LLVM 24.0.0git
RegAllocFast.cpp
Go to the documentation of this file.
1//===- RegAllocFast.cpp - A fast register allocator for debug code --------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9/// \file A block-local register allocator. No virtual register stays in a
10/// register across a block boundary. A value live across one gets a stack slot:
11/// spilled after its def and reloaded above its uses in each block, at the top
12/// of the block or just after an intervening instruction that evicts it.
13/// There is no dataflow liveness analysis, only a bounded scan of def and use
14/// lists, and no live range splitting, interference graph or coalescer, only a
15/// copy hint plus removal of COPYs that end up identity or dead.
16///
17/// Each block is walked backwards: a use is the first reference reached and
18/// acquires a register, a def is the last and releases one.
19//
20//===----------------------------------------------------------------------===//
21
23#include "llvm/ADT/ArrayRef.h"
24#include "llvm/ADT/DenseMap.h"
25#include "llvm/ADT/IndexedMap.h"
26#include "llvm/ADT/MapVector.h"
27#include "llvm/ADT/SmallSet.h"
29#include "llvm/ADT/SparseSet.h"
30#include "llvm/ADT/Statistic.h"
48#include "llvm/Pass.h"
49#include "llvm/Support/Debug.h"
52#include <cassert>
53#include <tuple>
54#include <vector>
55
56using namespace llvm;
57
58#define DEBUG_TYPE "regalloc"
59
60STATISTIC(NumStores, "Number of stores added");
61STATISTIC(NumLoads, "Number of loads added");
62STATISTIC(NumCoalesced, "Number of copies coalesced");
63
64// FIXME: Remove this switch when all testcases are fixed!
65static cl::opt<bool> IgnoreMissingDefs("rafast-ignore-missing-defs",
67
68static RegisterRegAlloc fastRegAlloc("fast", "fast register allocator",
70
71namespace {
72
73/// Assign ascending index for instructions in machine basic block. The index
74/// can be used to determine dominance between instructions in same MBB.
75class InstrPosIndexes {
76public:
77 void unsetInitialized() { IsInitialized = false; }
78
79 void init(const MachineBasicBlock &MBB) {
80 CurMBB = &MBB;
81 Instr2PosIndex.clear();
82 uint64_t LastIndex = 0;
83 for (const MachineInstr &MI : MBB) {
84 LastIndex += InstrDist;
85 Instr2PosIndex[&MI] = LastIndex;
86 }
87 }
88
89 /// Set \p Index to index of \p MI. If \p MI is new inserted, it try to assign
90 /// index without affecting existing instruction's index. Return true if all
91 /// instructions index has been reassigned.
92 bool getIndex(const MachineInstr &MI, uint64_t &Index) {
93 if (!IsInitialized) {
94 init(*MI.getParent());
95 IsInitialized = true;
96 Index = Instr2PosIndex.at(&MI);
97 return true;
98 }
99
100 assert(MI.getParent() == CurMBB && "MI is not in CurMBB");
101 auto It = Instr2PosIndex.find(&MI);
102 if (It != Instr2PosIndex.end()) {
103 Index = It->second;
104 return false;
105 }
106
107 // Distance is the number of consecutive unassigned instructions including
108 // MI. Start is the first instruction of them. End is the next of last
109 // instruction of them.
110 // e.g.
111 // |Instruction| A | B | C | MI | D | E |
112 // | Index | 1024 | | | | | 2048 |
113 //
114 // In this case, B, C, MI, D are unassigned. Distance is 4, Start is B, End
115 // is E.
116 unsigned Distance = 1;
118 End = std::next(Start);
119 while (Start != CurMBB->begin() &&
120 !Instr2PosIndex.count(&*std::prev(Start))) {
121 --Start;
122 ++Distance;
123 }
124 while (End != CurMBB->end() && !Instr2PosIndex.count(&*(End))) {
125 ++End;
126 ++Distance;
127 }
128
129 // LastIndex is initialized to last used index prior to MI or zero.
130 // In previous example, LastIndex is 1024, EndIndex is 2048;
131 uint64_t LastIndex =
132 Start == CurMBB->begin() ? 0 : Instr2PosIndex.at(&*std::prev(Start));
133 uint64_t Step;
134 if (End == CurMBB->end())
135 Step = static_cast<uint64_t>(InstrDist);
136 else {
137 // No instruction uses index zero.
138 uint64_t EndIndex = Instr2PosIndex.at(&*End);
139 assert(EndIndex > LastIndex && "Index must be ascending order");
140 unsigned NumAvailableIndexes = EndIndex - LastIndex - 1;
141 // We want index gap between two adjacent MI is as same as possible. Given
142 // total A available indexes, D is number of consecutive unassigned
143 // instructions, S is the step.
144 // |<- S-1 -> MI <- S-1 -> MI <- A-S*D ->|
145 // There're S-1 available indexes between unassigned instruction and its
146 // predecessor. There're A-S*D available indexes between the last
147 // unassigned instruction and its successor.
148 // Ideally, we want
149 // S-1 = A-S*D
150 // then
151 // S = (A+1)/(D+1)
152 // An valid S must be integer greater than zero, so
153 // S <= (A+1)/(D+1)
154 // =>
155 // A-S*D >= 0
156 // That means we can safely use (A+1)/(D+1) as step.
157 // In previous example, Step is 204, Index of B, C, MI, D is 1228, 1432,
158 // 1636, 1840.
159 Step = (NumAvailableIndexes + 1) / (Distance + 1);
160 }
161
162 // Reassign index for all instructions if number of new inserted
163 // instructions exceed slot or all instructions are new.
164 if (LLVM_UNLIKELY(!Step || (!LastIndex && Step == InstrDist))) {
165 init(*CurMBB);
166 Index = Instr2PosIndex.at(&MI);
167 return true;
168 }
169
170 for (auto I = Start; I != End; ++I) {
171 LastIndex += Step;
172 Instr2PosIndex[&*I] = LastIndex;
173 }
174 Index = Instr2PosIndex.at(&MI);
175 return false;
176 }
177
178private:
179 bool IsInitialized = false;
180 enum { InstrDist = 1024 };
181 const MachineBasicBlock *CurMBB = nullptr;
182 DenseMap<const MachineInstr *, uint64_t> Instr2PosIndex;
183};
184
185class RegAllocFastImpl {
186public:
187 RegAllocFastImpl(const RegAllocFilterFunc F = nullptr,
188 bool ClearVirtRegs_ = true)
189 : ShouldAllocateRegisterImpl(F), StackSlotForVirtReg(-1),
190 ClearVirtRegs(ClearVirtRegs_) {}
191
192private:
193 MachineFrameInfo *MFI = nullptr;
194 MachineRegisterInfo *MRI = nullptr;
195 const TargetRegisterInfo *TRI = nullptr;
196 const TargetInstrInfo *TII = nullptr;
197 RegisterClassInfo RegClassInfo;
198 const RegAllocFilterFunc ShouldAllocateRegisterImpl;
199
200 /// Basic block currently being allocated.
201 MachineBasicBlock *MBB = nullptr;
202
203 /// Maps virtual regs to the frame index where these values are spilled.
204 IndexedMap<int, VirtReg2IndexFunctor> StackSlotForVirtReg;
205
206 /// A virtual register live at the current point of the backward walk.
207 /// Created at its last reference, cleared only when the block is done.
208 struct LiveReg {
209 MachineInstr *LastUse = nullptr; ///< Last instr to use reg.
210 Register VirtReg; ///< Virtual register number.
211 MCRegister PhysReg; ///< Currently held here, 0 if none.
212 bool LiveOut = false; ///< May be live out; the def spills.
213 bool Reloaded = false; ///< Reloaded below; the def spills.
214 bool Error = false; ///< Could not allocate.
215
216 explicit LiveReg(Register VirtReg) : VirtReg(VirtReg) {}
217 explicit LiveReg() = default;
218
219 unsigned getSparseSetIndex() const { return VirtReg.virtRegIndex(); }
220 };
221
222 using LiveRegMap = SparseSet<LiveReg, unsigned, identity, uint16_t>;
223 /// This map contains entries for each virtual register that is currently
224 /// available in a physical register.
225 LiveRegMap LiveVirtRegs;
226
227 /// Stores assigned virtual registers present in the bundle MI.
228 DenseMap<Register, LiveReg> BundleVirtRegsMap;
229
230 DenseMap<Register, SmallVector<MachineOperand *, 2>> LiveDbgValueMap;
231 /// List of DBG_VALUE that we encountered without the vreg being assigned
232 /// because they were placed after the last use of the vreg.
233 DenseMap<Register, SmallVector<MachineInstr *, 1>> DanglingDbgValues;
234
235 /// Has a bit set for every virtual register for which it was determined
236 /// that it is alive across blocks.
237 BitVector MayLiveAcrossBlocks;
238
239 /// What occupies a register unit. Registers interfere exactly when their
240 /// unit sets intersect, so overlap needs no alias walk.
241 enum RegUnitState {
242 /// Not in use; a register is allocatable iff all of its units are free.
243 regFree,
244
245 /// Not available to the allocator and not a virtual register: a physreg
246 /// operand or a block live-out. Cannot be spilled.
247 regPreAssigned,
248
249 /// Scratch marker: reloadAtBegin() stamps MBB.liveins() over the finished
250 /// map, and a virtual register left in a live-in register is not reloaded.
251 regLiveIn,
252
253 /// Any other value is a virtual register number (>= VirtualRegFlag);
254 /// LiveVirtRegs holds the inverse mapping.
255 };
256
257 /// State of each register unit, indexed by MCRegUnit.
258 std::vector<unsigned> RegUnitStates;
259
261
262 /// Track register units that are used in the current instruction, and so
263 /// cannot be allocated.
264 ///
265 /// In the first phase (tied defs/early clobber), we consider also physical
266 /// uses, afterwards, we don't. If the lowest bit isn't set, it's a solely
267 /// physical use (markPhysRegUsedInInstr), otherwise, it's a normal use. To
268 /// avoid resetting the entire vector after every instruction, we track the
269 /// instruction "generation" in the remaining 31 bits -- this means, that if
270 /// UsedInInstr[Idx] < InstrGen, the register unit is unused. InstrGen is
271 /// never zero and always incremented by two.
272 ///
273 /// Don't allocate inline storage: the number of register units is typically
274 /// quite large (e.g., AArch64 > 100, X86 > 200, AMDGPU > 1000).
275 uint32_t InstrGen;
276 SmallVector<unsigned, 0> UsedInInstr;
277
278 SmallVector<unsigned, 8> DefOperandIndexes;
279 // Register masks attached to the current instruction.
281
282 // Assign index for each instruction to quickly determine dominance.
283 InstrPosIndexes PosIndexes;
284
285 void setRegUnitState(MCRegUnit Unit, unsigned NewState);
286 unsigned getRegUnitState(MCRegUnit Unit) const;
287
288 void setPhysRegState(MCRegister PhysReg, unsigned NewState);
289 bool isPhysRegFree(MCRegister PhysReg) const;
290
291 /// Mark a physreg as used in this instruction.
292 void markRegUsedInInstr(MCRegister PhysReg) {
293 for (MCRegUnit Unit : TRI->regunits(PhysReg))
294 UsedInInstr[static_cast<unsigned>(Unit)] = InstrGen | 1;
295 }
296
297 // Check if physreg is clobbered by instruction's regmask(s).
298 bool isClobberedByRegMasks(MCRegister PhysReg) const {
299 return llvm::any_of(RegMasks, [PhysReg](const uint32_t *Mask) {
300 return MachineOperand::clobbersPhysReg(Mask, PhysReg);
301 });
302 }
303
304 /// Check if a physreg or any of its aliases are used in this instruction.
305 bool isRegUsedInInstr(MCRegister PhysReg, bool LookAtPhysRegUses) const {
306 if (LookAtPhysRegUses && isClobberedByRegMasks(PhysReg))
307 return true;
308 for (MCRegUnit Unit : TRI->regunits(PhysReg))
309 if (UsedInInstr[static_cast<unsigned>(Unit)] >=
310 (InstrGen | !LookAtPhysRegUses))
311 return true;
312 return false;
313 }
314
315 /// Mark physical register as being used in a register use operand.
316 /// This is only used by the special livethrough handling code.
317 void markPhysRegUsedInInstr(MCRegister PhysReg) {
318 for (MCRegUnit Unit : TRI->regunits(PhysReg)) {
319 assert(UsedInInstr[static_cast<unsigned>(Unit)] <= InstrGen &&
320 "non-phys use before phys use?");
321 UsedInInstr[static_cast<unsigned>(Unit)] = InstrGen;
322 }
323 }
324
325 /// Remove mark of physical register being used in the instruction.
326 void unmarkRegUsedInInstr(MCRegister PhysReg) {
327 for (MCRegUnit Unit : TRI->regunits(PhysReg))
328 UsedInInstr[static_cast<unsigned>(Unit)] = 0;
329 }
330
331 enum : unsigned {
332 spillClean = 50,
333 spillDirty = 100,
334 spillPrefBonus = 20,
335 spillImpossible = ~0u
336 };
337
338public:
339 bool ClearVirtRegs;
340
341 bool runOnMachineFunction(MachineFunction &MF);
342
343private:
344 void allocateBasicBlock(MachineBasicBlock &MBB);
345
346 void addRegClassDefCounts(MutableArrayRef<unsigned> RegClassDefCounts,
347 Register Reg) const;
348
349 void findAndSortDefOperandIndexes(const MachineInstr &MI);
350
351 void allocateInstruction(MachineInstr &MI);
352 void handleDebugValue(MachineInstr &MI);
353 void handleBundle(MachineInstr &MI);
354
355 bool usePhysReg(MachineInstr &MI, MCRegister PhysReg);
356 bool definePhysReg(MachineInstr &MI, MCRegister PhysReg);
357 bool displacePhysReg(MachineInstr &MI, MCRegister PhysReg);
358 void freePhysReg(MCRegister PhysReg);
359
360 unsigned calcSpillCost(MCPhysReg PhysReg) const;
361
362 LiveRegMap::iterator findLiveVirtReg(Register VirtReg) {
363 return LiveVirtRegs.find(VirtReg.virtRegIndex());
364 }
365
366 LiveRegMap::const_iterator findLiveVirtReg(Register VirtReg) const {
367 return LiveVirtRegs.find(VirtReg.virtRegIndex());
368 }
369
370 void assignVirtToPhysReg(MachineInstr &MI, LiveReg &, MCRegister PhysReg);
371 void allocVirtReg(MachineInstr &MI, LiveReg &LR, Register Hint,
372 bool LookAtPhysRegUses = false);
373 void allocVirtRegUndef(MachineOperand &MO);
374 void assignDanglingDebugValues(MachineInstr &Def, Register VirtReg,
375 MCRegister Reg);
376 bool defineLiveThroughVirtReg(MachineInstr &MI, unsigned OpNum,
377 Register VirtReg);
378 bool defineVirtReg(MachineInstr &MI, unsigned OpNum, Register VirtReg,
379 bool LookAtPhysRegUses = false);
380 bool useVirtReg(MachineInstr &MI, MachineOperand &MO, Register VirtReg);
381
382 MCPhysReg getErrorAssignment(const LiveReg &LR, MachineInstr &MI,
383 const TargetRegisterClass &RC);
384
386 getMBBBeginInsertionPoint(MachineBasicBlock &MBB,
387 SmallSet<Register, 2> &PrologLiveIns) const;
388
389 void reloadAtBegin(MachineBasicBlock &MBB);
390 bool setPhysReg(MachineInstr &MI, MachineOperand &MO,
391 const LiveReg &Assignment);
392
393 Register traceCopies(Register VirtReg) const;
394 Register traceCopyChain(Register Reg) const;
395
396 bool shouldAllocateRegister(const Register Reg) const;
397 int getStackSpaceFor(Register VirtReg);
398 void spill(MachineBasicBlock::iterator Before, Register VirtReg,
399 MCRegister AssignedReg, bool Kill, bool LiveOut);
400 void reload(MachineBasicBlock::iterator Before, Register VirtReg,
401 MCRegister PhysReg);
402
403 bool mayLiveOut(Register VirtReg);
404 bool mayLiveIn(Register VirtReg);
405
406 bool mayBeSpillFromInlineAsmBr(const MachineInstr &MI) const;
407
408 void dumpState() const;
409};
410
411class RegAllocFast : public MachineFunctionPass {
412 RegAllocFastImpl Impl;
413
414public:
415 static char ID;
416
417 RegAllocFast(const RegAllocFilterFunc F = nullptr, bool ClearVirtRegs_ = true)
418 : MachineFunctionPass(ID), Impl(F, ClearVirtRegs_) {}
419
420 bool runOnMachineFunction(MachineFunction &MF) override {
421 return Impl.runOnMachineFunction(MF);
422 }
423
424 StringRef getPassName() const override { return "Fast Register Allocator"; }
425
426 void getAnalysisUsage(AnalysisUsage &AU) const override {
427 AU.setPreservesCFG();
429 }
430
431 MachineFunctionProperties getRequiredProperties() const override {
432 return MachineFunctionProperties().setNoPHIs();
433 }
434
435 MachineFunctionProperties getSetProperties() const override {
436 if (Impl.ClearVirtRegs) {
437 return MachineFunctionProperties().setNoVRegs();
438 }
439
440 return MachineFunctionProperties();
441 }
442
443 MachineFunctionProperties getClearedProperties() const override {
444 return MachineFunctionProperties().setIsSSA();
445 }
446};
447
448} // end anonymous namespace
449
450char RegAllocFast::ID = 0;
451
452INITIALIZE_PASS(RegAllocFast, "regallocfast", "Fast Register Allocator", false,
453 false)
454
455bool RegAllocFastImpl::shouldAllocateRegister(const Register Reg) const {
456 assert(Reg.isVirtual());
457 if (!ShouldAllocateRegisterImpl)
458 return true;
459
460 return ShouldAllocateRegisterImpl(*TRI, *MRI, Reg);
461}
462
463void RegAllocFastImpl::setRegUnitState(MCRegUnit Unit, unsigned NewState) {
464 RegUnitStates[static_cast<unsigned>(Unit)] = NewState;
465}
466
467unsigned RegAllocFastImpl::getRegUnitState(MCRegUnit Unit) const {
468 return RegUnitStates[static_cast<unsigned>(Unit)];
469}
470
471void RegAllocFastImpl::setPhysRegState(MCRegister PhysReg, unsigned NewState) {
472 for (MCRegUnit Unit : TRI->regunits(PhysReg))
473 setRegUnitState(Unit, NewState);
474}
475
476bool RegAllocFastImpl::isPhysRegFree(MCRegister PhysReg) const {
477 for (MCRegUnit Unit : TRI->regunits(PhysReg)) {
478 if (getRegUnitState(Unit) != regFree)
479 return false;
480 }
481 return true;
482}
483
484/// This allocates space for the specified virtual register to be held on the
485/// stack.
486int RegAllocFastImpl::getStackSpaceFor(Register VirtReg) {
487 // Find the location Reg would belong...
488 int SS = StackSlotForVirtReg[VirtReg];
489 // Already has space allocated?
490 if (SS != -1)
491 return SS;
492
493 // Allocate a new stack object for this spill location...
494 const TargetRegisterClass &RC = *MRI->getRegClass(VirtReg);
495 unsigned Size = TRI->getSpillSize(RC);
496 Align Alignment = TRI->getSpillAlign(RC);
497
498 const MachineFunction &MF = MRI->getMF();
499 auto &ST = MF.getSubtarget();
500 Align CurrentAlign = ST.getFrameLowering()->getStackAlign();
501 if (Alignment > CurrentAlign && !TRI->canRealignStack(MF))
502 Alignment = CurrentAlign;
503
504 int FrameIdx =
505 MFI->CreateSpillStackObject(Size, Alignment, TRI->getSpillStackID(RC));
506
507 // Assign the slot.
508 StackSlotForVirtReg[VirtReg] = FrameIdx;
509 return FrameIdx;
510}
511
512static bool dominates(InstrPosIndexes &PosIndexes, const MachineInstr &A,
513 const MachineInstr &B) {
514 uint64_t IndexA, IndexB;
515 PosIndexes.getIndex(A, IndexA);
516 // getIndex() returns true when it renumbered the block, invalidating IndexA.
517 if (LLVM_UNLIKELY(PosIndexes.getIndex(B, IndexB)))
518 PosIndexes.getIndex(A, IndexA);
519 return IndexA < IndexB;
520}
521
522/// Returns true if \p MI is a spill of a live-in physical register in a block
523/// targeted by an INLINEASM_BR. Such spills must precede reloads of live-in
524/// virtual registers, so that we do not reload from an uninitialized stack
525/// slot.
526bool RegAllocFastImpl::mayBeSpillFromInlineAsmBr(const MachineInstr &MI) const {
527 int FI;
528 auto *MBB = MI.getParent();
530 MFI->isSpillSlotObjectIndex(FI))
531 for (const auto &Op : MI.operands())
532 if (Op.isReg() && Op.getReg().isValid() && MBB->isLiveIn(Op.getReg()))
533 return true;
534 return false;
535}
536
537/// Returns false if \p VirtReg is known to not live out of the current block.
538bool RegAllocFastImpl::mayLiveOut(Register VirtReg) {
539 if (MayLiveAcrossBlocks.test(VirtReg.virtRegIndex())) {
540 // Cannot be live-out if there are no successors.
541 return !MBB->succ_empty();
542 }
543
544 const MachineInstr *SelfLoopDef = nullptr;
545
546 // If this block loops back to itself, it is necessary to check whether the
547 // use comes after the def.
548 if (MBB->isSuccessor(MBB)) {
549 // Find the first def in the self loop MBB.
550 for (const MachineInstr &DefInst : MRI->def_instructions(VirtReg)) {
551 if (DefInst.getParent() != MBB) {
552 MayLiveAcrossBlocks.set(VirtReg.virtRegIndex());
553 return true;
554 } else {
555 if (!SelfLoopDef || dominates(PosIndexes, DefInst, *SelfLoopDef))
556 SelfLoopDef = &DefInst;
557 }
558 }
559 if (!SelfLoopDef) {
560 MayLiveAcrossBlocks.set(VirtReg.virtRegIndex());
561 return true;
562 }
563 }
564
565 // See if the first \p Limit uses of the register are all in the current
566 // block.
567 static const unsigned Limit = 8;
568 unsigned C = 0;
569 for (const MachineInstr &UseInst : MRI->use_nodbg_instructions(VirtReg)) {
570 if (UseInst.getParent() != MBB || ++C >= Limit) {
571 MayLiveAcrossBlocks.set(VirtReg.virtRegIndex());
572 // Cannot be live-out if there are no successors.
573 return !MBB->succ_empty();
574 }
575
576 if (SelfLoopDef) {
577 // Try to handle some simple cases to avoid spilling and reloading every
578 // value inside a self looping block.
579 if (SelfLoopDef == &UseInst ||
580 !dominates(PosIndexes, *SelfLoopDef, UseInst)) {
581 MayLiveAcrossBlocks.set(VirtReg.virtRegIndex());
582 return true;
583 }
584 }
585 }
586
587 return false;
588}
589
590/// Returns false if \p VirtReg is known to not be live into the current block.
591bool RegAllocFastImpl::mayLiveIn(Register VirtReg) {
592 if (MayLiveAcrossBlocks.test(VirtReg.virtRegIndex()))
593 return !MBB->pred_empty();
594
595 // See if the first \p Limit def of the register are all in the current block.
596 static const unsigned Limit = 8;
597 unsigned C = 0;
598 for (const MachineInstr &DefInst : MRI->def_instructions(VirtReg)) {
599 if (DefInst.getParent() != MBB || ++C >= Limit) {
600 MayLiveAcrossBlocks.set(VirtReg.virtRegIndex());
601 return !MBB->pred_empty();
602 }
603 }
604
605 return false;
606}
607
608/// Insert spill instruction for \p AssignedReg before \p Before. Update
609/// DBG_VALUEs with \p VirtReg operands with the stack slot.
610void RegAllocFastImpl::spill(MachineBasicBlock::iterator Before,
611 Register VirtReg, MCRegister AssignedReg,
612 bool Kill, bool LiveOut) {
613 LLVM_DEBUG(dbgs() << "Spilling " << printReg(VirtReg, TRI) << " in "
614 << printReg(AssignedReg, TRI));
615 int FI = getStackSpaceFor(VirtReg);
616 LLVM_DEBUG(dbgs() << " to stack slot #" << FI << '\n');
617
618 const TargetRegisterClass &RC = *MRI->getRegClass(VirtReg);
619 TII->storeRegToStackSlot(*MBB, Before, AssignedReg, Kill, FI, &RC, VirtReg);
620 ++NumStores;
621
623
624 // When we spill a virtual register, we will have spill instructions behind
625 // every definition of it, meaning we can switch all the DBG_VALUEs over
626 // to just reference the stack slot.
627 SmallVectorImpl<MachineOperand *> &LRIDbgOperands = LiveDbgValueMap[VirtReg];
628 SmallMapVector<MachineInstr *, SmallVector<const MachineOperand *>, 2>
629 SpilledOperandsMap;
630 for (MachineOperand *MO : LRIDbgOperands)
631 SpilledOperandsMap[MO->getParent()].push_back(MO);
632 for (const auto &MISpilledOperands : SpilledOperandsMap) {
633 MachineInstr &DBG = *MISpilledOperands.first;
634 // We don't have enough support for tracking operands of DBG_VALUE_LISTs.
635 if (DBG.isDebugValueList())
636 continue;
637 MachineInstr *NewDV = buildDbgValueForSpill(
638 *MBB, Before, *MISpilledOperands.first, FI, MISpilledOperands.second);
639 assert(NewDV->getParent() == MBB && "dangling parent pointer");
640 (void)NewDV;
641 LLVM_DEBUG(dbgs() << "Inserting debug info due to spill:\n" << *NewDV);
642
643 if (LiveOut) {
644 // We need to insert a DBG_VALUE at the end of the block if the spill slot
645 // is live out, but there is another use of the value after the
646 // spill. This will allow LiveDebugValues to see the correct live out
647 // value to propagate to the successors.
648 MachineInstr *ClonedDV = MBB->getParent()->CloneMachineInstr(NewDV);
649 MBB->insert(FirstTerm, ClonedDV);
650 LLVM_DEBUG(dbgs() << "Cloning debug info due to live out spill\n");
651 }
652
653 // Rewrite unassigned dbg_values to use the stack slot.
654 // TODO We can potentially do this for list debug values as well if we know
655 // how the dbg_values are getting unassigned.
656 if (DBG.isNonListDebugValue()) {
657 MachineOperand &MO = DBG.getDebugOperand(0);
658 if (MO.isReg() && !MO.getReg()) {
660 }
661 }
662 }
663 // Now this register is spilled there is should not be any DBG_VALUE
664 // pointing to this register because they are all pointing to spilled value
665 // now.
666 LRIDbgOperands.clear();
667}
668
669/// Insert reload instruction for \p PhysReg before \p Before.
670void RegAllocFastImpl::reload(MachineBasicBlock::iterator Before,
671 Register VirtReg, MCRegister PhysReg) {
672 LLVM_DEBUG(dbgs() << "Reloading " << printReg(VirtReg, TRI) << " into "
673 << printReg(PhysReg, TRI) << '\n');
674 int FI = getStackSpaceFor(VirtReg);
675 const TargetRegisterClass &RC = *MRI->getRegClass(VirtReg);
676 TII->loadRegFromStackSlot(*MBB, Before, PhysReg, FI, &RC, VirtReg);
677 ++NumLoads;
678}
679
680/// Get basic block begin insertion point.
681/// This is not just MBB.begin() because surprisingly we have EH_LABEL
682/// instructions marking the begin of a basic block. This means we must insert
683/// new instructions after such labels...
684MachineBasicBlock::iterator RegAllocFastImpl::getMBBBeginInsertionPoint(
685 MachineBasicBlock &MBB, SmallSet<Register, 2> &PrologLiveIns) const {
687 while (I != MBB.end()) {
688 if (I->isLabel()) {
689 ++I;
690 continue;
691 }
692
693 // Skip prologues and inlineasm_br spills to place reloads afterwards.
694 if (!TII->isBasicBlockPrologue(*I) && !mayBeSpillFromInlineAsmBr(*I))
695 break;
696
697 // However if a prolog instruction reads a register that needs to be
698 // reloaded, the reload should be inserted before the prolog.
699 for (MachineOperand &MO : I->operands()) {
700 if (MO.isReg())
701 PrologLiveIns.insert(MO.getReg());
702 }
703
704 ++I;
705 }
706
707 return I;
708}
709
710/// Reload all currently assigned virtual registers.
711void RegAllocFastImpl::reloadAtBegin(MachineBasicBlock &MBB) {
712 if (LiveVirtRegs.empty())
713 return;
714
715 // Mark live-in registers so the loop below skips reloads into them. The
716 // virtual register mappings this overwrites are not needed anymore.
717 for (MachineBasicBlock::RegisterMaskPair P : MBB.liveins())
718 setPhysRegState(P.PhysReg, regLiveIn);
719
720 SmallSet<Register, 2> PrologLiveIns;
721
722 // The LiveRegMap is keyed by an unsigned (the virtreg number), so the order
723 // of spilling here is deterministic, if arbitrary.
724 MachineBasicBlock::iterator InsertBefore =
725 getMBBBeginInsertionPoint(MBB, PrologLiveIns);
726 for (const LiveReg &LR : LiveVirtRegs) {
727 MCRegister PhysReg = LR.PhysReg;
728 if (!PhysReg || LR.Error)
729 continue;
730
731 MCRegUnit FirstUnit = *TRI->regunits(PhysReg).begin();
732 if (getRegUnitState(FirstUnit) == regLiveIn)
733 continue;
734
736 "no reload in start block. Missing vreg def?");
737
738 if (PrologLiveIns.count(PhysReg)) {
739 // FIXME: Theoretically this should use an insert point skipping labels
740 // but I'm not sure how labels should interact with prolog instruction
741 // that need reloads.
742 reload(MBB.begin(), LR.VirtReg, PhysReg);
743 } else
744 reload(InsertBefore, LR.VirtReg, PhysReg);
745 }
746 LiveVirtRegs.clear();
747}
748
749/// Handle the direct use of a physical register. Displace whatever occupies it
750/// and mark it pre-assigned: backwards, a use means live from here upward.
751/// Returns false if nothing was displaced, so the use is a kill. This may add
752/// implicit kills to MO->getParent() and invalidate MO.
753bool RegAllocFastImpl::usePhysReg(MachineInstr &MI, MCRegister Reg) {
754 assert(Reg.isPhysical() && "expected physreg");
755 bool displacedAny = displacePhysReg(MI, Reg);
756 setPhysRegState(Reg, regPreAssigned);
757 markRegUsedInInstr(Reg);
758 return displacedAny;
759}
760
761/// Displace whatever holds \p Reg and reserve it, so a virtual register def
762/// cannot land on a register this instruction already writes. Released in the
763/// free-def-operands step, or after the uses for an early clobber; if the
764/// instruction also reads \p Reg it ends up reserved for the code above.
765bool RegAllocFastImpl::definePhysReg(MachineInstr &MI, MCRegister Reg) {
766 bool displacedAny = displacePhysReg(MI, Reg);
767 setPhysRegState(Reg, regPreAssigned);
768 return displacedAny;
769}
770
771/// Mark PhysReg as reserved or free after spilling any virtregs. This is very
772/// similar to defineVirtReg except the physreg is reserved instead of
773/// allocated.
774bool RegAllocFastImpl::displacePhysReg(MachineInstr &MI, MCRegister PhysReg) {
775 bool displacedAny = false;
776
777 for (MCRegUnit Unit : TRI->regunits(PhysReg)) {
778 switch (unsigned VirtReg = getRegUnitState(Unit)) {
779 default: {
780 LiveRegMap::iterator LRI = findLiveVirtReg(VirtReg);
781 assert(LRI != LiveVirtRegs.end() && "datastructures in sync");
782 MachineBasicBlock::iterator ReloadBefore =
783 std::next((MachineBasicBlock::iterator)MI.getIterator());
784 while (mayBeSpillFromInlineAsmBr(*ReloadBefore))
785 ++ReloadBefore;
786 reload(ReloadBefore, VirtReg, LRI->PhysReg);
787
788 setPhysRegState(LRI->PhysReg, regFree);
789 LRI->PhysReg = MCRegister();
790 LRI->Reloaded = true;
791 displacedAny = true;
792 break;
793 }
794 case regPreAssigned:
795 setRegUnitState(Unit, regFree);
796 displacedAny = true;
797 break;
798 case regFree:
799 break;
800 }
801 }
802 return displacedAny;
803}
804
805void RegAllocFastImpl::freePhysReg(MCRegister PhysReg) {
806 LLVM_DEBUG(dbgs() << "Freeing " << printReg(PhysReg, TRI) << ':');
807
808 MCRegUnit FirstUnit = *TRI->regunits(PhysReg).begin();
809 switch (unsigned VirtReg = getRegUnitState(FirstUnit)) {
810 case regFree:
811 LLVM_DEBUG(dbgs() << '\n');
812 return;
813 case regPreAssigned:
814 LLVM_DEBUG(dbgs() << '\n');
815 setPhysRegState(PhysReg, regFree);
816 return;
817 default: {
818 LiveRegMap::iterator LRI = findLiveVirtReg(VirtReg);
819 assert(LRI != LiveVirtRegs.end());
820 LLVM_DEBUG(dbgs() << ' ' << printReg(LRI->VirtReg, TRI) << '\n');
821 setPhysRegState(LRI->PhysReg, regFree);
822 LRI->PhysReg = MCRegister();
823 }
824 return;
825 }
826}
827
828/// Return the cost of spilling clearing out PhysReg and aliases so it is free
829/// for allocation. Returns 0 when PhysReg is free or disabled with all aliases
830/// disabled - it can be allocated directly.
831/// \returns spillImpossible when PhysReg or an alias can't be spilled.
832unsigned RegAllocFastImpl::calcSpillCost(MCPhysReg PhysReg) const {
833 for (MCRegUnit Unit : TRI->regunits(PhysReg)) {
834 switch (unsigned VirtReg = getRegUnitState(Unit)) {
835 case regFree:
836 break;
837 case regPreAssigned:
838 LLVM_DEBUG(dbgs() << "Cannot spill pre-assigned "
839 << printReg(PhysReg, TRI) << '\n');
840 return spillImpossible;
841 default: {
842 bool SureSpill = StackSlotForVirtReg[VirtReg] != -1 ||
843 findLiveVirtReg(VirtReg)->LiveOut;
844 return SureSpill ? spillClean : spillDirty;
845 }
846 }
847 }
848 return 0;
849}
850
851void RegAllocFastImpl::assignDanglingDebugValues(MachineInstr &Definition,
852 Register VirtReg,
853 MCRegister Reg) {
854 auto UDBGValIter = DanglingDbgValues.find(VirtReg);
855 if (UDBGValIter == DanglingDbgValues.end())
856 return;
857
858 SmallVectorImpl<MachineInstr *> &Dangling = UDBGValIter->second;
859 for (MachineInstr *DbgValue : Dangling) {
860 assert(DbgValue->isDebugValue());
861 if (!DbgValue->hasDebugOperandForReg(VirtReg))
862 continue;
863
864 // Test whether the physreg survives from the definition to the DBG_VALUE.
865 MCRegister SetToReg = Reg;
866 unsigned Limit = 20;
867 for (MachineBasicBlock::iterator I = std::next(Definition.getIterator()),
868 E = DbgValue->getIterator();
869 I != E; ++I) {
870 if (I->modifiesRegister(Reg, TRI) || --Limit == 0) {
871 LLVM_DEBUG(dbgs() << "Register did not survive for " << *DbgValue
872 << '\n');
873 SetToReg = MCRegister();
874 break;
875 }
876 }
877 for (MachineOperand &MO : DbgValue->getDebugOperandsForReg(VirtReg)) {
878 MO.setReg(SetToReg);
879 if (SetToReg)
880 MO.setIsRenamable();
881 }
882 }
883 Dangling.clear();
884}
885
886/// This method updates local state so that we know that PhysReg is the
887/// proper container for VirtReg now. The physical register must not be used
888/// for anything else when this is called.
889void RegAllocFastImpl::assignVirtToPhysReg(MachineInstr &AtMI, LiveReg &LR,
890 MCRegister PhysReg) {
891 Register VirtReg = LR.VirtReg;
892 LLVM_DEBUG(dbgs() << "Assigning " << printReg(VirtReg, TRI) << " to "
893 << printReg(PhysReg, TRI) << '\n');
894 assert(!LR.PhysReg && "Already assigned a physreg");
895 assert(PhysReg && "Trying to assign no register");
896 LR.PhysReg = PhysReg;
897 setPhysRegState(PhysReg, VirtReg.id());
898
899 assignDanglingDebugValues(AtMI, VirtReg, PhysReg);
900}
901
902static bool isCoalescable(const MachineInstr &MI) { return MI.isFullCopy(); }
903
904Register RegAllocFastImpl::traceCopyChain(Register Reg) const {
905 static const unsigned ChainLengthLimit = 3;
906 for (unsigned C = 0; C <= ChainLengthLimit; ++C) {
907 if (Reg.isPhysical())
908 return Reg;
910
911 const MachineOperand *DefMO = MRI->getOneDef(Reg);
912 if (!DefMO)
913 return Register();
914 const MachineInstr *Def = DefMO->getParent();
915 if (!isCoalescable(*Def))
916 return Register();
917 Reg = Def->getOperand(1).getReg();
918 }
919 return Register();
920}
921
922/// Check if any of \p VirtReg's definitions is a copy. If it is follow the
923/// chain of copies to check whether we reach a physical register we can
924/// coalesce with.
925Register RegAllocFastImpl::traceCopies(Register VirtReg) const {
926 static const unsigned DefLimit = 3;
927 unsigned C = 0;
928 for (const MachineInstr &MI : MRI->def_instructions(VirtReg)) {
929 if (isCoalescable(MI)) {
930 Register Reg = MI.getOperand(1).getReg();
931 Reg = traceCopyChain(Reg);
932 if (Reg.isValid())
933 return Reg;
934 }
935
936 if (++C >= DefLimit)
937 break;
938 }
939 return Register();
940}
941
942/// Allocates a physical register for VirtReg.
943void RegAllocFastImpl::allocVirtReg(MachineInstr &MI, LiveReg &LR,
944 Register Hint0, bool LookAtPhysRegUses) {
945 const Register VirtReg = LR.VirtReg;
946 assert(!LR.PhysReg);
947
948 const TargetRegisterClass &RC = *MRI->getRegClass(VirtReg);
949 LLVM_DEBUG(dbgs() << "Search register for " << printReg(VirtReg)
950 << " in class " << TRI->getRegClassName(&RC)
951 << " with hint " << printReg(Hint0, TRI) << '\n');
952
953 // Take hint when possible.
954 if (Hint0.isPhysical() && MRI->isAllocatable(Hint0) && RC.contains(Hint0) &&
955 !isRegUsedInInstr(Hint0, LookAtPhysRegUses)) {
956 // Take hint if the register is currently free.
957 if (isPhysRegFree(Hint0)) {
958 LLVM_DEBUG(dbgs() << "\tPreferred Register 1: " << printReg(Hint0, TRI)
959 << '\n');
960 assignVirtToPhysReg(MI, LR, Hint0);
961 return;
962 } else {
963 LLVM_DEBUG(dbgs() << "\tPreferred Register 0: " << printReg(Hint0, TRI)
964 << " occupied\n");
965 }
966 } else {
967 Hint0 = Register();
968 }
969
970 // Try other hint.
971 Register Hint1 = traceCopies(VirtReg);
972 if (Hint1.isPhysical() && MRI->isAllocatable(Hint1) && RC.contains(Hint1) &&
973 !isRegUsedInInstr(Hint1, LookAtPhysRegUses)) {
974 // Take hint if the register is currently free.
975 if (isPhysRegFree(Hint1)) {
976 LLVM_DEBUG(dbgs() << "\tPreferred Register 0: " << printReg(Hint1, TRI)
977 << '\n');
978 assignVirtToPhysReg(MI, LR, Hint1);
979 return;
980 } else {
981 LLVM_DEBUG(dbgs() << "\tPreferred Register 1: " << printReg(Hint1, TRI)
982 << " occupied\n");
983 }
984 } else {
985 Hint1 = Register();
986 }
987
988 MCPhysReg BestReg = 0;
989 unsigned BestCost = spillImpossible;
990 ArrayRef<MCPhysReg> AllocationOrder = RegClassInfo.getOrder(&RC);
991 for (MCPhysReg PhysReg : AllocationOrder) {
992 LLVM_DEBUG(dbgs() << "\tRegister: " << printReg(PhysReg, TRI) << ' ');
993 if (isRegUsedInInstr(PhysReg, LookAtPhysRegUses)) {
994 LLVM_DEBUG(dbgs() << "already used in instr.\n");
995 continue;
996 }
997
998 unsigned Cost = calcSpillCost(PhysReg);
999 LLVM_DEBUG(dbgs() << "Cost: " << Cost << " BestCost: " << BestCost << '\n');
1000 // Immediate take a register with cost 0.
1001 if (Cost == 0) {
1002 assignVirtToPhysReg(MI, LR, PhysReg);
1003 return;
1004 }
1005
1006 if (PhysReg == Hint0 || PhysReg == Hint1)
1007 Cost -= spillPrefBonus;
1008
1009 if (Cost < BestCost) {
1010 BestReg = PhysReg;
1011 BestCost = Cost;
1012 }
1013 }
1014
1015 if (!BestReg) {
1016 // Nothing we can do: Report an error and keep going with an invalid
1017 // allocation.
1018 LR.PhysReg = getErrorAssignment(LR, MI, RC);
1019 LR.Error = true;
1020 return;
1021 }
1022
1023 displacePhysReg(MI, BestReg);
1024 assignVirtToPhysReg(MI, LR, BestReg);
1025}
1026
1027void RegAllocFastImpl::allocVirtRegUndef(MachineOperand &MO) {
1028 assert(MO.isUndef() && "expected undef use");
1029 Register VirtReg = MO.getReg();
1030 assert(VirtReg.isVirtual() && "Expected virtreg");
1031 if (!shouldAllocateRegister(VirtReg))
1032 return;
1033
1034 LiveRegMap::iterator LRI = findLiveVirtReg(VirtReg);
1035 MCRegister PhysReg;
1036 bool IsRenamable = true;
1037 if (LRI != LiveVirtRegs.end() && LRI->PhysReg) {
1038 PhysReg = LRI->PhysReg;
1039 } else {
1040 const TargetRegisterClass &RC = *MRI->getRegClass(VirtReg);
1041 ArrayRef<MCPhysReg> AllocationOrder = RegClassInfo.getOrder(&RC);
1042 if (AllocationOrder.empty()) {
1043 // All registers in the class were reserved.
1044 //
1045 // It might be OK to take any entry from the class as this is an undef
1046 // use, but accepting this would give different behavior than greedy and
1047 // basic.
1048 PhysReg = getErrorAssignment(*LRI, *MO.getParent(), RC);
1049 LRI->Error = true;
1050 IsRenamable = false;
1051 } else
1052 PhysReg = AllocationOrder.front();
1053 }
1054
1055 unsigned SubRegIdx = MO.getSubReg();
1056 if (SubRegIdx != 0) {
1057 PhysReg = TRI->getSubReg(PhysReg, SubRegIdx);
1058 MO.setSubReg(0);
1059 }
1060 MO.setReg(PhysReg);
1061 MO.setIsRenamable(IsRenamable);
1062}
1063
1064/// Variation of defineVirtReg() with special handling for livethrough regs
1065/// (tied or earlyclobber) that may interfere with preassigned uses.
1066/// \return true if MI's MachineOperands were re-arranged/invalidated.
1067bool RegAllocFastImpl::defineLiveThroughVirtReg(MachineInstr &MI,
1068 unsigned OpNum,
1069 Register VirtReg) {
1070 if (!shouldAllocateRegister(VirtReg))
1071 return false;
1072 LiveRegMap::iterator LRI = findLiveVirtReg(VirtReg);
1073 if (LRI != LiveVirtRegs.end()) {
1074 MCRegister PrevReg = LRI->PhysReg;
1075 if (PrevReg && isRegUsedInInstr(PrevReg, true)) {
1076 LLVM_DEBUG(dbgs() << "Need new assignment for " << printReg(PrevReg, TRI)
1077 << " (tied/earlyclobber resolution)\n");
1078 freePhysReg(PrevReg);
1079 LRI->PhysReg = MCRegister();
1080 allocVirtReg(MI, *LRI, Register(), true);
1081 MachineBasicBlock::iterator InsertBefore =
1082 std::next((MachineBasicBlock::iterator)MI.getIterator());
1083 LLVM_DEBUG(dbgs() << "Copy " << printReg(LRI->PhysReg, TRI) << " to "
1084 << printReg(PrevReg, TRI) << '\n');
1085 BuildMI(*MBB, InsertBefore, MI.getDebugLoc(),
1086 TII->get(TargetOpcode::COPY), PrevReg)
1087 .addReg(LRI->PhysReg, llvm::RegState::Kill);
1088 }
1089 MachineOperand &MO = MI.getOperand(OpNum);
1090 if (MO.getSubReg() && !MO.isUndef()) {
1091 LRI->LastUse = &MI;
1092 }
1093 }
1094 return defineVirtReg(MI, OpNum, VirtReg, true);
1095}
1096
1097/// Allocates a register for VirtReg definition. Typically the register is
1098/// already assigned from a use of the virtreg, however we still need to
1099/// perform an allocation if:
1100/// - It is a dead definition without any uses.
1101/// - The value is live out and all uses are in different basic blocks.
1102///
1103/// \return true if MI's MachineOperands were re-arranged/invalidated.
1104bool RegAllocFastImpl::defineVirtReg(MachineInstr &MI, unsigned OpNum,
1105 Register VirtReg, bool LookAtPhysRegUses) {
1106 assert(VirtReg.isVirtual() && "Not a virtual register");
1107 if (!shouldAllocateRegister(VirtReg))
1108 return false;
1109 MachineOperand &MO = MI.getOperand(OpNum);
1110 LiveRegMap::iterator LRI;
1111 bool New;
1112 std::tie(LRI, New) = LiveVirtRegs.insert(LiveReg(VirtReg));
1113 if (New) {
1114 if (!MO.isDead()) {
1115 if (mayLiveOut(VirtReg)) {
1116 LRI->LiveOut = true;
1117 } else {
1118 // It is a dead def without the dead flag; add the flag now.
1119 MO.setIsDead(true);
1120 }
1121 }
1122 }
1123 if (!LRI->PhysReg) {
1124 allocVirtReg(MI, *LRI, Register(), LookAtPhysRegUses);
1125 } else {
1126 assert((!isRegUsedInInstr(LRI->PhysReg, LookAtPhysRegUses) || LRI->Error) &&
1127 "TODO: preassign mismatch");
1128 LLVM_DEBUG(dbgs() << "In def of " << printReg(VirtReg, TRI)
1129 << " use existing assignment to "
1130 << printReg(LRI->PhysReg, TRI) << '\n');
1131 }
1132
1133 MCRegister PhysReg = LRI->PhysReg;
1134 // Either flag means a reader below depends on the slot.
1135 if (LRI->Reloaded || LRI->LiveOut) {
1136 if (!MI.isImplicitDef()) {
1137 MachineBasicBlock::iterator SpillBefore =
1138 std::next((MachineBasicBlock::iterator)MI.getIterator());
1139 LLVM_DEBUG(dbgs() << "Spill Reason: LO: " << LRI->LiveOut
1140 << " RL: " << LRI->Reloaded << '\n');
1141 bool Kill = LRI->LastUse == nullptr;
1142 spill(SpillBefore, VirtReg, PhysReg, Kill, LRI->LiveOut);
1143
1144 // We need to place additional spills for each indirect destination of an
1145 // INLINEASM_BR.
1146 if (MI.getOpcode() == TargetOpcode::INLINEASM_BR) {
1147 int FI = StackSlotForVirtReg[VirtReg];
1148 const TargetRegisterClass &RC = *MRI->getRegClass(VirtReg);
1149 for (MachineOperand &MO : MI.operands()) {
1150 if (MO.isMBB()) {
1151 MachineBasicBlock *Succ = MO.getMBB();
1152 TII->storeRegToStackSlot(*Succ, Succ->begin(), PhysReg, Kill, FI,
1153 &RC, VirtReg);
1154 ++NumStores;
1155 Succ->addLiveIn(PhysReg);
1156 }
1157 }
1158 }
1159
1160 LRI->LastUse = nullptr;
1161 }
1162 // A def above spills only if a displacement above reloads again.
1163 LRI->LiveOut = false;
1164 LRI->Reloaded = false;
1165 }
1166 if (MI.getOpcode() == TargetOpcode::BUNDLE) {
1167 BundleVirtRegsMap[VirtReg] = *LRI;
1168 }
1169 markRegUsedInInstr(PhysReg);
1170 return setPhysReg(MI, MO, *LRI);
1171}
1172
1173/// Allocates a register for a VirtReg use.
1174/// \return true if MI's MachineOperands were re-arranged/invalidated.
1175bool RegAllocFastImpl::useVirtReg(MachineInstr &MI, MachineOperand &MO,
1176 Register VirtReg) {
1177 assert(VirtReg.isVirtual() && "Not a virtual register");
1178 if (!shouldAllocateRegister(VirtReg))
1179 return false;
1180 LiveRegMap::iterator LRI;
1181 bool New;
1182 std::tie(LRI, New) = LiveVirtRegs.insert(LiveReg(VirtReg));
1183 if (New) {
1184 if (!MO.isKill()) {
1185 if (mayLiveOut(VirtReg)) {
1186 LRI->LiveOut = true;
1187 } else {
1188 // It is a last (killing) use without the kill flag; add the flag now.
1189 MO.setIsKill(true);
1190 }
1191 }
1192 } else {
1193 assert((!MO.isKill() || LRI->LastUse == &MI) && "Invalid kill flag");
1194 }
1195
1196 // If necessary allocate a register.
1197 if (!LRI->PhysReg) {
1198 assert(!MO.isTied() && "tied op should be allocated");
1199 Register Hint;
1200 if (MI.isCopy() && MI.getOperand(1).getSubReg() == 0) {
1201 Hint = MI.getOperand(0).getReg();
1202 if (Hint.isVirtual()) {
1203 assert(!shouldAllocateRegister(Hint));
1204 Hint = Register();
1205 } else {
1206 assert(Hint.isPhysical() &&
1207 "Copy destination should already be assigned");
1208 }
1209 }
1210 allocVirtReg(MI, *LRI, Hint, false);
1211 }
1212
1213 LRI->LastUse = &MI;
1214
1215 if (MI.getOpcode() == TargetOpcode::BUNDLE) {
1216 BundleVirtRegsMap[VirtReg] = *LRI;
1217 }
1218 markRegUsedInInstr(LRI->PhysReg);
1219 return setPhysReg(MI, MO, *LRI);
1220}
1221
1222/// Query a physical register to use as a filler in contexts where the
1223/// allocation has failed. This will raise an error, but not abort the
1224/// compilation.
1225MCPhysReg RegAllocFastImpl::getErrorAssignment(const LiveReg &LR,
1226 MachineInstr &MI,
1227 const TargetRegisterClass &RC) {
1228 MachineFunction &MF = *MI.getMF();
1229
1230 // Avoid repeating the error every time a register is used.
1231 bool EmitError = !MF.getProperties().hasFailedRegAlloc();
1232 if (EmitError)
1233 MF.getProperties().setFailedRegAlloc();
1234
1235 // If the allocation order was empty, all registers in the class were
1236 // probably reserved. Fall back to taking the first register in the class,
1237 // even if it's reserved.
1238 ArrayRef<MCPhysReg> AllocationOrder = RegClassInfo.getOrder(&RC);
1239 if (AllocationOrder.empty()) {
1240 const Function &Fn = MF.getFunction();
1241 if (EmitError) {
1242 Fn.getContext().diagnose(DiagnosticInfoRegAllocFailure(
1243 "no registers from class available to allocate", Fn,
1244 MI.getDebugLoc()));
1245 }
1246
1247 ArrayRef<MCPhysReg> RawRegs = RC.getRegisters();
1248 assert(!RawRegs.empty() && "register classes cannot have no registers");
1249 return RawRegs.front();
1250 }
1251
1252 if (!LR.Error && EmitError) {
1253 // Nothing we can do: Report an error and keep going with an invalid
1254 // allocation.
1255 if (MI.isInlineAsm()) {
1256 MI.emitInlineAsmError(
1257 "inline assembly requires more registers than available");
1258 } else {
1259 const Function &Fn = MBB->getParent()->getFunction();
1260 Fn.getContext().diagnose(DiagnosticInfoRegAllocFailure(
1261 "ran out of registers during register allocation", Fn,
1262 MI.getDebugLoc()));
1263 }
1264 }
1265
1266 return AllocationOrder.front();
1267}
1268
1269/// Changes operand OpNum in MI the refer the PhysReg, considering subregs.
1270/// \return true if MI's MachineOperands were re-arranged/invalidated.
1271bool RegAllocFastImpl::setPhysReg(MachineInstr &MI, MachineOperand &MO,
1272 const LiveReg &Assignment) {
1273 MCRegister PhysReg = Assignment.PhysReg;
1274 assert(PhysReg && "assignments should always be to a valid physreg");
1275
1276 if (LLVM_UNLIKELY(Assignment.Error)) {
1277 // Make sure we don't set renamable in error scenarios, as we may have
1278 // assigned to a reserved register.
1279 if (MO.isUse())
1280 MO.setIsUndef(true);
1281 }
1282
1283 if (!MO.getSubReg()) {
1284 MO.setReg(PhysReg);
1285 MO.setIsRenamable(!Assignment.Error);
1286 return false;
1287 }
1288
1289 // Handle subregister index.
1290 MO.setReg(TRI->getSubReg(PhysReg, MO.getSubReg()));
1291 MO.setIsRenamable(!Assignment.Error);
1292
1293 // Note: We leave the subreg number around a little longer in case of defs.
1294 // This is so that the register freeing logic in allocateInstruction can still
1295 // recognize this as subregister defs. The code there will clear the number.
1296 if (!MO.isDef())
1297 MO.setSubReg(0);
1298
1299 // A kill flag implies killing the full register. Add corresponding super
1300 // register kill.
1301 if (MO.isKill()) {
1302 MI.addRegisterKilled(PhysReg, TRI, true);
1303 // Conservatively assume implicit MOs were re-arranged
1304 return true;
1305 }
1306
1307 // A <def,read-undef> of a sub-register requires an implicit def of the full
1308 // register.
1309 if (MO.isDef() && MO.isUndef()) {
1310 if (MO.isDead())
1311 MI.addRegisterDead(PhysReg, TRI, true);
1312 else
1313 MI.addRegisterDefined(PhysReg, TRI);
1314 // Conservatively assume implicit MOs were re-arranged
1315 return true;
1316 }
1317 return false;
1318}
1319
1320#ifndef NDEBUG
1321
1322void RegAllocFastImpl::dumpState() const {
1323 for (MCRegUnit Unit : TRI->regunits()) {
1324 switch (unsigned VirtReg = getRegUnitState(Unit)) {
1325 case regFree:
1326 break;
1327 case regPreAssigned:
1328 dbgs() << " " << printRegUnit(Unit, TRI) << "[P]";
1329 break;
1330 case regLiveIn:
1331 llvm_unreachable("Should not have regLiveIn in map");
1332 default: {
1333 dbgs() << ' ' << printRegUnit(Unit, TRI) << '=' << printReg(VirtReg);
1334 LiveRegMap::const_iterator I = findLiveVirtReg(VirtReg);
1335 assert(I != LiveVirtRegs.end() && "have LiveVirtRegs entry");
1336 if (I->LiveOut || I->Reloaded) {
1337 dbgs() << '[';
1338 if (I->LiveOut)
1339 dbgs() << 'O';
1340 if (I->Reloaded)
1341 dbgs() << 'R';
1342 dbgs() << ']';
1343 }
1344 assert(TRI->hasRegUnit(I->PhysReg, Unit) && "inverse mapping present");
1345 break;
1346 }
1347 }
1348 }
1349 dbgs() << '\n';
1350 // Check that LiveVirtRegs is the inverse.
1351 for (const LiveReg &LR : LiveVirtRegs) {
1352 Register VirtReg = LR.VirtReg;
1353 assert(VirtReg.isVirtual() && "Bad map key");
1354 MCRegister PhysReg = LR.PhysReg;
1355 if (PhysReg) {
1356 assert(PhysReg.isPhysical() && "mapped to physreg");
1357 for (MCRegUnit Unit : TRI->regunits(PhysReg)) {
1358 assert(getRegUnitState(Unit) == VirtReg && "inverse map valid");
1359 }
1360 }
1361 }
1362}
1363#endif
1364
1365/// Count number of defs consumed from each register class by \p Reg
1366void RegAllocFastImpl::addRegClassDefCounts(
1367 MutableArrayRef<unsigned> RegClassDefCounts, Register Reg) const {
1368 assert(RegClassDefCounts.size() == TRI->getNumRegClasses());
1369
1370 if (Reg.isVirtual()) {
1371 if (!shouldAllocateRegister(Reg))
1372 return;
1373 const TargetRegisterClass *OpRC = MRI->getRegClass(Reg);
1374 for (unsigned RCIdx = 0, RCIdxEnd = TRI->getNumRegClasses();
1375 RCIdx != RCIdxEnd; ++RCIdx) {
1376 const TargetRegisterClass *IdxRC = TRI->getRegClass(RCIdx);
1377 // FIXME: Consider aliasing sub/super registers.
1378 if (OpRC->hasSubClassEq(IdxRC))
1379 ++RegClassDefCounts[RCIdx];
1380 }
1381
1382 return;
1383 }
1384
1385 for (unsigned RCIdx = 0, RCIdxEnd = TRI->getNumRegClasses();
1386 RCIdx != RCIdxEnd; ++RCIdx) {
1387 const TargetRegisterClass *IdxRC = TRI->getRegClass(RCIdx);
1388 for (MCRegAliasIterator Alias(Reg, TRI, true); Alias.isValid(); ++Alias) {
1389 if (IdxRC->contains(*Alias)) {
1390 ++RegClassDefCounts[RCIdx];
1391 break;
1392 }
1393 }
1394 }
1395}
1396
1397/// Compute \ref DefOperandIndexes so it contains the indices of "def" operands
1398/// that are to be allocated. Those are ordered in a way that small classes,
1399/// early clobbers and livethroughs are allocated first.
1400void RegAllocFastImpl::findAndSortDefOperandIndexes(const MachineInstr &MI) {
1401 DefOperandIndexes.clear();
1402
1403 LLVM_DEBUG(dbgs() << "Need to assign livethroughs\n");
1404 for (unsigned I = 0, E = MI.getNumOperands(); I < E; ++I) {
1405 const MachineOperand &MO = MI.getOperand(I);
1406 if (!MO.isReg())
1407 continue;
1408 Register Reg = MO.getReg();
1409 if (MO.readsReg()) {
1410 if (Reg.isPhysical()) {
1411 LLVM_DEBUG(dbgs() << "mark extra used: " << printReg(Reg, TRI) << '\n');
1412 markPhysRegUsedInInstr(Reg);
1413 }
1414 }
1415
1416 if (MO.isDef() && Reg.isVirtual() && shouldAllocateRegister(Reg))
1417 DefOperandIndexes.push_back(I);
1418 }
1419
1420 // Most instructions only have one virtual def, so there's no point in
1421 // computing the possible number of defs for every register class.
1422 if (DefOperandIndexes.size() <= 1)
1423 return;
1424
1425 // Track number of defs which may consume a register from the class. This is
1426 // used to assign registers for possibly-too-small classes first. Example:
1427 // defs are eax, 3 * gr32_abcd, 2 * gr32 => we want to assign the gr32_abcd
1428 // registers first so that the gr32 don't use the gr32_abcd registers before
1429 // we assign these.
1430 SmallVector<unsigned> RegClassDefCounts(TRI->getNumRegClasses(), 0);
1431
1432 for (const MachineOperand &MO : MI.all_defs())
1433 addRegClassDefCounts(RegClassDefCounts, MO.getReg());
1434
1435 llvm::sort(DefOperandIndexes, [&](unsigned I0, unsigned I1) {
1436 const MachineOperand &MO0 = MI.getOperand(I0);
1437 const MachineOperand &MO1 = MI.getOperand(I1);
1438 Register Reg0 = MO0.getReg();
1439 Register Reg1 = MO1.getReg();
1440 const TargetRegisterClass &RC0 = *MRI->getRegClass(Reg0);
1441 const TargetRegisterClass &RC1 = *MRI->getRegClass(Reg1);
1442
1443 // Identify regclass that are easy to use up completely just in this
1444 // instruction.
1445 unsigned ClassSize0 = RegClassInfo.getOrder(&RC0).size();
1446 unsigned ClassSize1 = RegClassInfo.getOrder(&RC1).size();
1447
1448 bool SmallClass0 = ClassSize0 < RegClassDefCounts[RC0.getID()];
1449 bool SmallClass1 = ClassSize1 < RegClassDefCounts[RC1.getID()];
1450 if (SmallClass0 > SmallClass1)
1451 return true;
1452 if (SmallClass0 < SmallClass1)
1453 return false;
1454
1455 // Allocate early clobbers and livethrough operands first.
1456 bool Livethrough0 = MO0.isEarlyClobber() || MO0.isTied() ||
1457 (MO0.getSubReg() == 0 && !MO0.isUndef());
1458 bool Livethrough1 = MO1.isEarlyClobber() || MO1.isTied() ||
1459 (MO1.getSubReg() == 0 && !MO1.isUndef());
1460 if (Livethrough0 > Livethrough1)
1461 return true;
1462 if (Livethrough0 < Livethrough1)
1463 return false;
1464
1465 // Tie-break rule: operand index.
1466 return I0 < I1;
1467 });
1468}
1469
1470// Returns true if this def (MO) ties to a use that actually carries a value
1471// (not undef).
1472static bool isTiedToNotUndef(const MachineInstr &MI, const MachineOperand &MO) {
1473 assert(MO.isDef() && "expected a def operand");
1474 if (!MO.isTied())
1475 return false;
1476 unsigned TiedIdx = MI.findTiedOperandIdx(MI.getOperandNo(&MO));
1477 const MachineOperand &TiedMO = MI.getOperand(TiedIdx);
1478 return !TiedMO.isUndef();
1479}
1480
1481void RegAllocFastImpl::allocateInstruction(MachineInstr &MI) {
1482 // Backwards, a def frees a register and a use occupies it. The phases:
1483 // * pre-assigned physreg defs
1484 // * virtual register defs
1485 // * free the def operands' registers
1486 // * displace registers clobbered by regmasks
1487 // * pre-assigned physreg uses
1488 // * virtual register uses, inserting reloads
1489 // * undef uses
1490 // * free early-clobber defs
1491 //
1492 // Freeing follows the def allocation so a def is not handed a register this
1493 // instruction also writes, and precedes the uses so a use may take one. It
1494 // skips tied defs, whose register the tied use reads, and early-clobber defs,
1495 // freed last so that no use lands on them.
1496
1497 InstrGen += 2;
1498 // In the event we ever get more than 2**31 instructions...
1499 if (LLVM_UNLIKELY(InstrGen == 0)) {
1500 UsedInInstr.assign(UsedInInstr.size(), 0);
1501 InstrGen = 2;
1502 }
1503 RegMasks.clear();
1504 BundleVirtRegsMap.clear();
1505
1506 // Scan for special cases; Apply pre-assigned register defs to state.
1507 bool HasPhysRegUse = false;
1508 bool HasRegMask = false;
1509 bool HasVRegDef = false;
1510 bool HasDef = false;
1511 bool HasEarlyClobber = false;
1512 bool NeedToAssignLiveThroughs = false;
1513 for (MachineOperand &MO : MI.operands()) {
1514 if (MO.isReg()) {
1515 Register Reg = MO.getReg();
1516 if (Reg.isVirtual()) {
1517 if (!shouldAllocateRegister(Reg))
1518 continue;
1519 if (MO.isDef()) {
1520 HasDef = true;
1521 HasVRegDef = true;
1522 if (MO.isEarlyClobber()) {
1523 HasEarlyClobber = true;
1524 NeedToAssignLiveThroughs = true;
1525 }
1526 if (isTiedToNotUndef(MI, MO) ||
1527 (MO.getSubReg() != 0 && !MO.isUndef()))
1528 NeedToAssignLiveThroughs = true;
1529 }
1530 } else if (Reg.isPhysical()) {
1531 if (!MRI->isReserved(Reg)) {
1532 if (MO.isDef()) {
1533 HasDef = true;
1534 bool displacedAny = definePhysReg(MI, Reg);
1535 if (MO.isEarlyClobber())
1536 HasEarlyClobber = true;
1537 if (!displacedAny)
1538 MO.setIsDead(true);
1539 }
1540 if (MO.readsReg())
1541 HasPhysRegUse = true;
1542 }
1543 }
1544 } else if (MO.isRegMask()) {
1545 HasRegMask = true;
1546 RegMasks.push_back(MO.getRegMask());
1547 }
1548 }
1549
1550 // Allocate virtreg defs.
1551 if (HasDef) {
1552 if (HasVRegDef) {
1553 // Note that Implicit MOs can get re-arranged by defineVirtReg(), so loop
1554 // multiple times to ensure no operand is missed.
1555 bool ReArrangedImplicitOps = true;
1556
1557 // Special handling for early clobbers, tied operands or subregister defs:
1558 // Compared to "normal" defs these:
1559 // - Must not use a register that is pre-assigned for a use operand.
1560 // - In order to solve tricky inline assembly constraints we change the
1561 // heuristic to figure out a good operand order before doing
1562 // assignments.
1563 if (NeedToAssignLiveThroughs) {
1564 while (ReArrangedImplicitOps) {
1565 ReArrangedImplicitOps = false;
1566 findAndSortDefOperandIndexes(MI);
1567 for (unsigned OpIdx : DefOperandIndexes) {
1568 MachineOperand &MO = MI.getOperand(OpIdx);
1569 LLVM_DEBUG(dbgs() << "Allocating " << MO << '\n');
1570 Register Reg = MO.getReg();
1571 if (MO.isEarlyClobber() || isTiedToNotUndef(MI, MO) ||
1572 (MO.getSubReg() && !MO.isUndef())) {
1573 ReArrangedImplicitOps = defineLiveThroughVirtReg(MI, OpIdx, Reg);
1574 } else {
1575 ReArrangedImplicitOps = defineVirtReg(MI, OpIdx, Reg);
1576 }
1577 // Implicit operands of MI were re-arranged,
1578 // re-compute DefOperandIndexes.
1579 if (ReArrangedImplicitOps)
1580 break;
1581 }
1582 }
1583 } else {
1584 // Assign virtual register defs.
1585 while (ReArrangedImplicitOps) {
1586 ReArrangedImplicitOps = false;
1587 for (MachineOperand &MO : MI.all_defs()) {
1588 Register Reg = MO.getReg();
1589 if (Reg.isVirtual()) {
1590 ReArrangedImplicitOps =
1591 defineVirtReg(MI, MI.getOperandNo(&MO), Reg);
1592 if (ReArrangedImplicitOps)
1593 break;
1594 }
1595 }
1596 }
1597 }
1598 }
1599
1600 // Free registers occupied by defs.
1601 // Iterate operands in reverse order, so we see the implicit super register
1602 // defs first (we added them earlier in case of <def,read-undef>).
1603 for (MachineOperand &MO : reverse(MI.all_defs())) {
1604 Register Reg = MO.getReg();
1605
1606 // subreg defs don't free the full register. We left the subreg number
1607 // around as a marker in setPhysReg() to recognize this case here.
1608 if (Reg.isPhysical() && MO.getSubReg() != 0) {
1609 MO.setSubReg(0);
1610 continue;
1611 }
1612
1613 assert((!MO.isTied() || !isClobberedByRegMasks(MO.getReg())) &&
1614 "tied def assigned to clobbered register");
1615
1616 // Do not free tied operands and early clobbers.
1617 if (isTiedToNotUndef(MI, MO) || MO.isEarlyClobber())
1618 continue;
1619 if (!Reg)
1620 continue;
1621 if (Reg.isVirtual()) {
1622 assert(!shouldAllocateRegister(Reg));
1623 continue;
1624 }
1626 if (MRI->isReserved(Reg))
1627 continue;
1628 freePhysReg(Reg);
1629 unmarkRegUsedInInstr(Reg);
1630 }
1631 }
1632
1633 // A regmask is a def of every clobbered register: reload what lives in one
1634 // below MI. Nothing is reserved, so the uses may still take those registers.
1635 if (HasRegMask) {
1636 assert(!RegMasks.empty() && "expected RegMask");
1637 // MRI bookkeeping.
1638 for (const auto *RM : RegMasks)
1640
1641 for (const LiveReg &LR : LiveVirtRegs) {
1642 MCRegister PhysReg = LR.PhysReg;
1643 if (PhysReg && isClobberedByRegMasks(PhysReg))
1644 displacePhysReg(MI, PhysReg);
1645 }
1646 }
1647
1648 // Apply pre-assigned register uses to state.
1649 if (HasPhysRegUse) {
1650 for (MachineOperand &MO : MI.operands()) {
1651 if (!MO.isReg() || !MO.readsReg())
1652 continue;
1653 Register Reg = MO.getReg();
1654 if (!Reg.isPhysical())
1655 continue;
1656 if (MRI->isReserved(Reg))
1657 continue;
1658 if (!usePhysReg(MI, Reg))
1659 MO.setIsKill(true);
1660 }
1661 }
1662
1663 // Allocate virtreg uses and insert reloads as necessary.
1664 // Implicit MOs can get moved/removed by useVirtReg(), so loop multiple
1665 // times to ensure no operand is missed.
1666 bool HasUndefUse = false;
1667 bool ReArrangedImplicitMOs = true;
1668 while (ReArrangedImplicitMOs) {
1669 ReArrangedImplicitMOs = false;
1670 for (MachineOperand &MO : MI.operands()) {
1671 if (!MO.isReg() || !MO.isUse())
1672 continue;
1673 Register Reg = MO.getReg();
1674 if (!Reg.isVirtual() || !shouldAllocateRegister(Reg))
1675 continue;
1676
1677 if (MO.isUndef()) {
1678 HasUndefUse = true;
1679 continue;
1680 }
1681
1682 // Populate MayLiveAcrossBlocks now: these uses are about to be rewritten
1683 // to physregs, so a def block allocated later can no longer see them.
1684 mayLiveIn(Reg);
1685
1686 assert(!MO.isInternalRead() && "Bundles not supported");
1687 assert(MO.readsReg() && "reading use");
1688 ReArrangedImplicitMOs = useVirtReg(MI, MO, Reg);
1689 if (ReArrangedImplicitMOs)
1690 break;
1691 }
1692 }
1693
1694 // Allocate undef operands. This is a separate step because in a situation
1695 // like ` = OP undef %X, %X` both operands need the same register assign
1696 // so we should perform the normal assignment first.
1697 if (HasUndefUse) {
1698 for (MachineOperand &MO : MI.all_uses()) {
1699 Register Reg = MO.getReg();
1700 if (!Reg.isVirtual() || !shouldAllocateRegister(Reg))
1701 continue;
1702
1703 assert(MO.isUndef() && "Should only have undef virtreg uses left");
1704 allocVirtRegUndef(MO);
1705 }
1706 }
1707
1708 // Free early clobbers. Last, because they must not share a register with any
1709 // use.
1710 if (HasEarlyClobber) {
1711 for (MachineOperand &MO : reverse(MI.all_defs())) {
1712 if (!MO.isEarlyClobber())
1713 continue;
1714 assert(!MO.getSubReg() && "should be already handled in def processing");
1715
1716 Register Reg = MO.getReg();
1717 if (!Reg)
1718 continue;
1719 if (Reg.isVirtual()) {
1720 assert(!shouldAllocateRegister(Reg));
1721 continue;
1722 }
1723 assert(Reg.isPhysical() && "should have register assigned");
1724
1725 // We sometimes get odd situations like:
1726 // early-clobber %x0 = INSTRUCTION %x0
1727 // which is semantically questionable as the early-clobber should
1728 // apply before the use. But in practice we consider the use to
1729 // happen before the early clobber now. Don't free the early clobber
1730 // register in this case.
1731 if (MI.readsRegister(Reg, TRI))
1732 continue;
1733
1734 freePhysReg(Reg);
1735 }
1736 }
1737
1738 LLVM_DEBUG(dbgs() << "<< " << MI);
1739 if (MI.isCopy() &&
1740 (MI.getOperand(0).getReg() == MI.getOperand(1).getReg() ||
1741 MI.getOperand(0).isDead()) &&
1742 MI.getNumOperands() == 2) {
1743 LLVM_DEBUG(dbgs() << "Mark unnecessary copy for removal: " << MI);
1744 Coalesced.push_back(&MI);
1745 }
1746}
1747
1748void RegAllocFastImpl::handleDebugValue(MachineInstr &MI) {
1749 // Ignore DBG_VALUEs that aren't based on virtual registers. These are
1750 // mostly constants and frame indices.
1751 assert(MI.isDebugValue() && "not a DBG_VALUE*");
1752 for (const auto &MO : MI.debug_operands()) {
1753 if (!MO.isReg())
1754 continue;
1755 Register Reg = MO.getReg();
1756 if (!Reg.isVirtual())
1757 continue;
1758 if (!shouldAllocateRegister(Reg))
1759 continue;
1760
1761 // Already spilled to a stackslot?
1762 int SS = StackSlotForVirtReg[Reg];
1763 if (SS != -1) {
1764 // Modify DBG_VALUE now that the value is in a spill slot.
1766 LLVM_DEBUG(dbgs() << "Rewrite DBG_VALUE for spilled memory: " << MI);
1767 continue;
1768 }
1769
1770 // See if this virtual register has already been allocated to a physical
1771 // register or spilled to a stack slot.
1772 LiveRegMap::iterator LRI = findLiveVirtReg(Reg);
1774 llvm::make_pointer_range(MI.getDebugOperandsForReg(Reg)));
1775
1776 if (LRI != LiveVirtRegs.end() && LRI->PhysReg) {
1777 // Update every use of Reg within MI.
1778 for (auto &RegMO : DbgOps)
1779 setPhysReg(MI, *RegMO, *LRI);
1780 } else {
1781 DanglingDbgValues[Reg].push_back(&MI);
1782 }
1783
1784 // If Reg hasn't been spilled, put this DBG_VALUE in LiveDbgValueMap so
1785 // that future spills of Reg will have DBG_VALUEs.
1786 LiveDbgValueMap[Reg].append(DbgOps.begin(), DbgOps.end());
1787 }
1788}
1789
1790void RegAllocFastImpl::handleBundle(MachineInstr &MI) {
1791 MachineBasicBlock::instr_iterator BundledMI = MI.getIterator();
1792 ++BundledMI;
1793 while (BundledMI->isBundledWithPred()) {
1794 for (MachineOperand &MO : BundledMI->operands()) {
1795 if (!MO.isReg())
1796 continue;
1797
1798 Register Reg = MO.getReg();
1799 if (!Reg.isVirtual() || !shouldAllocateRegister(Reg))
1800 continue;
1801
1802 auto DI = BundleVirtRegsMap.find(Reg);
1803 assert(DI != BundleVirtRegsMap.end() && "Unassigned virtual register");
1804
1805 setPhysReg(MI, MO, DI->second);
1806 }
1807
1808 ++BundledMI;
1809 }
1810}
1811
1812void RegAllocFastImpl::allocateBasicBlock(MachineBasicBlock &MBB) {
1813 this->MBB = &MBB;
1814 LLVM_DEBUG(dbgs() << "\nAllocating " << MBB);
1815
1816 PosIndexes.unsetInitialized();
1817 RegUnitStates.assign(TRI->getNumRegUnits(), regFree);
1818 assert(LiveVirtRegs.empty() && "Mapping not cleared from last block?");
1819
1820 for (const auto &LiveReg : MBB.liveouts())
1821 setPhysRegState(LiveReg.PhysReg, regPreAssigned);
1822
1823 Coalesced.clear();
1824
1825 // Traverse block in reverse order allocating instructions one by one.
1826 for (MachineInstr &MI : reverse(MBB)) {
1827 LLVM_DEBUG(dbgs() << "\n>> " << MI << "Regs:"; dumpState());
1828
1829 // Special handling for debug values. Note that they are not allowed to
1830 // affect codegen of the other instructions in any way.
1831 if (MI.isDebugValue()) {
1832 handleDebugValue(MI);
1833 continue;
1834 }
1835
1836 allocateInstruction(MI);
1837
1838 // Once BUNDLE header is assigned registers, same assignments need to be
1839 // done for bundled MIs.
1840 if (MI.getOpcode() == TargetOpcode::BUNDLE) {
1841 handleBundle(MI);
1842 }
1843 }
1844
1845 LLVM_DEBUG(dbgs() << "Begin Regs:"; dumpState());
1846
1847 // Spill all physical registers holding virtual registers now.
1848 LLVM_DEBUG(dbgs() << "Loading live registers at begin of block.\n");
1849 reloadAtBegin(MBB);
1850
1851 // Erase all the coalesced copies. We are delaying it until now because
1852 // LiveVirtRegs might refer to the instrs.
1853 for (MachineInstr *MI : Coalesced)
1854 MBB.erase(MI);
1855 NumCoalesced += Coalesced.size();
1856
1857 for (auto &UDBGPair : DanglingDbgValues) {
1858 for (MachineInstr *DbgValue : UDBGPair.second) {
1859 assert(DbgValue->isDebugValue() && "expected DBG_VALUE");
1860 // Nothing to do if the vreg was spilled in the meantime.
1861 if (!DbgValue->hasDebugOperandForReg(UDBGPair.first))
1862 continue;
1863 LLVM_DEBUG(dbgs() << "Register did not survive for " << *DbgValue
1864 << '\n');
1865 DbgValue->setDebugValueUndef();
1866 }
1867 }
1868 DanglingDbgValues.clear();
1869
1870 LLVM_DEBUG(MBB.dump());
1871}
1872
1873bool RegAllocFastImpl::runOnMachineFunction(MachineFunction &MF) {
1874 LLVM_DEBUG(dbgs() << "********** FAST REGISTER ALLOCATION **********\n"
1875 << "********** Function: " << MF.getName() << '\n');
1876 MRI = &MF.getRegInfo();
1877 const TargetSubtargetInfo &STI = MF.getSubtarget();
1878 TRI = STI.getRegisterInfo();
1879 TII = STI.getInstrInfo();
1880 MFI = &MF.getFrameInfo();
1881 MRI->freezeReservedRegs();
1882 RegClassInfo.runOnMachineFunction(MF);
1883 unsigned NumRegUnits = TRI->getNumRegUnits();
1884 InstrGen = 0;
1885 UsedInInstr.assign(NumRegUnits, 0);
1886
1887 // initialize the virtual->physical register map to have a 'null'
1888 // mapping for all virtual registers
1889 unsigned NumVirtRegs = MRI->getNumVirtRegs();
1890 StackSlotForVirtReg.resize(NumVirtRegs);
1891 LiveVirtRegs.setUniverse(NumVirtRegs);
1892 MayLiveAcrossBlocks.clear();
1893 MayLiveAcrossBlocks.resize(NumVirtRegs);
1894
1895 // Loop over all of the basic blocks, eliminating virtual register references
1896 for (MachineBasicBlock &MBB : MF)
1897 allocateBasicBlock(MBB);
1898
1899 if (ClearVirtRegs) {
1900 // All machine operands and other references to virtual registers have been
1901 // replaced. Remove the virtual registers.
1902 MRI->clearVirtRegs();
1903 }
1904
1905 StackSlotForVirtReg.clear();
1906 LiveDbgValueMap.clear();
1907 return true;
1908}
1909
1912 MFPropsModifier _(*this, MF);
1913 RegAllocFastImpl Impl(Opts.Filter, Opts.ClearVRegs);
1914 bool Changed = Impl.runOnMachineFunction(MF);
1915 if (!Changed)
1916 return PreservedAnalyses::all();
1918 PA.preserveSet<CFGAnalyses>();
1919 return PA;
1920}
1921
1923 raw_ostream &OS, function_ref<StringRef(StringRef)> MapClassName2PassName) {
1924 bool PrintFilterName = Opts.FilterName != "all";
1925 bool PrintNoClearVRegs = !Opts.ClearVRegs;
1926 bool PrintSemicolon = PrintFilterName && PrintNoClearVRegs;
1927
1928 OS << "regallocfast";
1929 if (PrintFilterName || PrintNoClearVRegs) {
1930 OS << '<';
1931 if (PrintFilterName)
1932 OS << "filter=" << Opts.FilterName;
1933 if (PrintSemicolon)
1934 OS << ';';
1935 if (PrintNoClearVRegs)
1936 OS << "no-clear-vregs";
1937 OS << '>';
1938 }
1939}
1940
1941FunctionPass *llvm::createFastRegisterAllocator() { return new RegAllocFast(); }
1942
1944 bool ClearVirtRegs) {
1945 return new RegAllocFast(Ftor, ClearVirtRegs);
1946}
#define DBG(...)
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
aarch64 promote const
unsigned uint64_t
MachineBasicBlock & MBB
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
#define LLVM_UNLIKELY(EXPR)
Definition Compiler.h:344
This file defines the DenseMap class.
const HexagonInstrInfo * TII
#define _
IRTranslator LLVM IR MI
This file implements an indexed map.
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
Register Reg
Register const TargetRegisterInfo * TRI
This file implements a map that provides insertion order iteration.
Promote Memory to Register
Definition Mem2Reg.cpp:110
#define P(N)
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition PassSupport.h:56
static bool isCoalescable(const MachineInstr &MI)
static cl::opt< bool > IgnoreMissingDefs("rafast-ignore-missing-defs", cl::Hidden)
static bool dominates(InstrPosIndexes &PosIndexes, const MachineInstr &A, const MachineInstr &B)
static RegisterRegAlloc fastRegAlloc("fast", "fast register allocator", createFastRegisterAllocator)
static bool isTiedToNotUndef(const MachineInstr &MI, const MachineOperand &MO)
This file defines the SmallSet class.
This file defines the SmallVector class.
This file defines the SparseSet class derived from the version described in Briggs,...
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:171
#define LLVM_DEBUG(...)
Definition Debug.h:119
LLVM_ABI void setPreservesCFG()
This function should be called by the pass, iff they do not:
Definition Pass.cpp:278
const T & front() const
Get the first element.
Definition ArrayRef.h:144
size_t size() const
Get the array size.
Definition ArrayRef.h:141
bool empty() const
Check if the array is empty.
Definition ArrayRef.h:136
bool test(unsigned Idx) const
Returns true if bit Idx is set.
Definition BitVector.h:482
void resize(unsigned N, bool t=false)
Grow or shrink the bitvector.
Definition BitVector.h:355
void clear()
Removes all bits from the bitvector.
Definition BitVector.h:349
BitVector & set()
Set all bits in the bitvector.
Definition BitVector.h:366
Represents analyses that only rely on functions' control flow.
Definition Analysis.h:73
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:223
iterator end()
Definition DenseMap.h:141
FunctionPass class - This class is used to implement most global optimizations.
Definition Pass.h:314
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function.
Definition Function.cpp:356
void storeRegToStackSlot(MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI, Register SrcReg, bool isKill, int FrameIndex, const TargetRegisterClass *RC, Register VReg, MachineInstr::MIFlag Flags=MachineInstr::NoFlags) const override
Store the specified register of the given register class to the specified stack frame index.
void loadRegFromStackSlot(MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI, Register DestReg, int FrameIndex, const TargetRegisterClass *RC, Register VReg, unsigned SubReg=0, MachineInstr::MIFlag Flags=MachineInstr::NoFlags) const override
Load the specified register of the given register class from the specified stack frame index.
Register isStoreToStackSlot(const MachineInstr &MI, int &FrameIndex) const override
If the specified machine instruction is a direct store to a stack slot, return the virtual or physica...
void resize(typename StorageT::size_type S)
Definition IndexedMap.h:67
LLVM_ABI void diagnose(const DiagnosticInfo &DI)
Report a message to the currently installed diagnostic handler.
unsigned getID() const
getID() - Return the register class ID number.
ArrayRef< MCPhysReg > getRegisters() const
bool contains(MCRegister Reg) const
contains - Return true if the specified register is included in this register class.
bool hasSubClassEq(const MCRegisterClass *RC) const
Returns true if RC is a sub-class of or equal to this class.
constexpr bool isPhysical() const
Return true if the specified register number is in the physical register namespace.
Definition MCRegister.h:72
An RAII based helper class to modify MachineFunctionProperties when running pass.
bool isInlineAsmBrIndirectTarget() const
Returns true if this is the indirect dest of an INLINEASM_BR.
iterator_range< liveout_iterator > liveouts() const
MachineInstrBundleIterator< const MachineInstr > const_iterator
LLVM_ABI instr_iterator insert(instr_iterator I, MachineInstr *M)
Insert MI into the instruction list before I, possibly inside a bundle.
iterator_range< livein_iterator > liveins() const
LLVM_ABI iterator getFirstTerminator()
Returns an iterator to the first terminator instruction of this basic block.
LLVM_ABI void dump() const
Instructions::iterator instr_iterator
void addLiveIn(MCRegister PhysReg, LaneBitmask LaneMask=LaneBitmask::getAll())
Adds the specified register as a live in.
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
LLVM_ABI instr_iterator erase(instr_iterator I)
Remove an instruction from the instruction list and delete it.
LLVM_ABI bool isSuccessor(const MachineBasicBlock *MBB) const
Return true if the specified MBB is a successor of this block.
MachineInstrBundleIterator< MachineInstr > iterator
LLVM_ABI bool isLiveIn(MCRegister Reg, LaneBitmask LaneMask=LaneBitmask::getAll()) const
Return true if the specified register is in the live in set.
bool isSpillSlotObjectIndex(int ObjectIdx) const
Returns true if the specified index corresponds to a spill slot.
LLVM_ABI int CreateSpillStackObject(uint64_t Size, Align Alignment, TargetStackID::Value StackID=TargetStackID::Default)
Create a new statically sized stack object that represents a spill slot, returning a nonnegative iden...
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
StringRef getName() const
getName - Return the name of the corresponding LLVM function.
MachineFrameInfo & getFrameInfo()
getFrameInfo - Return the frame info object for the current function.
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
Function & getFunction()
Return the LLVM function that this machine code represents.
const MachineFunctionProperties & getProperties() const
Get the function properties.
const MachineBasicBlock & front() const
const MachineInstrBuilder & addReg(Register RegNo, RegState Flags={}, unsigned SubReg=0) const
Add a new virtual register operand.
Representation of each machine instruction.
bool hasDebugOperandForReg(Register Reg) const
Returns whether this debug value has at least one debug operand with the register Reg.
void setDebugValueUndef()
Sets all register debug operands in this debug value instruction to be undef.
const MachineBasicBlock * getParent() const
bool isDebugValue() const
MachineOperand class - Representation of each machine instruction operand.
void setSubReg(unsigned subReg)
unsigned getSubReg() const
bool readsReg() const
readsReg - Returns true if this operand reads the previous value of its register.
LLVM_ABI void setIsRenamable(bool Val=true)
bool isReg() const
isReg - Tests if this is a MO_Register operand.
bool isRegMask() const
isRegMask - Tests if this is a MO_RegisterMask operand.
MachineBasicBlock * getMBB() const
void setIsDead(bool Val=true)
LLVM_ABI void setReg(Register Reg)
Change the register this operand corresponds to.
void setIsKill(bool Val=true)
MachineInstr * getParent()
getParent - Return the instruction that this operand belongs to.
void setIsUndef(bool Val=true)
bool isEarlyClobber() const
Register getReg() const
getReg - Returns the register number.
bool isInternalRead() const
static bool clobbersPhysReg(const uint32_t *RegMask, MCRegister PhysReg)
clobbersPhysReg - Returns true if this RegMask clobbers PhysReg.
const uint32_t * getRegMask() const
getRegMask - Returns a bit mask of registers preserved by this RegMask operand.
bool isMBB() const
isMBB - Tests if this is a MO_MachineBasicBlock operand.
LLVM_ABI void freezeReservedRegs()
freezeReservedRegs - Called by the register allocator to freeze the set of reserved registers before ...
const TargetRegisterClass * getRegClass(Register Reg) const
Return the register class of the specified virtual register.
iterator_range< def_instr_iterator > def_instructions(Register Reg) const
bool isReserved(MCRegister PhysReg) const
isReserved - Returns true when PhysReg is a reserved register.
MachineOperand * getOneDef(Register Reg) const
Returns the defining operand if there is exactly one operand defining the specified register,...
LLVM_ABI void clearVirtRegs()
clearVirtRegs - Remove all virtual registers (after physreg assignment).
bool isAllocatable(MCRegister PhysReg) const
isAllocatable - Returns true when PhysReg belongs to an allocatable register class and it hasn't been...
iterator_range< use_instr_nodbg_iterator > use_nodbg_instructions(Register Reg) const
const MachineFunction & getMF() const
void addPhysRegsUsedFromRegMask(const uint32_t *RegMask)
addPhysRegsUsedFromRegMask - Mark any registers not in RegMask as used.
unsigned getNumVirtRegs() const
getNumVirtRegs - Return the number of virtual registers created.
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
LLVM_ABI PreservedAnalyses run(MachineFunction &MF, MachineFunctionAnalysisManager &)
LLVM_ABI void printPipeline(raw_ostream &OS, function_ref< StringRef(StringRef)> MapClassName2PassName)
LLVM_ABI void runOnMachineFunction(const MachineFunction &MF, bool Rev=false)
runOnFunction - Prepare to answer questions about MF.
ArrayRef< MCPhysReg > getOrder(const TargetRegisterClass *RC) const
getOrder - Returns the preferred allocation order for RC.
Wrapper class representing virtual and physical registers.
Definition Register.h:20
unsigned virtRegIndex() const
Convert a virtual register number to a 0-based index.
Definition Register.h:87
constexpr bool isValid() const
Definition Register.h:112
constexpr bool isVirtual() const
Return true if the specified register number is in the virtual register namespace.
Definition Register.h:79
constexpr unsigned id() const
Definition Register.h:100
constexpr bool isPhysical() const
Return true if the specified register number is in the physical register namespace.
Definition Register.h:83
size_type count(const T &V) const
count - Return 1 if the element is in the set, 0 otherwise.
Definition SmallSet.h:176
std::pair< const_iterator, bool > insert(const T &V)
insert - Insert an element into the set if it isn't already there.
Definition SmallSet.h:184
void assign(size_type NumElts, ValueParamT Elt)
void push_back(const T &Elt)
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
virtual const TargetInstrInfo * getInstrInfo() const
virtual const TargetRegisterInfo * getRegisterInfo() const =0
Return the target's register information.
An efficient, type-erasing, non-owning reference to a callable.
self_iterator getIterator()
Definition ilist_node.h:123
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
Changed
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
initializer< Ty > init(const Ty &Val)
NodeAddr< DefNode * > Def
Definition RDFGraph.h:384
This is an optimization pass for GlobalISel generic memory operations.
LLVM_ABI FunctionPass * createFastRegisterAllocator()
FastRegisterAllocation Pass - This pass register allocates as fast as possible.
std::function< bool(const TargetRegisterInfo &TRI, const MachineRegisterInfo &MRI, const Register Reg)> RegAllocFilterFunc
Filter function for register classes during regalloc.
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
InstructionCost Cost
@ Kill
The last use of a register.
LLVM_ABI void updateDbgValueForSpill(MachineInstr &Orig, int FrameIndex, Register Reg)
Update a DBG_VALUE whose value has been spilled to FrameIndex.
LLVM_ABI Printable printRegUnit(MCRegUnit Unit, const TargetRegisterInfo *TRI)
Create Printable object to print register units on a raw_ostream.
AnalysisManager< MachineFunction > MachineFunctionAnalysisManager
LLVM_ABI PreservedAnalyses getMachineFunctionPassPreservedAnalyses()
Returns the minimum set of Analyses that all machine function passes must preserve.
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1746
auto reverse(ContainerTy &&C)
Definition STLExtras.h:407
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1636
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
MutableArrayRef(T &OneElt) -> MutableArrayRef< T >
uint16_t MCPhysReg
An unsigned integer type large enough to represent all physical registers, but not necessarily virtua...
Definition MCRegister.h:21
DWARFExpression::Operation Op
ArrayRef(const T &OneElt) -> ArrayRef< T >
LLVM_ABI MachineInstr * buildDbgValueForSpill(MachineBasicBlock &BB, MachineBasicBlock::iterator I, const MachineInstr &Orig, int FrameIndex, Register SpillReg)
Clone a DBG_VALUE whose value has been spilled to FrameIndex.
iterator_range< pointer_iterator< WrappedIteratorT > > make_pointer_range(RangeT &&Range)
Definition iterator.h:368
LLVM_ABI Printable printReg(Register Reg, const TargetRegisterInfo *TRI=nullptr, unsigned SubIdx=0, const MachineRegisterInfo *MRI=nullptr)
Prints virtual and physical registers with or without a TRI instance.
MCRegisterClass TargetRegisterClass
Definition FastISel.h:58