blob: 34843b52dc91b8981ef393e453641ebe7717ec5d [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"
Ahmed Bougacha24d0d4d2016-08-02 15:10:32 +000015#include "llvm/CodeGen/GlobalISel/MachineLegalizer.h"
Quentin Colombet40ad5732016-04-07 18:19:27 +000016#include "llvm/CodeGen/GlobalISel/RegisterBank.h"
Quentin Colombet55650752016-05-20 00:49:10 +000017#include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
18#include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
Quentin Colombet40ad5732016-04-07 18:19:27 +000019#include "llvm/CodeGen/MachineRegisterInfo.h"
Quentin Colombetacb857b2016-08-27 02:38:27 +000020#include "llvm/CodeGen/TargetPassConfig.h"
Quentin Colombeta5530122016-05-20 17:36:54 +000021#include "llvm/IR/Function.h"
Quentin Colombetcfd97b92016-05-20 00:35:26 +000022#include "llvm/Support/BlockFrequency.h"
Quentin Colombeta41272f2016-06-08 15:49:23 +000023#include "llvm/Support/CommandLine.h"
Quentin Colombete16f5612016-04-07 23:53:55 +000024#include "llvm/Support/Debug.h"
Quentin Colombet40ad5732016-04-07 18:19:27 +000025#include "llvm/Target/TargetSubtargetInfo.h"
Quentin Colombet8e8e85c2016-04-05 19:06:01 +000026
27#define DEBUG_TYPE "regbankselect"
28
29using namespace llvm;
30
Quentin Colombeta41272f2016-06-08 15:49:23 +000031static cl::opt<RegBankSelect::Mode> RegBankSelectMode(
32 cl::desc("Mode of the RegBankSelect pass"), cl::Hidden, cl::Optional,
33 cl::values(clEnumValN(RegBankSelect::Mode::Fast, "regbankselect-fast",
34 "Run the Fast mode (default mapping)"),
35 clEnumValN(RegBankSelect::Mode::Greedy, "regbankselect-greedy",
36 "Use the Greedy mode (best local mapping)"),
37 clEnumValEnd));
38
Quentin Colombet8e8e85c2016-04-05 19:06:01 +000039char RegBankSelect::ID = 0;
Quentin Colombetc13ea882016-09-23 17:50:06 +000040INITIALIZE_PASS_BEGIN(RegBankSelect, DEBUG_TYPE,
Quentin Colombet25fcef72016-05-20 17:54:09 +000041 "Assign register bank of generic virtual registers",
42 false, false);
43INITIALIZE_PASS_DEPENDENCY(MachineBlockFrequencyInfo)
44INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
Quentin Colombetacb857b2016-08-27 02:38:27 +000045INITIALIZE_PASS_DEPENDENCY(TargetPassConfig)
Quentin Colombetc13ea882016-09-23 17:50:06 +000046INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE,
Quentin Colombet25fcef72016-05-20 17:54:09 +000047 "Assign register bank of generic virtual registers", false,
Tim Northover884b47e2016-07-26 03:29:18 +000048 false)
Quentin Colombet8e8e85c2016-04-05 19:06:01 +000049
Quentin Colombet46df7222016-05-20 16:55:35 +000050RegBankSelect::RegBankSelect(Mode RunningMode)
Quentin Colombet25fcef72016-05-20 17:54:09 +000051 : MachineFunctionPass(ID), RBI(nullptr), MRI(nullptr), TRI(nullptr),
52 MBFI(nullptr), MBPI(nullptr), OptMode(RunningMode) {
Quentin Colombet8e8e85c2016-04-05 19:06:01 +000053 initializeRegBankSelectPass(*PassRegistry::getPassRegistry());
Quentin Colombeta41272f2016-06-08 15:49:23 +000054 if (RegBankSelectMode.getNumOccurrences() != 0) {
55 OptMode = RegBankSelectMode;
56 if (RegBankSelectMode != RunningMode)
57 DEBUG(dbgs() << "RegBankSelect mode overrided by command line\n");
58 }
Quentin Colombet8e8e85c2016-04-05 19:06:01 +000059}
60
Quentin Colombet40ad5732016-04-07 18:19:27 +000061void RegBankSelect::init(MachineFunction &MF) {
62 RBI = MF.getSubtarget().getRegBankInfo();
63 assert(RBI && "Cannot work without RegisterBankInfo");
64 MRI = &MF.getRegInfo();
Quentin Colombetaac71a42016-04-07 21:32:23 +000065 TRI = MF.getSubtarget().getRegisterInfo();
Quentin Colombetacb857b2016-08-27 02:38:27 +000066 TPC = &getAnalysis<TargetPassConfig>();
Quentin Colombet25fcef72016-05-20 17:54:09 +000067 if (OptMode != Mode::Fast) {
68 MBFI = &getAnalysis<MachineBlockFrequencyInfo>();
69 MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
70 } else {
71 MBFI = nullptr;
72 MBPI = nullptr;
73 }
Quentin Colombet40ad5732016-04-07 18:19:27 +000074 MIRBuilder.setMF(MF);
75}
76
Quentin Colombet25fcef72016-05-20 17:54:09 +000077void RegBankSelect::getAnalysisUsage(AnalysisUsage &AU) const {
78 if (OptMode != Mode::Fast) {
79 // We could preserve the information from these two analysis but
80 // the APIs do not allow to do so yet.
81 AU.addRequired<MachineBlockFrequencyInfo>();
82 AU.addRequired<MachineBranchProbabilityInfo>();
83 }
Quentin Colombetacb857b2016-08-27 02:38:27 +000084 AU.addRequired<TargetPassConfig>();
Quentin Colombet25fcef72016-05-20 17:54:09 +000085 MachineFunctionPass::getAnalysisUsage(AU);
86}
87
Quentin Colombet40ad5732016-04-07 18:19:27 +000088bool RegBankSelect::assignmentMatch(
Quentin Colombet0d77da42016-05-20 00:42:57 +000089 unsigned Reg, const RegisterBankInfo::ValueMapping &ValMapping,
90 bool &OnlyAssign) const {
91 // By default we assume we will have to repair something.
92 OnlyAssign = false;
Quentin Colombet40ad5732016-04-07 18:19:27 +000093 // Each part of a break down needs to end up in a different register.
94 // In other word, Reg assignement does not match.
Quentin Colombet0afa7d62016-09-23 00:14:30 +000095 if (ValMapping.NumBreakDowns > 1)
Quentin Colombet40ad5732016-04-07 18:19:27 +000096 return false;
97
Quentin Colombet6d6d6af2016-04-08 16:48:16 +000098 const RegisterBank *CurRegBank = RBI->getRegBank(Reg, *MRI, *TRI);
99 const RegisterBank *DesiredRegBrank = ValMapping.BreakDown[0].RegBank;
Quentin Colombet0d77da42016-05-20 00:42:57 +0000100 // Reg is free of assignment, a simple assignment will make the
101 // register bank to match.
102 OnlyAssign = CurRegBank == nullptr;
Quentin Colombet6d6d6af2016-04-08 16:48:16 +0000103 DEBUG(dbgs() << "Does assignment already match: ";
104 if (CurRegBank) dbgs() << *CurRegBank; else dbgs() << "none";
105 dbgs() << " against ";
106 assert(DesiredRegBrank && "The mapping must be valid");
107 dbgs() << *DesiredRegBrank << '\n';);
108 return CurRegBank == DesiredRegBrank;
Quentin Colombet40ad5732016-04-07 18:19:27 +0000109}
110
Quentin Colombetacb857b2016-08-27 02:38:27 +0000111bool RegBankSelect::repairReg(
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000112 MachineOperand &MO, const RegisterBankInfo::ValueMapping &ValMapping,
113 RegBankSelect::RepairingPlacement &RepairPt,
Quentin Colombet06ef4e22016-06-08 16:24:55 +0000114 const iterator_range<SmallVectorImpl<unsigned>::const_iterator> &NewVRegs) {
Quentin Colombet0afa7d62016-09-23 00:14:30 +0000115 if (ValMapping.NumBreakDowns != 1 && !TPC->isGlobalISelAbortEnabled())
Quentin Colombetacb857b2016-08-27 02:38:27 +0000116 return false;
Quentin Colombet0afa7d62016-09-23 00:14:30 +0000117 assert(ValMapping.NumBreakDowns == 1 && "Not yet implemented");
Quentin Colombetf33e3652016-06-08 16:30:55 +0000118 // An empty range of new register means no repairing.
119 assert(NewVRegs.begin() != NewVRegs.end() && "We should not have to repair");
120
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000121 // Assume we are repairing a use and thus, the original reg will be
122 // the source of the repairing.
123 unsigned Src = MO.getReg();
124 unsigned Dst = *NewVRegs.begin();
Quentin Colombet904a2c72016-04-12 00:12:59 +0000125
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000126 // If we repair a definition, swap the source and destination for
127 // the repairing.
128 if (MO.isDef())
Quentin Colombet904a2c72016-04-12 00:12:59 +0000129 std::swap(Src, Dst);
Quentin Colombet904a2c72016-04-12 00:12:59 +0000130
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000131 assert((RepairPt.getNumInsertPoints() == 1 ||
132 TargetRegisterInfo::isPhysicalRegister(Dst)) &&
133 "We are about to create several defs for Dst");
Quentin Colombet904a2c72016-04-12 00:12:59 +0000134
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000135 // Build the instruction used to repair, then clone it at the right places.
Tim Northover756eca32016-07-26 16:45:30 +0000136 MachineInstr *MI = MIRBuilder.buildCopy(Dst, Src);
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000137 MI->removeFromParent();
138 DEBUG(dbgs() << "Copy: " << PrintReg(Src) << " to: " << PrintReg(Dst)
139 << '\n');
140 // TODO:
141 // Check if MI is legal. if not, we need to legalize all the
142 // instructions we are going to insert.
143 std::unique_ptr<MachineInstr *[]> NewInstrs(
144 new MachineInstr *[RepairPt.getNumInsertPoints()]);
145 bool IsFirst = true;
146 unsigned Idx = 0;
147 for (const std::unique_ptr<InsertPoint> &InsertPt : RepairPt) {
148 MachineInstr *CurMI;
149 if (IsFirst)
150 CurMI = MI;
151 else
152 CurMI = MIRBuilder.getMF().CloneMachineInstr(MI);
153 InsertPt->insert(*CurMI);
154 NewInstrs[Idx++] = CurMI;
155 IsFirst = false;
156 }
157 // TODO:
158 // Legalize NewInstrs if need be.
Quentin Colombetacb857b2016-08-27 02:38:27 +0000159 return true;
Quentin Colombet40ad5732016-04-07 18:19:27 +0000160}
161
Quentin Colombetf2723a22016-05-21 01:43:25 +0000162uint64_t RegBankSelect::getRepairCost(
163 const MachineOperand &MO,
164 const RegisterBankInfo::ValueMapping &ValMapping) const {
165 assert(MO.isReg() && "We should only repair register operand");
Quentin Colombet0afa7d62016-09-23 00:14:30 +0000166 assert(ValMapping.NumBreakDowns && "Nothing to map??");
Quentin Colombetf2723a22016-05-21 01:43:25 +0000167
Quentin Colombet0afa7d62016-09-23 00:14:30 +0000168 bool IsSameNumOfValues = ValMapping.NumBreakDowns == 1;
Quentin Colombetf2723a22016-05-21 01:43:25 +0000169 const RegisterBank *CurRegBank = RBI->getRegBank(MO.getReg(), *MRI, *TRI);
170 // If MO does not have a register bank, we should have just been
171 // able to set one unless we have to break the value down.
172 assert((!IsSameNumOfValues || CurRegBank) && "We should not have to repair");
173 // Def: Val <- NewDefs
174 // Same number of values: copy
175 // Different number: Val = build_sequence Defs1, Defs2, ...
176 // Use: NewSources <- Val.
177 // Same number of values: copy.
178 // Different number: Src1, Src2, ... =
179 // extract_value Val, Src1Begin, Src1Len, Src2Begin, Src2Len, ...
180 // We should remember that this value is available somewhere else to
181 // coalesce the value.
182
183 if (IsSameNumOfValues) {
184 const RegisterBank *DesiredRegBrank = ValMapping.BreakDown[0].RegBank;
185 // If we repair a definition, swap the source and destination for
186 // the repairing.
187 if (MO.isDef())
188 std::swap(CurRegBank, DesiredRegBrank);
Quentin Colombetd6886bd2016-06-08 17:39:43 +0000189 // TODO: It may be possible to actually avoid the copy.
190 // If we repair something where the source is defined by a copy
191 // and the source of that copy is on the right bank, we can reuse
192 // it for free.
193 // E.g.,
194 // RegToRepair<BankA> = copy AlternativeSrc<BankB>
195 // = op RegToRepair<BankA>
196 // We can simply propagate AlternativeSrc instead of copying RegToRepair
197 // into a new virtual register.
198 // We would also need to propagate this information in the
199 // repairing placement.
Quentin Colombetcfbdee22016-06-08 01:11:03 +0000200 unsigned Cost =
201 RBI->copyCost(*DesiredRegBrank, *CurRegBank,
202 RegisterBankInfo::getSizeInBits(MO.getReg(), *MRI, *TRI));
Quentin Colombetf2723a22016-05-21 01:43:25 +0000203 // TODO: use a dedicated constant for ImpossibleCost.
204 if (Cost != UINT_MAX)
205 return Cost;
Quentin Colombetacb857b2016-08-27 02:38:27 +0000206 assert(!TPC->isGlobalISelAbortEnabled() &&
207 "Legalization not available yet");
Quentin Colombetf2723a22016-05-21 01:43:25 +0000208 // Return the legalization cost of that repairing.
209 }
Quentin Colombetacb857b2016-08-27 02:38:27 +0000210 assert(!TPC->isGlobalISelAbortEnabled() &&
211 "Complex repairing not implemented yet");
212 return UINT_MAX;
Quentin Colombetf2723a22016-05-21 01:43:25 +0000213}
214
Quentin Colombet79fe1be2016-05-20 18:37:33 +0000215RegisterBankInfo::InstructionMapping &RegBankSelect::findBestMapping(
216 MachineInstr &MI, RegisterBankInfo::InstructionMappings &PossibleMappings,
217 SmallVectorImpl<RepairingPlacement> &RepairPts) {
Quentin Colombetacb857b2016-08-27 02:38:27 +0000218 assert(!PossibleMappings.empty() &&
219 "Do not know how to map this instruction");
Quentin Colombet79fe1be2016-05-20 18:37:33 +0000220
221 RegisterBankInfo::InstructionMapping *BestMapping = nullptr;
222 MappingCost Cost = MappingCost::ImpossibleCost();
223 SmallVector<RepairingPlacement, 4> LocalRepairPts;
224 for (RegisterBankInfo::InstructionMapping &CurMapping : PossibleMappings) {
225 MappingCost CurCost = computeMapping(MI, CurMapping, LocalRepairPts, &Cost);
226 if (CurCost < Cost) {
227 Cost = CurCost;
228 BestMapping = &CurMapping;
229 RepairPts.clear();
230 for (RepairingPlacement &RepairPt : LocalRepairPts)
231 RepairPts.emplace_back(std::move(RepairPt));
232 }
233 }
Quentin Colombetacb857b2016-08-27 02:38:27 +0000234 if (!BestMapping && !TPC->isGlobalISelAbortEnabled()) {
235 // If none of the mapping worked that means they are all impossible.
236 // Thus, pick the first one and set an impossible repairing point.
237 // It will trigger the failed isel mode.
238 BestMapping = &(*PossibleMappings.begin());
239 RepairPts.emplace_back(
240 RepairingPlacement(MI, 0, *TRI, *this, RepairingPlacement::Impossible));
241 } else
242 assert(BestMapping && "No suitable mapping for instruction");
Quentin Colombet79fe1be2016-05-20 18:37:33 +0000243 return *BestMapping;
244}
245
Quentin Colombetf75c2bf2016-05-20 16:36:12 +0000246void RegBankSelect::tryAvoidingSplit(
247 RegBankSelect::RepairingPlacement &RepairPt, const MachineOperand &MO,
248 const RegisterBankInfo::ValueMapping &ValMapping) const {
249 const MachineInstr &MI = *MO.getParent();
250 assert(RepairPt.hasSplit() && "We should not have to adjust for split");
251 // Splitting should only occur for PHIs or between terminators,
252 // because we only do local repairing.
253 assert((MI.isPHI() || MI.isTerminator()) && "Why do we split?");
254
255 assert(&MI.getOperand(RepairPt.getOpIdx()) == &MO &&
256 "Repairing placement does not match operand");
257
258 // If we need splitting for phis, that means it is because we
259 // could not find an insertion point before the terminators of
260 // the predecessor block for this argument. In other words,
261 // the input value is defined by one of the terminators.
262 assert((!MI.isPHI() || !MO.isDef()) && "Need split for phi def?");
263
264 // We split to repair the use of a phi or a terminator.
265 if (!MO.isDef()) {
266 if (MI.isTerminator()) {
267 assert(&MI != &(*MI.getParent()->getFirstTerminator()) &&
268 "Need to split for the first terminator?!");
269 } else {
270 // For the PHI case, the split may not be actually required.
271 // In the copy case, a phi is already a copy on the incoming edge,
272 // therefore there is no need to split.
Quentin Colombet0afa7d62016-09-23 00:14:30 +0000273 if (ValMapping.NumBreakDowns == 1)
Quentin Colombetf75c2bf2016-05-20 16:36:12 +0000274 // This is a already a copy, there is nothing to do.
275 RepairPt.switchTo(RepairingPlacement::RepairingKind::Reassign);
276 }
277 return;
278 }
279
280 // At this point, we need to repair a defintion of a terminator.
281
282 // Technically we need to fix the def of MI on all outgoing
283 // edges of MI to keep the repairing local. In other words, we
284 // will create several definitions of the same register. This
285 // does not work for SSA unless that definition is a physical
286 // register.
287 // However, there are other cases where we can get away with
288 // that while still keeping the repairing local.
289 assert(MI.isTerminator() && MO.isDef() &&
290 "This code is for the def of a terminator");
291
292 // Since we use RPO traversal, if we need to repair a definition
293 // this means this definition could be:
294 // 1. Used by PHIs (i.e., this VReg has been visited as part of the
295 // uses of a phi.), or
296 // 2. Part of a target specific instruction (i.e., the target applied
297 // some register class constraints when creating the instruction.)
298 // If the constraints come for #2, the target said that another mapping
299 // is supported so we may just drop them. Indeed, if we do not change
300 // the number of registers holding that value, the uses will get fixed
301 // when we get to them.
302 // Uses in PHIs may have already been proceeded though.
303 // If the constraints come for #1, then, those are weak constraints and
304 // no actual uses may rely on them. However, the problem remains mainly
305 // the same as for #2. If the value stays in one register, we could
306 // just switch the register bank of the definition, but we would need to
307 // account for a repairing cost for each phi we silently change.
308 //
309 // In any case, if the value needs to be broken down into several
310 // registers, the repairing is not local anymore as we need to patch
311 // every uses to rebuild the value in just one register.
312 //
313 // To summarize:
314 // - If the value is in a physical register, we can do the split and
315 // fix locally.
316 // Otherwise if the value is in a virtual register:
317 // - If the value remains in one register, we do not have to split
318 // just switching the register bank would do, but we need to account
319 // in the repairing cost all the phi we changed.
320 // - If the value spans several registers, then we cannot do a local
321 // repairing.
322
323 // Check if this is a physical or virtual register.
324 unsigned Reg = MO.getReg();
325 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
326 // We are going to split every outgoing edges.
327 // Check that this is possible.
328 // FIXME: The machine representation is currently broken
329 // since it also several terminators in one basic block.
330 // Because of that we would technically need a way to get
331 // the targets of just one terminator to know which edges
332 // we have to split.
333 // Assert that we do not hit the ill-formed representation.
334
335 // If there are other terminators before that one, some of
336 // the outgoing edges may not be dominated by this definition.
337 assert(&MI == &(*MI.getParent()->getFirstTerminator()) &&
338 "Do not know which outgoing edges are relevant");
339 const MachineInstr *Next = MI.getNextNode();
340 assert((!Next || Next->isUnconditionalBranch()) &&
341 "Do not know where each terminator ends up");
342 if (Next)
343 // If the next terminator uses Reg, this means we have
344 // to split right after MI and thus we need a way to ask
345 // which outgoing edges are affected.
346 assert(!Next->readsRegister(Reg) && "Need to split between terminators");
347 // We will split all the edges and repair there.
348 } else {
349 // This is a virtual register defined by a terminator.
Quentin Colombet0afa7d62016-09-23 00:14:30 +0000350 if (ValMapping.NumBreakDowns == 1) {
Quentin Colombetf75c2bf2016-05-20 16:36:12 +0000351 // There is nothing to repair, but we may actually lie on
352 // the repairing cost because of the PHIs already proceeded
353 // as already stated.
354 // Though the code will be correct.
355 assert(0 && "Repairing cost may not be accurate");
356 } else {
357 // We need to do non-local repairing. Basically, patch all
358 // the uses (i.e., phis) that we already proceeded.
359 // For now, just say this mapping is not possible.
360 RepairPt.switchTo(RepairingPlacement::RepairingKind::Impossible);
361 }
362 }
363}
364
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000365RegBankSelect::MappingCost RegBankSelect::computeMapping(
366 MachineInstr &MI, const RegisterBankInfo::InstructionMapping &InstrMapping,
Quentin Colombet6e80dbc2016-05-20 18:00:46 +0000367 SmallVectorImpl<RepairingPlacement> &RepairPts,
368 const RegBankSelect::MappingCost *BestCost) {
369 assert((MBFI || !BestCost) && "Costs comparison require MBFI");
Quentin Colombete16f5612016-04-07 23:53:55 +0000370
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000371 // If mapped with InstrMapping, MI will have the recorded cost.
Quentin Colombet25fcef72016-05-20 17:54:09 +0000372 MappingCost Cost(MBFI ? MBFI->getBlockFreq(MI.getParent()) : 1);
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000373 bool Saturated = Cost.addLocalCost(InstrMapping.getCost());
374 assert(!Saturated && "Possible mapping saturated the cost");
375 DEBUG(dbgs() << "Evaluating mapping cost for: " << MI);
376 DEBUG(dbgs() << "With: " << InstrMapping << '\n');
377 RepairPts.clear();
Quentin Colombet6e80dbc2016-05-20 18:00:46 +0000378 if (BestCost && Cost > *BestCost)
379 return Cost;
380
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000381 // Moreover, to realize this mapping, the register bank of each operand must
382 // match this mapping. In other words, we may need to locally reassign the
383 // register banks. Account for that repairing cost as well.
384 // In this context, local means in the surrounding of MI.
Quentin Colombet1b016772016-09-29 19:51:46 +0000385 for (unsigned OpIdx = 0, EndOpIdx = InstrMapping.getNumOperands();
386 OpIdx != EndOpIdx; ++OpIdx) {
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000387 const MachineOperand &MO = MI.getOperand(OpIdx);
Quentin Colombet40ad5732016-04-07 18:19:27 +0000388 if (!MO.isReg())
389 continue;
390 unsigned Reg = MO.getReg();
391 if (!Reg)
392 continue;
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000393 DEBUG(dbgs() << "Opd" << OpIdx);
Quentin Colombet40ad5732016-04-07 18:19:27 +0000394 const RegisterBankInfo::ValueMapping &ValMapping =
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000395 InstrMapping.getOperandMapping(OpIdx);
396 // If Reg is already properly mapped, this is free.
397 bool Assign;
398 if (assignmentMatch(Reg, ValMapping, Assign)) {
399 DEBUG(dbgs() << " is free (match).\n");
Quentin Colombet40ad5732016-04-07 18:19:27 +0000400 continue;
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000401 }
402 if (Assign) {
403 DEBUG(dbgs() << " is free (simple assignment).\n");
404 RepairPts.emplace_back(RepairingPlacement(MI, OpIdx, *TRI, *this,
405 RepairingPlacement::Reassign));
406 continue;
Quentin Colombet40ad5732016-04-07 18:19:27 +0000407 }
Quentin Colombet904a2c72016-04-12 00:12:59 +0000408
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000409 // Find the insertion point for the repairing code.
410 RepairPts.emplace_back(
411 RepairingPlacement(MI, OpIdx, *TRI, *this, RepairingPlacement::Insert));
412 RepairingPlacement &RepairPt = RepairPts.back();
413
Quentin Colombetf75c2bf2016-05-20 16:36:12 +0000414 // If we need to split a basic block to materialize this insertion point,
415 // we may give a higher cost to this mapping.
416 // Nevertheless, we may get away with the split, so try that first.
417 if (RepairPt.hasSplit())
418 tryAvoidingSplit(RepairPt, MO, ValMapping);
419
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000420 // Check that the materialization of the repairing is possible.
421 if (!RepairPt.canMaterialize())
422 return MappingCost::ImpossibleCost();
423
424 // Account for the split cost and repair cost.
Quentin Colombet6e80dbc2016-05-20 18:00:46 +0000425 // Unless the cost is already saturated or we do not care about the cost.
426 if (!BestCost || Saturated)
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000427 continue;
428
Quentin Colombet6e80dbc2016-05-20 18:00:46 +0000429 // To get accurate information we need MBFI and MBPI.
430 // Thus, if we end up here this information should be here.
431 assert(MBFI && MBPI && "Cost computation requires MBFI and MBPI");
432
Quentin Colombet6feaf8202016-06-08 15:40:32 +0000433 // FIXME: We will have to rework the repairing cost model.
434 // The repairing cost depends on the register bank that MO has.
435 // However, when we break down the value into different values,
436 // MO may not have a register bank while still needing repairing.
437 // For the fast mode, we don't compute the cost so that is fine,
438 // but still for the repairing code, we will have to make a choice.
439 // For the greedy mode, we should choose greedily what is the best
440 // choice based on the next use of MO.
441
Quentin Colombetf2723a22016-05-21 01:43:25 +0000442 // Sums up the repairing cost of MO at each insertion point.
443 uint64_t RepairCost = getRepairCost(MO, ValMapping);
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000444 // Bias used for splitting: 5%.
445 const uint64_t PercentageForBias = 5;
446 uint64_t Bias = (RepairCost * PercentageForBias + 99) / 100;
447 // We should not need more than a couple of instructions to repair
448 // an assignment. In other words, the computation should not
449 // overflow because the repairing cost is free of basic block
450 // frequency.
451 assert(((RepairCost < RepairCost * PercentageForBias) &&
452 (RepairCost * PercentageForBias <
453 RepairCost * PercentageForBias + 99)) &&
454 "Repairing involves more than a billion of instructions?!");
455 for (const std::unique_ptr<InsertPoint> &InsertPt : RepairPt) {
456 assert(InsertPt->canMaterialize() && "We should not have made it here");
457 // We will applied some basic block frequency and those uses uint64_t.
458 if (!InsertPt->isSplit())
459 Saturated = Cost.addLocalCost(RepairCost);
460 else {
461 uint64_t CostForInsertPt = RepairCost;
462 // Again we shouldn't overflow here givent that
463 // CostForInsertPt is frequency free at this point.
464 assert(CostForInsertPt + Bias > CostForInsertPt &&
465 "Repairing + split bias overflows");
466 CostForInsertPt += Bias;
467 uint64_t PtCost = InsertPt->frequency(*this) * CostForInsertPt;
468 // Check if we just overflowed.
469 if ((Saturated = PtCost < CostForInsertPt))
470 Cost.saturate();
471 else
472 Saturated = Cost.addNonLocalCost(PtCost);
473 }
Quentin Colombet6e80dbc2016-05-20 18:00:46 +0000474
475 // Stop looking into what it takes to repair, this is already
476 // too expensive.
477 if (BestCost && Cost > *BestCost)
478 return Cost;
479
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000480 // No need to accumulate more cost information.
481 // We need to still gather the repairing information though.
482 if (Saturated)
483 break;
484 }
Quentin Colombet40ad5732016-04-07 18:19:27 +0000485 }
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000486 return Cost;
487}
488
Quentin Colombetacb857b2016-08-27 02:38:27 +0000489bool RegBankSelect::applyMapping(
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000490 MachineInstr &MI, const RegisterBankInfo::InstructionMapping &InstrMapping,
491 SmallVectorImpl<RegBankSelect::RepairingPlacement> &RepairPts) {
Quentin Colombetf33e3652016-06-08 16:30:55 +0000492 // OpdMapper will hold all the information needed for the rewritting.
493 RegisterBankInfo::OperandsMapper OpdMapper(MI, InstrMapping, *MRI);
494
Quentin Colombetec5c93d2016-06-08 16:45:04 +0000495 // First, place the repairing code.
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000496 for (RepairingPlacement &RepairPt : RepairPts) {
Quentin Colombetacb857b2016-08-27 02:38:27 +0000497 if (!RepairPt.canMaterialize() ||
498 RepairPt.getKind() == RepairingPlacement::Impossible)
499 return false;
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000500 assert(RepairPt.getKind() != RepairingPlacement::None &&
501 "This should not make its way in the list");
502 unsigned OpIdx = RepairPt.getOpIdx();
503 MachineOperand &MO = MI.getOperand(OpIdx);
504 const RegisterBankInfo::ValueMapping &ValMapping =
505 InstrMapping.getOperandMapping(OpIdx);
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000506 unsigned Reg = MO.getReg();
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000507
508 switch (RepairPt.getKind()) {
509 case RepairingPlacement::Reassign:
Quentin Colombet0afa7d62016-09-23 00:14:30 +0000510 assert(ValMapping.NumBreakDowns == 1 &&
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000511 "Reassignment should only be for simple mapping");
512 MRI->setRegBank(Reg, *ValMapping.BreakDown[0].RegBank);
513 break;
514 case RepairingPlacement::Insert:
Quentin Colombetf33e3652016-06-08 16:30:55 +0000515 OpdMapper.createVRegs(OpIdx);
Quentin Colombetacb857b2016-08-27 02:38:27 +0000516 if (!repairReg(MO, ValMapping, RepairPt, OpdMapper.getVRegs(OpIdx)))
517 return false;
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000518 break;
519 default:
520 llvm_unreachable("Other kind should not happen");
521 }
522 }
523 // Second, rewrite the instruction.
Quentin Colombet33406452016-06-08 21:55:30 +0000524 DEBUG(dbgs() << "Actual mapping of the operands: " << OpdMapper << '\n');
Quentin Colombetec5c93d2016-06-08 16:45:04 +0000525 RBI->applyMapping(OpdMapper);
Quentin Colombetacb857b2016-08-27 02:38:27 +0000526 return true;
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000527}
528
Quentin Colombetacb857b2016-08-27 02:38:27 +0000529bool RegBankSelect::assignInstr(MachineInstr &MI) {
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000530 DEBUG(dbgs() << "Assign: " << MI);
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000531 // Remember the repairing placement for all the operands.
532 SmallVector<RepairingPlacement, 4> RepairPts;
533
Quentin Colombet79fe1be2016-05-20 18:37:33 +0000534 RegisterBankInfo::InstructionMapping BestMapping;
535 if (OptMode == RegBankSelect::Mode::Fast) {
536 BestMapping = RBI->getInstrMapping(MI);
537 MappingCost DefaultCost = computeMapping(MI, BestMapping, RepairPts);
538 (void)DefaultCost;
Quentin Colombetacb857b2016-08-27 02:38:27 +0000539 if (DefaultCost == MappingCost::ImpossibleCost())
540 return false;
Quentin Colombet79fe1be2016-05-20 18:37:33 +0000541 } else {
542 RegisterBankInfo::InstructionMappings PossibleMappings =
543 RBI->getInstrPossibleMappings(MI);
Quentin Colombetacb857b2016-08-27 02:38:27 +0000544 if (PossibleMappings.empty())
545 return false;
Quentin Colombet79fe1be2016-05-20 18:37:33 +0000546 BestMapping = std::move(findBestMapping(MI, PossibleMappings, RepairPts));
547 }
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000548 // Make sure the mapping is valid for MI.
Quentin Colombet79fe1be2016-05-20 18:37:33 +0000549 assert(BestMapping.verify(MI) && "Invalid instruction mapping");
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000550
Quentin Colombet79fe1be2016-05-20 18:37:33 +0000551 DEBUG(dbgs() << "Mapping: " << BestMapping << '\n');
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000552
Quentin Colombet9400bfb2016-06-08 21:55:29 +0000553 // After this call, MI may not be valid anymore.
554 // Do not use it.
Quentin Colombetacb857b2016-08-27 02:38:27 +0000555 return applyMapping(MI, BestMapping, RepairPts);
Quentin Colombet40ad5732016-04-07 18:19:27 +0000556}
557
Quentin Colombet8e8e85c2016-04-05 19:06:01 +0000558bool RegBankSelect::runOnMachineFunction(MachineFunction &MF) {
Quentin Colombet60495242016-08-27 00:18:24 +0000559 // If the ISel pipeline failed, do not bother running that pass.
560 if (MF.getProperties().hasProperty(
561 MachineFunctionProperties::Property::FailedISel))
562 return false;
563
Quentin Colombete16f5612016-04-07 23:53:55 +0000564 DEBUG(dbgs() << "Assign register banks for: " << MF.getName() << '\n');
Quentin Colombeta5530122016-05-20 17:36:54 +0000565 const Function *F = MF.getFunction();
566 Mode SaveOptMode = OptMode;
567 if (F->hasFnAttribute(Attribute::OptimizeNone))
568 OptMode = Mode::Fast;
Quentin Colombet40ad5732016-04-07 18:19:27 +0000569 init(MF);
Ahmed Bougacha24d0d4d2016-08-02 15:10:32 +0000570
571#ifndef NDEBUG
572 // Check that our input is fully legal: we require the function to have the
573 // Legalized property, so it should be.
574 // FIXME: This should be in the MachineVerifier, but it can't use the
575 // MachineLegalizer as it's currently in the separate GlobalISel library.
Tim Northover0f140c72016-09-09 11:46:34 +0000576 const MachineRegisterInfo &MRI = MF.getRegInfo();
Ahmed Bougacha24d0d4d2016-08-02 15:10:32 +0000577 if (const MachineLegalizer *MLI = MF.getSubtarget().getMachineLegalizer()) {
578 for (const MachineBasicBlock &MBB : MF) {
579 for (const MachineInstr &MI : MBB) {
Tim Northover0f140c72016-09-09 11:46:34 +0000580 if (isPreISelGenericOpcode(MI.getOpcode()) && !MLI->isLegal(MI, MRI)) {
Quentin Colombetacb857b2016-08-27 02:38:27 +0000581 if (!TPC->isGlobalISelAbortEnabled()) {
582 MF.getProperties().set(
583 MachineFunctionProperties::Property::FailedISel);
584 return false;
585 }
Ahmed Bougacha24d0d4d2016-08-02 15:10:32 +0000586 std::string ErrStorage;
587 raw_string_ostream Err(ErrStorage);
588 Err << "Instruction is not legal: " << MI << '\n';
589 report_fatal_error(Err.str());
590 }
591 }
592 }
593 }
594#endif
595
Quentin Colombet40ad5732016-04-07 18:19:27 +0000596 // Walk the function and assign register banks to all operands.
Quentin Colombetab8c21f2016-04-08 17:19:10 +0000597 // Use a RPOT to make sure all registers are assigned before we choose
598 // the best mapping of the current instruction.
599 ReversePostOrderTraversal<MachineFunction*> RPOT(&MF);
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000600 for (MachineBasicBlock *MBB : RPOT) {
601 // Set a sensible insertion point so that subsequent calls to
602 // MIRBuilder.
603 MIRBuilder.setMBB(*MBB);
Quentin Colombetec5c93d2016-06-08 16:45:04 +0000604 for (MachineBasicBlock::iterator MII = MBB->begin(), End = MBB->end();
605 MII != End;) {
606 // MI might be invalidated by the assignment, so move the
607 // iterator before hand.
Ahmed Bougacha45eb3b92016-08-02 11:41:16 +0000608 MachineInstr &MI = *MII++;
609
610 // Ignore target-specific instructions: they should use proper regclasses.
611 if (isTargetSpecificOpcode(MI.getOpcode()))
612 continue;
613
Quentin Colombetacb857b2016-08-27 02:38:27 +0000614 if (!assignInstr(MI)) {
615 if (TPC->isGlobalISelAbortEnabled())
616 report_fatal_error("Unable to map instruction");
617 MF.getProperties().set(MachineFunctionProperties::Property::FailedISel);
618 return false;
619 }
Quentin Colombetec5c93d2016-06-08 16:45:04 +0000620 }
Quentin Colombetd84d00b2016-05-20 00:55:51 +0000621 }
Quentin Colombeta5530122016-05-20 17:36:54 +0000622 OptMode = SaveOptMode;
Quentin Colombet8e8e85c2016-04-05 19:06:01 +0000623 return false;
624}
Quentin Colombetcfd97b92016-05-20 00:35:26 +0000625
626//------------------------------------------------------------------------------
Quentin Colombet55650752016-05-20 00:49:10 +0000627// Helper Classes Implementation
Quentin Colombetcfd97b92016-05-20 00:35:26 +0000628//------------------------------------------------------------------------------
Quentin Colombet55650752016-05-20 00:49:10 +0000629RegBankSelect::RepairingPlacement::RepairingPlacement(
630 MachineInstr &MI, unsigned OpIdx, const TargetRegisterInfo &TRI, Pass &P,
631 RepairingPlacement::RepairingKind Kind)
632 // Default is, we are going to insert code to repair OpIdx.
633 : Kind(Kind),
634 OpIdx(OpIdx),
635 CanMaterialize(Kind != RepairingKind::Impossible),
636 HasSplit(false),
637 P(P) {
638 const MachineOperand &MO = MI.getOperand(OpIdx);
639 assert(MO.isReg() && "Trying to repair a non-reg operand");
640
641 if (Kind != RepairingKind::Insert)
642 return;
643
644 // Repairings for definitions happen after MI, uses happen before.
645 bool Before = !MO.isDef();
646
647 // Check if we are done with MI.
648 if (!MI.isPHI() && !MI.isTerminator()) {
649 addInsertPoint(MI, Before);
650 // We are done with the initialization.
651 return;
652 }
653
654 // Now, look for the special cases.
655 if (MI.isPHI()) {
656 // - PHI must be the first instructions:
657 // * Before, we have to split the related incoming edge.
658 // * After, move the insertion point past the last phi.
659 if (!Before) {
660 MachineBasicBlock::iterator It = MI.getParent()->getFirstNonPHI();
661 if (It != MI.getParent()->end())
662 addInsertPoint(*It, /*Before*/ true);
663 else
664 addInsertPoint(*(--It), /*Before*/ false);
665 return;
666 }
667 // We repair a use of a phi, we may need to split the related edge.
668 MachineBasicBlock &Pred = *MI.getOperand(OpIdx + 1).getMBB();
669 // Check if we can move the insertion point prior to the
670 // terminators of the predecessor.
671 unsigned Reg = MO.getReg();
672 MachineBasicBlock::iterator It = Pred.getLastNonDebugInstr();
673 for (auto Begin = Pred.begin(); It != Begin && It->isTerminator(); --It)
674 if (It->modifiesRegister(Reg, &TRI)) {
675 // We cannot hoist the repairing code in the predecessor.
676 // Split the edge.
677 addInsertPoint(Pred, *MI.getParent());
678 return;
679 }
680 // At this point, we can insert in Pred.
681
682 // - If It is invalid, Pred is empty and we can insert in Pred
683 // wherever we want.
684 // - If It is valid, It is the first non-terminator, insert after It.
685 if (It == Pred.end())
686 addInsertPoint(Pred, /*Beginning*/ false);
687 else
688 addInsertPoint(*It, /*Before*/ false);
689 } else {
690 // - Terminators must be the last instructions:
691 // * Before, move the insert point before the first terminator.
692 // * After, we have to split the outcoming edges.
693 unsigned Reg = MO.getReg();
694 if (Before) {
695 // Check whether Reg is defined by any terminator.
696 MachineBasicBlock::iterator It = MI;
697 for (auto Begin = MI.getParent()->begin();
698 --It != Begin && It->isTerminator();)
699 if (It->modifiesRegister(Reg, &TRI)) {
700 // Insert the repairing code right after the definition.
701 addInsertPoint(*It, /*Before*/ false);
702 return;
703 }
704 addInsertPoint(*It, /*Before*/ true);
705 return;
706 }
707 // Make sure Reg is not redefined by other terminators, otherwise
708 // we do not know how to split.
709 for (MachineBasicBlock::iterator It = MI, End = MI.getParent()->end();
710 ++It != End;)
711 // The machine verifier should reject this kind of code.
712 assert(It->modifiesRegister(Reg, &TRI) && "Do not know where to split");
713 // Split each outcoming edges.
714 MachineBasicBlock &Src = *MI.getParent();
715 for (auto &Succ : Src.successors())
716 addInsertPoint(Src, Succ);
717 }
718}
719
720void RegBankSelect::RepairingPlacement::addInsertPoint(MachineInstr &MI,
721 bool Before) {
722 addInsertPoint(*new InstrInsertPoint(MI, Before));
723}
724
725void RegBankSelect::RepairingPlacement::addInsertPoint(MachineBasicBlock &MBB,
726 bool Beginning) {
727 addInsertPoint(*new MBBInsertPoint(MBB, Beginning));
728}
729
730void RegBankSelect::RepairingPlacement::addInsertPoint(MachineBasicBlock &Src,
731 MachineBasicBlock &Dst) {
732 addInsertPoint(*new EdgeInsertPoint(Src, Dst, P));
733}
734
735void RegBankSelect::RepairingPlacement::addInsertPoint(
736 RegBankSelect::InsertPoint &Point) {
737 CanMaterialize &= Point.canMaterialize();
738 HasSplit |= Point.isSplit();
739 InsertPoints.emplace_back(&Point);
740}
741
742RegBankSelect::InstrInsertPoint::InstrInsertPoint(MachineInstr &Instr,
743 bool Before)
744 : InsertPoint(), Instr(Instr), Before(Before) {
745 // Since we do not support splitting, we do not need to update
746 // liveness and such, so do not do anything with P.
747 assert((!Before || !Instr.isPHI()) &&
748 "Splitting before phis requires more points");
749 assert((!Before || !Instr.getNextNode() || !Instr.getNextNode()->isPHI()) &&
750 "Splitting between phis does not make sense");
751}
752
753void RegBankSelect::InstrInsertPoint::materialize() {
754 if (isSplit()) {
755 // Slice and return the beginning of the new block.
756 // If we need to split between the terminators, we theoritically
757 // need to know where the first and second set of terminators end
758 // to update the successors properly.
759 // Now, in pratice, we should have a maximum of 2 branch
760 // instructions; one conditional and one unconditional. Therefore
761 // we know how to update the successor by looking at the target of
762 // the unconditional branch.
763 // If we end up splitting at some point, then, we should update
764 // the liveness information and such. I.e., we would need to
765 // access P here.
766 // The machine verifier should actually make sure such cases
767 // cannot happen.
768 llvm_unreachable("Not yet implemented");
769 }
770 // Otherwise the insertion point is just the current or next
771 // instruction depending on Before. I.e., there is nothing to do
772 // here.
773}
774
775bool RegBankSelect::InstrInsertPoint::isSplit() const {
776 // If the insertion point is after a terminator, we need to split.
777 if (!Before)
778 return Instr.isTerminator();
779 // If we insert before an instruction that is after a terminator,
780 // we are still after a terminator.
781 return Instr.getPrevNode() && Instr.getPrevNode()->isTerminator();
782}
783
784uint64_t RegBankSelect::InstrInsertPoint::frequency(const Pass &P) const {
785 // Even if we need to split, because we insert between terminators,
786 // this split has actually the same frequency as the instruction.
787 const MachineBlockFrequencyInfo *MBFI =
788 P.getAnalysisIfAvailable<MachineBlockFrequencyInfo>();
789 if (!MBFI)
790 return 1;
791 return MBFI->getBlockFreq(Instr.getParent()).getFrequency();
792}
793
794uint64_t RegBankSelect::MBBInsertPoint::frequency(const Pass &P) const {
795 const MachineBlockFrequencyInfo *MBFI =
796 P.getAnalysisIfAvailable<MachineBlockFrequencyInfo>();
797 if (!MBFI)
798 return 1;
799 return MBFI->getBlockFreq(&MBB).getFrequency();
800}
801
802void RegBankSelect::EdgeInsertPoint::materialize() {
803 // If we end up repairing twice at the same place before materializing the
804 // insertion point, we may think we have to split an edge twice.
805 // We should have a factory for the insert point such that identical points
806 // are the same instance.
807 assert(Src.isSuccessor(DstOrSplit) && DstOrSplit->isPredecessor(&Src) &&
808 "This point has already been split");
809 MachineBasicBlock *NewBB = Src.SplitCriticalEdge(DstOrSplit, P);
810 assert(NewBB && "Invalid call to materialize");
811 // We reuse the destination block to hold the information of the new block.
812 DstOrSplit = NewBB;
813}
814
815uint64_t RegBankSelect::EdgeInsertPoint::frequency(const Pass &P) const {
816 const MachineBlockFrequencyInfo *MBFI =
817 P.getAnalysisIfAvailable<MachineBlockFrequencyInfo>();
818 if (!MBFI)
819 return 1;
820 if (WasMaterialized)
821 return MBFI->getBlockFreq(DstOrSplit).getFrequency();
822
823 const MachineBranchProbabilityInfo *MBPI =
824 P.getAnalysisIfAvailable<MachineBranchProbabilityInfo>();
825 if (!MBPI)
826 return 1;
827 // The basic block will be on the edge.
828 return (MBFI->getBlockFreq(&Src) * MBPI->getEdgeProbability(&Src, DstOrSplit))
829 .getFrequency();
830}
831
832bool RegBankSelect::EdgeInsertPoint::canMaterialize() const {
833 // If this is not a critical edge, we should not have used this insert
834 // point. Indeed, either the successor or the predecessor should
835 // have do.
836 assert(Src.succ_size() > 1 && DstOrSplit->pred_size() > 1 &&
837 "Edge is not critical");
838 return Src.canSplitCriticalEdge(DstOrSplit);
839}
840
Quentin Colombetcfd97b92016-05-20 00:35:26 +0000841RegBankSelect::MappingCost::MappingCost(const BlockFrequency &LocalFreq)
842 : LocalCost(0), NonLocalCost(0), LocalFreq(LocalFreq.getFrequency()) {}
843
844bool RegBankSelect::MappingCost::addLocalCost(uint64_t Cost) {
845 // Check if this overflows.
846 if (LocalCost + Cost < LocalCost) {
847 saturate();
848 return true;
849 }
850 LocalCost += Cost;
851 return isSaturated();
852}
853
854bool RegBankSelect::MappingCost::addNonLocalCost(uint64_t Cost) {
855 // Check if this overflows.
856 if (NonLocalCost + Cost < NonLocalCost) {
857 saturate();
858 return true;
859 }
860 NonLocalCost += Cost;
861 return isSaturated();
862}
863
864bool RegBankSelect::MappingCost::isSaturated() const {
865 return LocalCost == UINT64_MAX - 1 && NonLocalCost == UINT64_MAX &&
866 LocalFreq == UINT64_MAX;
867}
868
869void RegBankSelect::MappingCost::saturate() {
870 *this = ImpossibleCost();
871 --LocalCost;
872}
873
874RegBankSelect::MappingCost RegBankSelect::MappingCost::ImpossibleCost() {
875 return MappingCost(UINT64_MAX, UINT64_MAX, UINT64_MAX);
876}
877
878bool RegBankSelect::MappingCost::operator<(const MappingCost &Cost) const {
879 // Sort out the easy cases.
880 if (*this == Cost)
881 return false;
882 // If one is impossible to realize the other is cheaper unless it is
883 // impossible as well.
884 if ((*this == ImpossibleCost()) || (Cost == ImpossibleCost()))
885 return (*this == ImpossibleCost()) < (Cost == ImpossibleCost());
886 // If one is saturated the other is cheaper, unless it is saturated
887 // as well.
888 if (isSaturated() || Cost.isSaturated())
889 return isSaturated() < Cost.isSaturated();
890 // At this point we know both costs hold sensible values.
891
892 // If both values have a different base frequency, there is no much
893 // we can do but to scale everything.
894 // However, if they have the same base frequency we can avoid making
895 // complicated computation.
896 uint64_t ThisLocalAdjust;
897 uint64_t OtherLocalAdjust;
898 if (LLVM_LIKELY(LocalFreq == Cost.LocalFreq)) {
899
900 // At this point, we know the local costs are comparable.
901 // Do the case that do not involve potential overflow first.
902 if (NonLocalCost == Cost.NonLocalCost)
903 // Since the non-local costs do not discriminate on the result,
904 // just compare the local costs.
905 return LocalCost < Cost.LocalCost;
906
907 // The base costs are comparable so we may only keep the relative
908 // value to increase our chances of avoiding overflows.
909 ThisLocalAdjust = 0;
910 OtherLocalAdjust = 0;
911 if (LocalCost < Cost.LocalCost)
912 OtherLocalAdjust = Cost.LocalCost - LocalCost;
913 else
914 ThisLocalAdjust = LocalCost - Cost.LocalCost;
915
916 } else {
917 ThisLocalAdjust = LocalCost;
918 OtherLocalAdjust = Cost.LocalCost;
919 }
920
921 // The non-local costs are comparable, just keep the relative value.
922 uint64_t ThisNonLocalAdjust = 0;
923 uint64_t OtherNonLocalAdjust = 0;
924 if (NonLocalCost < Cost.NonLocalCost)
925 OtherNonLocalAdjust = Cost.NonLocalCost - NonLocalCost;
926 else
927 ThisNonLocalAdjust = NonLocalCost - Cost.NonLocalCost;
928 // Scale everything to make them comparable.
929 uint64_t ThisScaledCost = ThisLocalAdjust * LocalFreq;
930 // Check for overflow on that operation.
931 bool ThisOverflows = ThisLocalAdjust && (ThisScaledCost < ThisLocalAdjust ||
932 ThisScaledCost < LocalFreq);
933 uint64_t OtherScaledCost = OtherLocalAdjust * Cost.LocalFreq;
934 // Check for overflow on the last operation.
935 bool OtherOverflows =
936 OtherLocalAdjust &&
937 (OtherScaledCost < OtherLocalAdjust || OtherScaledCost < Cost.LocalFreq);
938 // Add the non-local costs.
939 ThisOverflows |= ThisNonLocalAdjust &&
940 ThisScaledCost + ThisNonLocalAdjust < ThisNonLocalAdjust;
941 ThisScaledCost += ThisNonLocalAdjust;
942 OtherOverflows |= OtherNonLocalAdjust &&
943 OtherScaledCost + OtherNonLocalAdjust < OtherNonLocalAdjust;
944 OtherScaledCost += OtherNonLocalAdjust;
945 // If both overflows, we cannot compare without additional
946 // precision, e.g., APInt. Just give up on that case.
947 if (ThisOverflows && OtherOverflows)
948 return false;
949 // If one overflows but not the other, we can still compare.
950 if (ThisOverflows || OtherOverflows)
951 return ThisOverflows < OtherOverflows;
952 // Otherwise, just compare the values.
953 return ThisScaledCost < OtherScaledCost;
954}
955
956bool RegBankSelect::MappingCost::operator==(const MappingCost &Cost) const {
957 return LocalCost == Cost.LocalCost && NonLocalCost == Cost.NonLocalCost &&
958 LocalFreq == Cost.LocalFreq;
959}