blob: 9586223ac133ec2f1b916ef51ed0ed6b5171a646 [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 Colombetcfd97b92016-05-20 00:35:26 +000019#include "llvm/Support/BlockFrequency.h"
Quentin Colombete16f5612016-04-07 23:53:55 +000020#include "llvm/Support/Debug.h"
Quentin Colombet40ad5732016-04-07 18:19:27 +000021#include "llvm/Target/TargetSubtargetInfo.h"
Quentin Colombet8e8e85c2016-04-05 19:06:01 +000022
23#define DEBUG_TYPE "regbankselect"
24
25using namespace llvm;
26
27char RegBankSelect::ID = 0;
28INITIALIZE_PASS(RegBankSelect, "regbankselect",
29 "Assign register bank of generic virtual registers",
30 false, false);
31
Quentin Colombet46df7222016-05-20 16:55:35 +000032RegBankSelect::RegBankSelect(Mode RunningMode)
33 : MachineFunctionPass(ID), RBI(nullptr), MRI(nullptr),
34 OptMode(RunningMode) {
Quentin Colombet8e8e85c2016-04-05 19:06:01 +000035 initializeRegBankSelectPass(*PassRegistry::getPassRegistry());
36}
37
Quentin Colombet40ad5732016-04-07 18:19:27 +000038void RegBankSelect::init(MachineFunction &MF) {
39 RBI = MF.getSubtarget().getRegBankInfo();
40 assert(RBI && "Cannot work without RegisterBankInfo");
41 MRI = &MF.getRegInfo();
Quentin Colombetaac71a42016-04-07 21:32:23 +000042 TRI = MF.getSubtarget().getRegisterInfo();
Quentin Colombet46df7222016-05-20 16:55:35 +000043 assert(OptMode == Mode::Fast && "Non-fast mode not implemented");
Quentin Colombet40ad5732016-04-07 18:19:27 +000044 MIRBuilder.setMF(MF);
45}
46
47bool RegBankSelect::assignmentMatch(
Quentin Colombet0d77da42016-05-20 00:42:57 +000048 unsigned Reg, const RegisterBankInfo::ValueMapping &ValMapping,
49 bool &OnlyAssign) const {
50 // By default we assume we will have to repair something.
51 OnlyAssign = false;
Quentin Colombet40ad5732016-04-07 18:19:27 +000052 // Each part of a break down needs to end up in a different register.
53 // In other word, Reg assignement does not match.
54 if (ValMapping.BreakDown.size() > 1)
55 return false;
56
Quentin Colombet6d6d6af2016-04-08 16:48:16 +000057 const RegisterBank *CurRegBank = RBI->getRegBank(Reg, *MRI, *TRI);
58 const RegisterBank *DesiredRegBrank = ValMapping.BreakDown[0].RegBank;
Quentin Colombet0d77da42016-05-20 00:42:57 +000059 // Reg is free of assignment, a simple assignment will make the
60 // register bank to match.
61 OnlyAssign = CurRegBank == nullptr;
Quentin Colombet6d6d6af2016-04-08 16:48:16 +000062 DEBUG(dbgs() << "Does assignment already match: ";
63 if (CurRegBank) dbgs() << *CurRegBank; else dbgs() << "none";
64 dbgs() << " against ";
65 assert(DesiredRegBrank && "The mapping must be valid");
66 dbgs() << *DesiredRegBrank << '\n';);
67 return CurRegBank == DesiredRegBrank;
Quentin Colombet40ad5732016-04-07 18:19:27 +000068}
69
Quentin Colombetd84d00b2016-05-20 00:55:51 +000070void RegBankSelect::repairReg(
71 MachineOperand &MO, const RegisterBankInfo::ValueMapping &ValMapping,
72 RegBankSelect::RepairingPlacement &RepairPt,
73 const iterator_range<SmallVectorImpl<unsigned>::iterator> &NewVRegs) {
74 assert(ValMapping.BreakDown.size() == 1 && "Not yet implemented");
75 // Assume we are repairing a use and thus, the original reg will be
76 // the source of the repairing.
77 unsigned Src = MO.getReg();
78 unsigned Dst = *NewVRegs.begin();
79 if (ValMapping.BreakDown.size() == 1)
80 MO.setReg(Dst);
Quentin Colombet904a2c72016-04-12 00:12:59 +000081
Quentin Colombetd84d00b2016-05-20 00:55:51 +000082 // If we repair a definition, swap the source and destination for
83 // the repairing.
84 if (MO.isDef())
Quentin Colombet904a2c72016-04-12 00:12:59 +000085 std::swap(Src, Dst);
Quentin Colombet904a2c72016-04-12 00:12:59 +000086
Quentin Colombetd84d00b2016-05-20 00:55:51 +000087 assert((RepairPt.getNumInsertPoints() == 1 ||
88 TargetRegisterInfo::isPhysicalRegister(Dst)) &&
89 "We are about to create several defs for Dst");
Quentin Colombet904a2c72016-04-12 00:12:59 +000090
Quentin Colombetd84d00b2016-05-20 00:55:51 +000091 // Build the instruction used to repair, then clone it at the right places.
92 MachineInstr *MI = MIRBuilder.buildInstr(TargetOpcode::COPY, Dst, Src);
93 MI->removeFromParent();
94 DEBUG(dbgs() << "Copy: " << PrintReg(Src) << " to: " << PrintReg(Dst)
95 << '\n');
96 // TODO:
97 // Check if MI is legal. if not, we need to legalize all the
98 // instructions we are going to insert.
99 std::unique_ptr<MachineInstr *[]> NewInstrs(
100 new MachineInstr *[RepairPt.getNumInsertPoints()]);
101 bool IsFirst = true;
102 unsigned Idx = 0;
103 for (const std::unique_ptr<InsertPoint> &InsertPt : RepairPt) {
104 MachineInstr *CurMI;
105 if (IsFirst)
106 CurMI = MI;
107 else
108 CurMI = MIRBuilder.getMF().CloneMachineInstr(MI);
109 InsertPt->insert(*CurMI);
110 NewInstrs[Idx++] = CurMI;
111 IsFirst = false;
112 }
113 // TODO:
114 // Legalize NewInstrs if need be.
Quentin Colombet40ad5732016-04-07 18:19:27 +0000115}
116
Quentin Colombet904a2c72016-04-12 00:12:59 +0000117void RegBankSelect::setSafeInsertionPoint(MachineInstr &InsertPt, bool Before) {
118 // Check that we are not looking to insert before a phi.
119 // Indeed, we would need more information on what to do.
120 // By default that should be all the predecessors, but this is
121 // probably not what we want in general.
122 assert((!Before || !InsertPt.isPHI()) &&
123 "Insertion before phis not implemented");
124 // The same kind of observation hold for terminators if we try to
125 // insert after them.
126 assert((Before || !InsertPt.isTerminator()) &&
127 "Insertion after terminatos not implemented");
128 if (InsertPt.isPHI()) {
129 assert(!Before && "Not supported!!");
130 MachineBasicBlock *MBB = InsertPt.getParent();
131 assert(MBB && "Insertion point is not in a basic block");
132 MachineBasicBlock::iterator FirstNonPHIPt = MBB->getFirstNonPHI();
133 if (FirstNonPHIPt == MBB->end()) {
134 // If there is not any non-phi instruction, insert at the end of MBB.
135 MIRBuilder.setMBB(*MBB, /*Beginning*/ false);
136 return;
137 }
138 // The insertion point before the first non-phi instruction.
139 MIRBuilder.setInstr(*FirstNonPHIPt, /*Before*/ true);
140 return;
141 }
142 if (InsertPt.isTerminator()) {
143 MachineBasicBlock *MBB = InsertPt.getParent();
144 assert(MBB && "Insertion point is not in a basic block");
145 MIRBuilder.setInstr(*MBB->getFirstTerminator(), /*Before*/ true);
146 return;
147 }
148 MIRBuilder.setInstr(InsertPt, /*Before*/ Before);
149}
150
Quentin Colombetf75c2bf2016-05-20 16:36:12 +0000151void RegBankSelect::tryAvoidingSplit(
152 RegBankSelect::RepairingPlacement &RepairPt, const MachineOperand &MO,
153 const RegisterBankInfo::ValueMapping &ValMapping) const {
154 const MachineInstr &MI = *MO.getParent();
155 assert(RepairPt.hasSplit() && "We should not have to adjust for split");
156 // Splitting should only occur for PHIs or between terminators,
157 // because we only do local repairing.
158 assert((MI.isPHI() || MI.isTerminator()) && "Why do we split?");
159
160 assert(&MI.getOperand(RepairPt.getOpIdx()) == &MO &&
161 "Repairing placement does not match operand");
162
163 // If we need splitting for phis, that means it is because we
164 // could not find an insertion point before the terminators of
165 // the predecessor block for this argument. In other words,
166 // the input value is defined by one of the terminators.
167 assert((!MI.isPHI() || !MO.isDef()) && "Need split for phi def?");
168
169 // We split to repair the use of a phi or a terminator.
170 if (!MO.isDef()) {
171 if (MI.isTerminator()) {
172 assert(&MI != &(*MI.getParent()->getFirstTerminator()) &&
173 "Need to split for the first terminator?!");
174 } else {
175 // For the PHI case, the split may not be actually required.
176 // In the copy case, a phi is already a copy on the incoming edge,
177 // therefore there is no need to split.
178 if (ValMapping.BreakDown.size() == 1)
179 // This is a already a copy, there is nothing to do.
180 RepairPt.switchTo(RepairingPlacement::RepairingKind::Reassign);
181 }
182 return;
183 }
184
185 // At this point, we need to repair a defintion of a terminator.
186
187 // Technically we need to fix the def of MI on all outgoing
188 // edges of MI to keep the repairing local. In other words, we
189 // will create several definitions of the same register. This
190 // does not work for SSA unless that definition is a physical
191 // register.
192 // However, there are other cases where we can get away with
193 // that while still keeping the repairing local.
194 assert(MI.isTerminator() && MO.isDef() &&
195 "This code is for the def of a terminator");
196
197 // Since we use RPO traversal, if we need to repair a definition
198 // this means this definition could be:
199 // 1. Used by PHIs (i.e., this VReg has been visited as part of the
200 // uses of a phi.), or
201 // 2. Part of a target specific instruction (i.e., the target applied
202 // some register class constraints when creating the instruction.)
203 // If the constraints come for #2, the target said that another mapping
204 // is supported so we may just drop them. Indeed, if we do not change
205 // the number of registers holding that value, the uses will get fixed
206 // when we get to them.
207 // Uses in PHIs may have already been proceeded though.
208 // If the constraints come for #1, then, those are weak constraints and
209 // no actual uses may rely on them. However, the problem remains mainly
210 // the same as for #2. If the value stays in one register, we could
211 // just switch the register bank of the definition, but we would need to
212 // account for a repairing cost for each phi we silently change.
213 //
214 // In any case, if the value needs to be broken down into several
215 // registers, the repairing is not local anymore as we need to patch
216 // every uses to rebuild the value in just one register.
217 //
218 // To summarize:
219 // - If the value is in a physical register, we can do the split and
220 // fix locally.
221 // Otherwise if the value is in a virtual register:
222 // - If the value remains in one register, we do not have to split
223 // just switching the register bank would do, but we need to account
224 // in the repairing cost all the phi we changed.
225 // - If the value spans several registers, then we cannot do a local
226 // repairing.
227
228 // Check if this is a physical or virtual register.
229 unsigned Reg = MO.getReg();
230 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
231 // We are going to split every outgoing edges.
232 // Check that this is possible.
233 // FIXME: The machine representation is currently broken
234 // since it also several terminators in one basic block.
235 // Because of that we would technically need a way to get
236 // the targets of just one terminator to know which edges
237 // we have to split.
238 // Assert that we do not hit the ill-formed representation.
239
240 // If there are other terminators before that one, some of
241 // the outgoing edges may not be dominated by this definition.
242 assert(&MI == &(*MI.getParent()->getFirstTerminator()) &&
243 "Do not know which outgoing edges are relevant");
244 const MachineInstr *Next = MI.getNextNode();
245 assert((!Next || Next->isUnconditionalBranch()) &&
246 "Do not know where each terminator ends up");
247 if (Next)
248 // If the next terminator uses Reg, this means we have
249 // to split right after MI and thus we need a way to ask
250 // which outgoing edges are affected.
251 assert(!Next->readsRegister(Reg) && "Need to split between terminators");
252 // We will split all the edges and repair there.
253 } else {
254 // This is a virtual register defined by a terminator.
255 if (ValMapping.BreakDown.size() == 1) {
256 // There is nothing to repair, but we may actually lie on
257 // the repairing cost because of the PHIs already proceeded
258 // as already stated.
259 // Though the code will be correct.
260 assert(0 && "Repairing cost may not be accurate");
261 } else {
262 // We need to do non-local repairing. Basically, patch all
263 // the uses (i.e., phis) that we already proceeded.
264 // For now, just say this mapping is not possible.
265 RepairPt.switchTo(RepairingPlacement::RepairingKind::Impossible);
266 }
267 }
268}
269
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000270RegBankSelect::MappingCost RegBankSelect::computeMapping(
271 MachineInstr &MI, const RegisterBankInfo::InstructionMapping &InstrMapping,
272 SmallVectorImpl<RepairingPlacement> &RepairPts) {
Quentin Colombete16f5612016-04-07 23:53:55 +0000273
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000274 // If mapped with InstrMapping, MI will have the recorded cost.
275 MappingCost Cost(1);
276 bool Saturated = Cost.addLocalCost(InstrMapping.getCost());
277 assert(!Saturated && "Possible mapping saturated the cost");
278 DEBUG(dbgs() << "Evaluating mapping cost for: " << MI);
279 DEBUG(dbgs() << "With: " << InstrMapping << '\n');
280 RepairPts.clear();
281 // Moreover, to realize this mapping, the register bank of each operand must
282 // match this mapping. In other words, we may need to locally reassign the
283 // register banks. Account for that repairing cost as well.
284 // In this context, local means in the surrounding of MI.
285 for (unsigned OpIdx = 0, EndOpIdx = MI.getNumOperands(); OpIdx != EndOpIdx;
Quentin Colombet40ad5732016-04-07 18:19:27 +0000286 ++OpIdx) {
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000287 const MachineOperand &MO = MI.getOperand(OpIdx);
Quentin Colombet40ad5732016-04-07 18:19:27 +0000288 if (!MO.isReg())
289 continue;
290 unsigned Reg = MO.getReg();
291 if (!Reg)
292 continue;
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000293 DEBUG(dbgs() << "Opd" << OpIdx);
Quentin Colombet40ad5732016-04-07 18:19:27 +0000294 const RegisterBankInfo::ValueMapping &ValMapping =
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000295 InstrMapping.getOperandMapping(OpIdx);
296 // If Reg is already properly mapped, this is free.
297 bool Assign;
298 if (assignmentMatch(Reg, ValMapping, Assign)) {
299 DEBUG(dbgs() << " is free (match).\n");
Quentin Colombet40ad5732016-04-07 18:19:27 +0000300 continue;
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000301 }
302 if (Assign) {
303 DEBUG(dbgs() << " is free (simple assignment).\n");
304 RepairPts.emplace_back(RepairingPlacement(MI, OpIdx, *TRI, *this,
305 RepairingPlacement::Reassign));
306 continue;
Quentin Colombet40ad5732016-04-07 18:19:27 +0000307 }
Quentin Colombet904a2c72016-04-12 00:12:59 +0000308
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000309 // TODO:
310 // Ask the repairing module how much it would cost to get this mapping.
311 // Use: NewSources <- Val.
312 // Same size: copy.
313 // Different size: Src1, Src2, ... =
314 // extract_value Val, Src1Begin, Src1Len, Src2Begin, Src2Len, ...
315 // Def: Val <- NewDefs
316 // Same size: copy
317 // Different size: Val = build_sequence Defs1, Defs2, ...
318 // We should remember that this value is available somewhere else to
319 // coalesce the value.
Quentin Colombet904a2c72016-04-12 00:12:59 +0000320
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000321 // Find the insertion point for the repairing code.
322 RepairPts.emplace_back(
323 RepairingPlacement(MI, OpIdx, *TRI, *this, RepairingPlacement::Insert));
324 RepairingPlacement &RepairPt = RepairPts.back();
325
Quentin Colombetf75c2bf2016-05-20 16:36:12 +0000326 // If we need to split a basic block to materialize this insertion point,
327 // we may give a higher cost to this mapping.
328 // Nevertheless, we may get away with the split, so try that first.
329 if (RepairPt.hasSplit())
330 tryAvoidingSplit(RepairPt, MO, ValMapping);
331
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000332 // Check that the materialization of the repairing is possible.
333 if (!RepairPt.canMaterialize())
334 return MappingCost::ImpossibleCost();
335
336 // Account for the split cost and repair cost.
337 // Unless the cost is already saturated.
338 if (Saturated)
339 continue;
340
341 // Sums up the repairing cost of at each insertion point.
342 // TODO: Get the actual repairing cost.
343 uint64_t RepairCost = 1;
344 // Bias used for splitting: 5%.
345 const uint64_t PercentageForBias = 5;
346 uint64_t Bias = (RepairCost * PercentageForBias + 99) / 100;
347 // We should not need more than a couple of instructions to repair
348 // an assignment. In other words, the computation should not
349 // overflow because the repairing cost is free of basic block
350 // frequency.
351 assert(((RepairCost < RepairCost * PercentageForBias) &&
352 (RepairCost * PercentageForBias <
353 RepairCost * PercentageForBias + 99)) &&
354 "Repairing involves more than a billion of instructions?!");
355 for (const std::unique_ptr<InsertPoint> &InsertPt : RepairPt) {
356 assert(InsertPt->canMaterialize() && "We should not have made it here");
357 // We will applied some basic block frequency and those uses uint64_t.
358 if (!InsertPt->isSplit())
359 Saturated = Cost.addLocalCost(RepairCost);
360 else {
361 uint64_t CostForInsertPt = RepairCost;
362 // Again we shouldn't overflow here givent that
363 // CostForInsertPt is frequency free at this point.
364 assert(CostForInsertPt + Bias > CostForInsertPt &&
365 "Repairing + split bias overflows");
366 CostForInsertPt += Bias;
367 uint64_t PtCost = InsertPt->frequency(*this) * CostForInsertPt;
368 // Check if we just overflowed.
369 if ((Saturated = PtCost < CostForInsertPt))
370 Cost.saturate();
371 else
372 Saturated = Cost.addNonLocalCost(PtCost);
373 }
374 // No need to accumulate more cost information.
375 // We need to still gather the repairing information though.
376 if (Saturated)
377 break;
378 }
Quentin Colombet40ad5732016-04-07 18:19:27 +0000379 }
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000380 return Cost;
381}
382
383void RegBankSelect::applyMapping(
384 MachineInstr &MI, const RegisterBankInfo::InstructionMapping &InstrMapping,
385 SmallVectorImpl<RegBankSelect::RepairingPlacement> &RepairPts) {
386 assert(InstrMapping.getID() == RegisterBankInfo::DefaultMappingID &&
387 "Rewriting of MI not implemented yet");
388 // First, place the repairing code.
389 bool NeedRewrite = false;
390 SmallVector<unsigned, 8> NewVRegs;
391 for (RepairingPlacement &RepairPt : RepairPts) {
392 assert(RepairPt.canMaterialize() &&
393 RepairPt.getKind() != RepairingPlacement::Impossible &&
394 "This mapping is impossible");
395 assert(RepairPt.getKind() != RepairingPlacement::None &&
396 "This should not make its way in the list");
397 unsigned OpIdx = RepairPt.getOpIdx();
398 MachineOperand &MO = MI.getOperand(OpIdx);
399 const RegisterBankInfo::ValueMapping &ValMapping =
400 InstrMapping.getOperandMapping(OpIdx);
401 unsigned BreakDownSize = ValMapping.BreakDown.size();
402 unsigned Reg = MO.getReg();
403 NeedRewrite = BreakDownSize != 1;
404
405 switch (RepairPt.getKind()) {
406 case RepairingPlacement::Reassign:
407 assert(BreakDownSize == 1 &&
408 "Reassignment should only be for simple mapping");
409 MRI->setRegBank(Reg, *ValMapping.BreakDown[0].RegBank);
410 break;
411 case RepairingPlacement::Insert:
412 // We need as many new virtual registers as the number of partial mapping.
413 for (const RegisterBankInfo::PartialMapping &PartMap :
414 ValMapping.BreakDown) {
415 unsigned Tmp = MRI->createGenericVirtualRegister(PartMap.Length);
416 MRI->setRegBank(Tmp, *PartMap.RegBank);
417 NewVRegs.push_back(Tmp);
418 }
419 repairReg(MO, ValMapping, RepairPt,
420 make_range(NewVRegs.end() - BreakDownSize, NewVRegs.end()));
421 break;
422 default:
423 llvm_unreachable("Other kind should not happen");
424 }
425 }
426 // Second, rewrite the instruction.
427 (void)NeedRewrite;
428 assert(!NeedRewrite && "Not implemented yet");
429}
430
431void RegBankSelect::assignInstr(MachineInstr &MI) {
432 DEBUG(dbgs() << "Assign: " << MI);
433 RegisterBankInfo::InstructionMapping DefaultMapping =
434 RBI->getInstrMapping(MI);
435 // Remember the repairing placement for all the operands.
436 SmallVector<RepairingPlacement, 4> RepairPts;
437
438 MappingCost DefaultCost = computeMapping(MI, DefaultMapping, RepairPts);
439 (void)DefaultCost;
440 assert(DefaultCost != MappingCost::ImpossibleCost() &&
441 "Default mapping is not suited");
442
443 // Make sure the mapping is valid for MI.
444 assert(DefaultMapping.verify(MI) && "Invalid instruction mapping");
445
446 DEBUG(dbgs() << "Mapping: " << DefaultMapping << '\n');
447
448 applyMapping(MI, DefaultMapping, RepairPts);
449
Quentin Colombete16f5612016-04-07 23:53:55 +0000450 DEBUG(dbgs() << "Assigned: " << MI);
Quentin Colombet40ad5732016-04-07 18:19:27 +0000451}
452
Quentin Colombet8e8e85c2016-04-05 19:06:01 +0000453bool RegBankSelect::runOnMachineFunction(MachineFunction &MF) {
Quentin Colombete16f5612016-04-07 23:53:55 +0000454 DEBUG(dbgs() << "Assign register banks for: " << MF.getName() << '\n');
Quentin Colombet40ad5732016-04-07 18:19:27 +0000455 init(MF);
456 // Walk the function and assign register banks to all operands.
Quentin Colombetab8c21f2016-04-08 17:19:10 +0000457 // Use a RPOT to make sure all registers are assigned before we choose
458 // the best mapping of the current instruction.
459 ReversePostOrderTraversal<MachineFunction*> RPOT(&MF);
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000460 for (MachineBasicBlock *MBB : RPOT) {
461 // Set a sensible insertion point so that subsequent calls to
462 // MIRBuilder.
463 MIRBuilder.setMBB(*MBB);
Quentin Colombetab8c21f2016-04-08 17:19:10 +0000464 for (MachineInstr &MI : *MBB)
Quentin Colombet40ad5732016-04-07 18:19:27 +0000465 assignInstr(MI);
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000466 }
Quentin Colombet8e8e85c2016-04-05 19:06:01 +0000467 return false;
468}
Quentin Colombetcfd97b92016-05-20 00:35:26 +0000469
470//------------------------------------------------------------------------------
Quentin Colombet55650752016-05-20 00:49:10 +0000471// Helper Classes Implementation
Quentin Colombetcfd97b92016-05-20 00:35:26 +0000472//------------------------------------------------------------------------------
Quentin Colombet55650752016-05-20 00:49:10 +0000473RegBankSelect::RepairingPlacement::RepairingPlacement(
474 MachineInstr &MI, unsigned OpIdx, const TargetRegisterInfo &TRI, Pass &P,
475 RepairingPlacement::RepairingKind Kind)
476 // Default is, we are going to insert code to repair OpIdx.
477 : Kind(Kind),
478 OpIdx(OpIdx),
479 CanMaterialize(Kind != RepairingKind::Impossible),
480 HasSplit(false),
481 P(P) {
482 const MachineOperand &MO = MI.getOperand(OpIdx);
483 assert(MO.isReg() && "Trying to repair a non-reg operand");
484
485 if (Kind != RepairingKind::Insert)
486 return;
487
488 // Repairings for definitions happen after MI, uses happen before.
489 bool Before = !MO.isDef();
490
491 // Check if we are done with MI.
492 if (!MI.isPHI() && !MI.isTerminator()) {
493 addInsertPoint(MI, Before);
494 // We are done with the initialization.
495 return;
496 }
497
498 // Now, look for the special cases.
499 if (MI.isPHI()) {
500 // - PHI must be the first instructions:
501 // * Before, we have to split the related incoming edge.
502 // * After, move the insertion point past the last phi.
503 if (!Before) {
504 MachineBasicBlock::iterator It = MI.getParent()->getFirstNonPHI();
505 if (It != MI.getParent()->end())
506 addInsertPoint(*It, /*Before*/ true);
507 else
508 addInsertPoint(*(--It), /*Before*/ false);
509 return;
510 }
511 // We repair a use of a phi, we may need to split the related edge.
512 MachineBasicBlock &Pred = *MI.getOperand(OpIdx + 1).getMBB();
513 // Check if we can move the insertion point prior to the
514 // terminators of the predecessor.
515 unsigned Reg = MO.getReg();
516 MachineBasicBlock::iterator It = Pred.getLastNonDebugInstr();
517 for (auto Begin = Pred.begin(); It != Begin && It->isTerminator(); --It)
518 if (It->modifiesRegister(Reg, &TRI)) {
519 // We cannot hoist the repairing code in the predecessor.
520 // Split the edge.
521 addInsertPoint(Pred, *MI.getParent());
522 return;
523 }
524 // At this point, we can insert in Pred.
525
526 // - If It is invalid, Pred is empty and we can insert in Pred
527 // wherever we want.
528 // - If It is valid, It is the first non-terminator, insert after It.
529 if (It == Pred.end())
530 addInsertPoint(Pred, /*Beginning*/ false);
531 else
532 addInsertPoint(*It, /*Before*/ false);
533 } else {
534 // - Terminators must be the last instructions:
535 // * Before, move the insert point before the first terminator.
536 // * After, we have to split the outcoming edges.
537 unsigned Reg = MO.getReg();
538 if (Before) {
539 // Check whether Reg is defined by any terminator.
540 MachineBasicBlock::iterator It = MI;
541 for (auto Begin = MI.getParent()->begin();
542 --It != Begin && It->isTerminator();)
543 if (It->modifiesRegister(Reg, &TRI)) {
544 // Insert the repairing code right after the definition.
545 addInsertPoint(*It, /*Before*/ false);
546 return;
547 }
548 addInsertPoint(*It, /*Before*/ true);
549 return;
550 }
551 // Make sure Reg is not redefined by other terminators, otherwise
552 // we do not know how to split.
553 for (MachineBasicBlock::iterator It = MI, End = MI.getParent()->end();
554 ++It != End;)
555 // The machine verifier should reject this kind of code.
556 assert(It->modifiesRegister(Reg, &TRI) && "Do not know where to split");
557 // Split each outcoming edges.
558 MachineBasicBlock &Src = *MI.getParent();
559 for (auto &Succ : Src.successors())
560 addInsertPoint(Src, Succ);
561 }
562}
563
564void RegBankSelect::RepairingPlacement::addInsertPoint(MachineInstr &MI,
565 bool Before) {
566 addInsertPoint(*new InstrInsertPoint(MI, Before));
567}
568
569void RegBankSelect::RepairingPlacement::addInsertPoint(MachineBasicBlock &MBB,
570 bool Beginning) {
571 addInsertPoint(*new MBBInsertPoint(MBB, Beginning));
572}
573
574void RegBankSelect::RepairingPlacement::addInsertPoint(MachineBasicBlock &Src,
575 MachineBasicBlock &Dst) {
576 addInsertPoint(*new EdgeInsertPoint(Src, Dst, P));
577}
578
579void RegBankSelect::RepairingPlacement::addInsertPoint(
580 RegBankSelect::InsertPoint &Point) {
581 CanMaterialize &= Point.canMaterialize();
582 HasSplit |= Point.isSplit();
583 InsertPoints.emplace_back(&Point);
584}
585
586RegBankSelect::InstrInsertPoint::InstrInsertPoint(MachineInstr &Instr,
587 bool Before)
588 : InsertPoint(), Instr(Instr), Before(Before) {
589 // Since we do not support splitting, we do not need to update
590 // liveness and such, so do not do anything with P.
591 assert((!Before || !Instr.isPHI()) &&
592 "Splitting before phis requires more points");
593 assert((!Before || !Instr.getNextNode() || !Instr.getNextNode()->isPHI()) &&
594 "Splitting between phis does not make sense");
595}
596
597void RegBankSelect::InstrInsertPoint::materialize() {
598 if (isSplit()) {
599 // Slice and return the beginning of the new block.
600 // If we need to split between the terminators, we theoritically
601 // need to know where the first and second set of terminators end
602 // to update the successors properly.
603 // Now, in pratice, we should have a maximum of 2 branch
604 // instructions; one conditional and one unconditional. Therefore
605 // we know how to update the successor by looking at the target of
606 // the unconditional branch.
607 // If we end up splitting at some point, then, we should update
608 // the liveness information and such. I.e., we would need to
609 // access P here.
610 // The machine verifier should actually make sure such cases
611 // cannot happen.
612 llvm_unreachable("Not yet implemented");
613 }
614 // Otherwise the insertion point is just the current or next
615 // instruction depending on Before. I.e., there is nothing to do
616 // here.
617}
618
619bool RegBankSelect::InstrInsertPoint::isSplit() const {
620 // If the insertion point is after a terminator, we need to split.
621 if (!Before)
622 return Instr.isTerminator();
623 // If we insert before an instruction that is after a terminator,
624 // we are still after a terminator.
625 return Instr.getPrevNode() && Instr.getPrevNode()->isTerminator();
626}
627
628uint64_t RegBankSelect::InstrInsertPoint::frequency(const Pass &P) const {
629 // Even if we need to split, because we insert between terminators,
630 // this split has actually the same frequency as the instruction.
631 const MachineBlockFrequencyInfo *MBFI =
632 P.getAnalysisIfAvailable<MachineBlockFrequencyInfo>();
633 if (!MBFI)
634 return 1;
635 return MBFI->getBlockFreq(Instr.getParent()).getFrequency();
636}
637
638uint64_t RegBankSelect::MBBInsertPoint::frequency(const Pass &P) const {
639 const MachineBlockFrequencyInfo *MBFI =
640 P.getAnalysisIfAvailable<MachineBlockFrequencyInfo>();
641 if (!MBFI)
642 return 1;
643 return MBFI->getBlockFreq(&MBB).getFrequency();
644}
645
646void RegBankSelect::EdgeInsertPoint::materialize() {
647 // If we end up repairing twice at the same place before materializing the
648 // insertion point, we may think we have to split an edge twice.
649 // We should have a factory for the insert point such that identical points
650 // are the same instance.
651 assert(Src.isSuccessor(DstOrSplit) && DstOrSplit->isPredecessor(&Src) &&
652 "This point has already been split");
653 MachineBasicBlock *NewBB = Src.SplitCriticalEdge(DstOrSplit, P);
654 assert(NewBB && "Invalid call to materialize");
655 // We reuse the destination block to hold the information of the new block.
656 DstOrSplit = NewBB;
657}
658
659uint64_t RegBankSelect::EdgeInsertPoint::frequency(const Pass &P) const {
660 const MachineBlockFrequencyInfo *MBFI =
661 P.getAnalysisIfAvailable<MachineBlockFrequencyInfo>();
662 if (!MBFI)
663 return 1;
664 if (WasMaterialized)
665 return MBFI->getBlockFreq(DstOrSplit).getFrequency();
666
667 const MachineBranchProbabilityInfo *MBPI =
668 P.getAnalysisIfAvailable<MachineBranchProbabilityInfo>();
669 if (!MBPI)
670 return 1;
671 // The basic block will be on the edge.
672 return (MBFI->getBlockFreq(&Src) * MBPI->getEdgeProbability(&Src, DstOrSplit))
673 .getFrequency();
674}
675
676bool RegBankSelect::EdgeInsertPoint::canMaterialize() const {
677 // If this is not a critical edge, we should not have used this insert
678 // point. Indeed, either the successor or the predecessor should
679 // have do.
680 assert(Src.succ_size() > 1 && DstOrSplit->pred_size() > 1 &&
681 "Edge is not critical");
682 return Src.canSplitCriticalEdge(DstOrSplit);
683}
684
Quentin Colombetcfd97b92016-05-20 00:35:26 +0000685RegBankSelect::MappingCost::MappingCost(const BlockFrequency &LocalFreq)
686 : LocalCost(0), NonLocalCost(0), LocalFreq(LocalFreq.getFrequency()) {}
687
688bool RegBankSelect::MappingCost::addLocalCost(uint64_t Cost) {
689 // Check if this overflows.
690 if (LocalCost + Cost < LocalCost) {
691 saturate();
692 return true;
693 }
694 LocalCost += Cost;
695 return isSaturated();
696}
697
698bool RegBankSelect::MappingCost::addNonLocalCost(uint64_t Cost) {
699 // Check if this overflows.
700 if (NonLocalCost + Cost < NonLocalCost) {
701 saturate();
702 return true;
703 }
704 NonLocalCost += Cost;
705 return isSaturated();
706}
707
708bool RegBankSelect::MappingCost::isSaturated() const {
709 return LocalCost == UINT64_MAX - 1 && NonLocalCost == UINT64_MAX &&
710 LocalFreq == UINT64_MAX;
711}
712
713void RegBankSelect::MappingCost::saturate() {
714 *this = ImpossibleCost();
715 --LocalCost;
716}
717
718RegBankSelect::MappingCost RegBankSelect::MappingCost::ImpossibleCost() {
719 return MappingCost(UINT64_MAX, UINT64_MAX, UINT64_MAX);
720}
721
722bool RegBankSelect::MappingCost::operator<(const MappingCost &Cost) const {
723 // Sort out the easy cases.
724 if (*this == Cost)
725 return false;
726 // If one is impossible to realize the other is cheaper unless it is
727 // impossible as well.
728 if ((*this == ImpossibleCost()) || (Cost == ImpossibleCost()))
729 return (*this == ImpossibleCost()) < (Cost == ImpossibleCost());
730 // If one is saturated the other is cheaper, unless it is saturated
731 // as well.
732 if (isSaturated() || Cost.isSaturated())
733 return isSaturated() < Cost.isSaturated();
734 // At this point we know both costs hold sensible values.
735
736 // If both values have a different base frequency, there is no much
737 // we can do but to scale everything.
738 // However, if they have the same base frequency we can avoid making
739 // complicated computation.
740 uint64_t ThisLocalAdjust;
741 uint64_t OtherLocalAdjust;
742 if (LLVM_LIKELY(LocalFreq == Cost.LocalFreq)) {
743
744 // At this point, we know the local costs are comparable.
745 // Do the case that do not involve potential overflow first.
746 if (NonLocalCost == Cost.NonLocalCost)
747 // Since the non-local costs do not discriminate on the result,
748 // just compare the local costs.
749 return LocalCost < Cost.LocalCost;
750
751 // The base costs are comparable so we may only keep the relative
752 // value to increase our chances of avoiding overflows.
753 ThisLocalAdjust = 0;
754 OtherLocalAdjust = 0;
755 if (LocalCost < Cost.LocalCost)
756 OtherLocalAdjust = Cost.LocalCost - LocalCost;
757 else
758 ThisLocalAdjust = LocalCost - Cost.LocalCost;
759
760 } else {
761 ThisLocalAdjust = LocalCost;
762 OtherLocalAdjust = Cost.LocalCost;
763 }
764
765 // The non-local costs are comparable, just keep the relative value.
766 uint64_t ThisNonLocalAdjust = 0;
767 uint64_t OtherNonLocalAdjust = 0;
768 if (NonLocalCost < Cost.NonLocalCost)
769 OtherNonLocalAdjust = Cost.NonLocalCost - NonLocalCost;
770 else
771 ThisNonLocalAdjust = NonLocalCost - Cost.NonLocalCost;
772 // Scale everything to make them comparable.
773 uint64_t ThisScaledCost = ThisLocalAdjust * LocalFreq;
774 // Check for overflow on that operation.
775 bool ThisOverflows = ThisLocalAdjust && (ThisScaledCost < ThisLocalAdjust ||
776 ThisScaledCost < LocalFreq);
777 uint64_t OtherScaledCost = OtherLocalAdjust * Cost.LocalFreq;
778 // Check for overflow on the last operation.
779 bool OtherOverflows =
780 OtherLocalAdjust &&
781 (OtherScaledCost < OtherLocalAdjust || OtherScaledCost < Cost.LocalFreq);
782 // Add the non-local costs.
783 ThisOverflows |= ThisNonLocalAdjust &&
784 ThisScaledCost + ThisNonLocalAdjust < ThisNonLocalAdjust;
785 ThisScaledCost += ThisNonLocalAdjust;
786 OtherOverflows |= OtherNonLocalAdjust &&
787 OtherScaledCost + OtherNonLocalAdjust < OtherNonLocalAdjust;
788 OtherScaledCost += OtherNonLocalAdjust;
789 // If both overflows, we cannot compare without additional
790 // precision, e.g., APInt. Just give up on that case.
791 if (ThisOverflows && OtherOverflows)
792 return false;
793 // If one overflows but not the other, we can still compare.
794 if (ThisOverflows || OtherOverflows)
795 return ThisOverflows < OtherOverflows;
796 // Otherwise, just compare the values.
797 return ThisScaledCost < OtherScaledCost;
798}
799
800bool RegBankSelect::MappingCost::operator==(const MappingCost &Cost) const {
801 return LocalCost == Cost.LocalCost && NonLocalCost == Cost.NonLocalCost &&
802 LocalFreq == Cost.LocalFreq;
803}