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 // If there are multiple undef uses, give them the same register. The def is
1035 // already freed, so take the register from the tie, not the lookup below.
1036 MachineInstr &MI = *MO.getParent();
1037 for (const MachineOperand &Tied : MI.all_uses()) {
1038 if (!Tied.isTied() || Tied.getReg() != VirtReg)
1039 continue;
1040 MCRegister DefReg =
1041 MI.getOperand(MI.findTiedOperandIdx(MI.getOperandNo(&Tied)))
1042 .getReg()
1043 .asMCReg();
1044 for (MachineOperand &O : MI.all_uses()) {
1045 if (O.getReg() != VirtReg)
1046 continue;
1047 // The def is already narrowed, so a tie takes its register whole.
1048 unsigned SubIdx = O.isTied() ? 0 : O.getSubReg();
1049 O.setReg(SubIdx ? TRI->getSubReg(DefReg, SubIdx) : DefReg);
1050 O.setSubReg(0);
1051 O.setIsRenamable(!MRI->isReserved(O.getReg()));
1052 }
1053 return;
1054 }
1055
1056 LiveRegMap::iterator LRI = findLiveVirtReg(VirtReg);
1057 MCRegister PhysReg;
1058 bool IsRenamable = true;
1059 if (LRI != LiveVirtRegs.end() && LRI->PhysReg) {
1060 PhysReg = LRI->PhysReg;
1061 } else {
1062 const TargetRegisterClass &RC = *MRI->getRegClass(VirtReg);
1063 ArrayRef<MCPhysReg> AllocationOrder = RegClassInfo.getOrder(&RC);
1064 if (AllocationOrder.empty()) {
1065 // All registers in the class were reserved.
1066 //
1067 // It might be OK to take any entry from the class as this is an undef
1068 // use, but accepting this would give different behavior than greedy and
1069 // basic.
1070 PhysReg = getErrorAssignment(*LRI, *MO.getParent(), RC);
1071 LRI->Error = true;
1072 IsRenamable = false;
1073 } else
1074 PhysReg = AllocationOrder.front();
1075 }
1076
1077 unsigned SubRegIdx = MO.getSubReg();
1078 if (SubRegIdx != 0) {
1079 PhysReg = TRI->getSubReg(PhysReg, SubRegIdx);
1080 MO.setSubReg(0);
1081 }
1082 MO.setReg(PhysReg);
1083 MO.setIsRenamable(IsRenamable);
1084}
1085
1086/// Variation of defineVirtReg() with special handling for livethrough regs
1087/// (tied or earlyclobber) that may interfere with preassigned uses.
1088/// \return true if MI's MachineOperands were re-arranged/invalidated.
1089bool RegAllocFastImpl::defineLiveThroughVirtReg(MachineInstr &MI,
1090 unsigned OpNum,
1091 Register VirtReg) {
1092 if (!shouldAllocateRegister(VirtReg))
1093 return false;
1094 LiveRegMap::iterator LRI = findLiveVirtReg(VirtReg);
1095 if (LRI != LiveVirtRegs.end()) {
1096 MCRegister PrevReg = LRI->PhysReg;
1097 if (PrevReg && isRegUsedInInstr(PrevReg, true)) {
1098 LLVM_DEBUG(dbgs() << "Need new assignment for " << printReg(PrevReg, TRI)
1099 << " (tied/earlyclobber resolution)\n");
1100 freePhysReg(PrevReg);
1101 LRI->PhysReg = MCRegister();
1102 allocVirtReg(MI, *LRI, Register(), true);
1103 MachineBasicBlock::iterator InsertBefore =
1104 std::next((MachineBasicBlock::iterator)MI.getIterator());
1105 LLVM_DEBUG(dbgs() << "Copy " << printReg(LRI->PhysReg, TRI) << " to "
1106 << printReg(PrevReg, TRI) << '\n');
1107 BuildMI(*MBB, InsertBefore, MI.getDebugLoc(),
1108 TII->get(TargetOpcode::COPY), PrevReg)
1109 .addReg(LRI->PhysReg, llvm::RegState::Kill);
1110 }
1111 MachineOperand &MO = MI.getOperand(OpNum);
1112 if (MO.getSubReg() && !MO.isUndef()) {
1113 LRI->LastUse = &MI;
1114 }
1115 }
1116 return defineVirtReg(MI, OpNum, VirtReg, true);
1117}
1118
1119/// Allocates a register for VirtReg definition. Typically the register is
1120/// already assigned from a use of the virtreg, however we still need to
1121/// perform an allocation if:
1122/// - It is a dead definition without any uses.
1123/// - The value is live out and all uses are in different basic blocks.
1124///
1125/// \return true if MI's MachineOperands were re-arranged/invalidated.
1126bool RegAllocFastImpl::defineVirtReg(MachineInstr &MI, unsigned OpNum,
1127 Register VirtReg, bool LookAtPhysRegUses) {
1128 assert(VirtReg.isVirtual() && "Not a virtual register");
1129 if (!shouldAllocateRegister(VirtReg))
1130 return false;
1131 MachineOperand &MO = MI.getOperand(OpNum);
1132 LiveRegMap::iterator LRI;
1133 bool New;
1134 std::tie(LRI, New) = LiveVirtRegs.insert(LiveReg(VirtReg));
1135 if (New) {
1136 if (!MO.isDead()) {
1137 if (mayLiveOut(VirtReg)) {
1138 LRI->LiveOut = true;
1139 } else {
1140 // It is a dead def without the dead flag; add the flag now.
1141 MO.setIsDead(true);
1142 }
1143 }
1144 }
1145 if (!LRI->PhysReg) {
1146 allocVirtReg(MI, *LRI, Register(), LookAtPhysRegUses);
1147 } else {
1148 assert((!isRegUsedInInstr(LRI->PhysReg, LookAtPhysRegUses) || LRI->Error) &&
1149 "TODO: preassign mismatch");
1150 LLVM_DEBUG(dbgs() << "In def of " << printReg(VirtReg, TRI)
1151 << " use existing assignment to "
1152 << printReg(LRI->PhysReg, TRI) << '\n');
1153 }
1154
1155 MCRegister PhysReg = LRI->PhysReg;
1156 // Either flag means a reader below depends on the slot.
1157 if (LRI->Reloaded || LRI->LiveOut) {
1158 if (!MI.isImplicitDef()) {
1159 MachineBasicBlock::iterator SpillBefore =
1160 std::next((MachineBasicBlock::iterator)MI.getIterator());
1161 LLVM_DEBUG(dbgs() << "Spill Reason: LO: " << LRI->LiveOut
1162 << " RL: " << LRI->Reloaded << '\n');
1163 bool Kill = LRI->LastUse == nullptr;
1164 spill(SpillBefore, VirtReg, PhysReg, Kill, LRI->LiveOut);
1165
1166 // We need to place additional spills for each indirect destination of an
1167 // INLINEASM_BR.
1168 if (MI.getOpcode() == TargetOpcode::INLINEASM_BR) {
1169 int FI = StackSlotForVirtReg[VirtReg];
1170 const TargetRegisterClass &RC = *MRI->getRegClass(VirtReg);
1171 for (MachineOperand &MO : MI.operands()) {
1172 if (MO.isMBB()) {
1173 MachineBasicBlock *Succ = MO.getMBB();
1174 TII->storeRegToStackSlot(*Succ, Succ->begin(), PhysReg, Kill, FI,
1175 &RC, VirtReg);
1176 ++NumStores;
1177 Succ->addLiveIn(PhysReg);
1178 }
1179 }
1180 }
1181
1182 LRI->LastUse = nullptr;
1183 } else if (!LRI->LastUse) {
1184 // No spill was inserted, so nothing below reads this def.
1185 MO.setIsDead(true);
1186 }
1187 // A def above spills only if a displacement above reloads again.
1188 LRI->LiveOut = false;
1189 LRI->Reloaded = false;
1190 }
1191 if (MI.getOpcode() == TargetOpcode::BUNDLE) {
1192 BundleVirtRegsMap[VirtReg] = *LRI;
1193 }
1194 markRegUsedInInstr(PhysReg);
1195 return setPhysReg(MI, MO, *LRI);
1196}
1197
1198/// Allocates a register for a VirtReg use.
1199/// \return true if MI's MachineOperands were re-arranged/invalidated.
1200bool RegAllocFastImpl::useVirtReg(MachineInstr &MI, MachineOperand &MO,
1201 Register VirtReg) {
1202 assert(VirtReg.isVirtual() && "Not a virtual register");
1203 if (!shouldAllocateRegister(VirtReg))
1204 return false;
1205 LiveRegMap::iterator LRI;
1206 bool New;
1207 std::tie(LRI, New) = LiveVirtRegs.insert(LiveReg(VirtReg));
1208 if (New) {
1209 if (!MO.isKill()) {
1210 if (mayLiveOut(VirtReg)) {
1211 LRI->LiveOut = true;
1212 } else {
1213 // It is a last (killing) use without the kill flag; add the flag now.
1214 MO.setIsKill(true);
1215 }
1216 }
1217 } else {
1218 assert((!MO.isKill() || LRI->LastUse == &MI) && "Invalid kill flag");
1219 }
1220
1221 // If necessary allocate a register.
1222 if (!LRI->PhysReg) {
1223 assert(!MO.isTied() && "tied op should be allocated");
1224 Register Hint;
1225 if (MI.isCopy() && MI.getOperand(1).getSubReg() == 0) {
1226 Hint = MI.getOperand(0).getReg();
1227 if (Hint.isVirtual()) {
1228 assert(!shouldAllocateRegister(Hint));
1229 Hint = Register();
1230 } else {
1231 assert(Hint.isPhysical() &&
1232 "Copy destination should already be assigned");
1233 }
1234 }
1235 allocVirtReg(MI, *LRI, Hint, false);
1236 }
1237
1238 LRI->LastUse = &MI;
1239
1240 if (MI.getOpcode() == TargetOpcode::BUNDLE) {
1241 BundleVirtRegsMap[VirtReg] = *LRI;
1242 }
1243 markRegUsedInInstr(LRI->PhysReg);
1244 return setPhysReg(MI, MO, *LRI);
1245}
1246
1247/// Query a physical register to use as a filler in contexts where the
1248/// allocation has failed. This will raise an error, but not abort the
1249/// compilation.
1250MCPhysReg RegAllocFastImpl::getErrorAssignment(const LiveReg &LR,
1251 MachineInstr &MI,
1252 const TargetRegisterClass &RC) {
1253 MachineFunction &MF = *MI.getMF();
1254
1255 // Avoid repeating the error every time a register is used.
1256 bool EmitError = !MF.getProperties().hasFailedRegAlloc();
1257 if (EmitError)
1258 MF.getProperties().setFailedRegAlloc();
1259
1260 // If the allocation order was empty, all registers in the class were
1261 // probably reserved. Fall back to taking the first register in the class,
1262 // even if it's reserved.
1263 ArrayRef<MCPhysReg> AllocationOrder = RegClassInfo.getOrder(&RC);
1264 if (AllocationOrder.empty()) {
1265 const Function &Fn = MF.getFunction();
1266 if (EmitError) {
1267 Fn.getContext().diagnose(DiagnosticInfoRegAllocFailure(
1268 "no registers from class available to allocate", Fn,
1269 MI.getDebugLoc()));
1270 }
1271
1272 ArrayRef<MCPhysReg> RawRegs = RC.getRegisters();
1273 assert(!RawRegs.empty() && "register classes cannot have no registers");
1274 return RawRegs.front();
1275 }
1276
1277 if (!LR.Error && EmitError) {
1278 // Nothing we can do: Report an error and keep going with an invalid
1279 // allocation.
1280 if (MI.isInlineAsm()) {
1281 MI.emitInlineAsmError(
1282 "inline assembly requires more registers than available");
1283 } else {
1284 const Function &Fn = MBB->getParent()->getFunction();
1285 Fn.getContext().diagnose(DiagnosticInfoRegAllocFailure(
1286 "ran out of registers during register allocation", Fn,
1287 MI.getDebugLoc()));
1288 }
1289 }
1290
1291 return AllocationOrder.front();
1292}
1293
1294/// Changes operand OpNum in MI the refer the PhysReg, considering subregs.
1295/// \return true if MI's MachineOperands were re-arranged/invalidated.
1296bool RegAllocFastImpl::setPhysReg(MachineInstr &MI, MachineOperand &MO,
1297 const LiveReg &Assignment) {
1298 MCRegister PhysReg = Assignment.PhysReg;
1299 assert(PhysReg && "assignments should always be to a valid physreg");
1300
1301 if (LLVM_UNLIKELY(Assignment.Error)) {
1302 // Make sure we don't set renamable in error scenarios, as we may have
1303 // assigned to a reserved register.
1304 if (MO.isUse())
1305 MO.setIsUndef(true);
1306 }
1307
1308 if (!MO.getSubReg()) {
1309 MO.setReg(PhysReg);
1310 MO.setIsRenamable(!Assignment.Error);
1311 return false;
1312 }
1313
1314 // Handle subregister index.
1315 MO.setReg(TRI->getSubReg(PhysReg, MO.getSubReg()));
1316 MO.setIsRenamable(!Assignment.Error);
1317
1318 // Note: We leave the subreg number around a little longer in case of defs.
1319 // This is so that the register freeing logic in allocateInstruction can still
1320 // recognize this as subregister defs. The code there will clear the number.
1321 if (!MO.isDef())
1322 MO.setSubReg(0);
1323
1324 // A kill flag implies killing the full register. Add corresponding super
1325 // register kill.
1326 if (MO.isKill()) {
1327 MI.addRegisterKilled(PhysReg, TRI, true);
1328 // Conservatively assume implicit MOs were re-arranged
1329 return true;
1330 }
1331
1332 // A <def,read-undef> of a sub-register requires an implicit def of the full
1333 // register.
1334 if (MO.isDef() && MO.isUndef()) {
1335 if (MO.isDead())
1336 MI.addRegisterDead(PhysReg, TRI, true);
1337 else
1338 MI.addRegisterDefined(PhysReg, TRI);
1339 // Conservatively assume implicit MOs were re-arranged
1340 return true;
1341 }
1342 return false;
1343}
1344
1345#ifndef NDEBUG
1346
1347void RegAllocFastImpl::dumpState() const {
1348 for (MCRegUnit Unit : TRI->regunits()) {
1349 switch (unsigned VirtReg = getRegUnitState(Unit)) {
1350 case regFree:
1351 break;
1352 case regPreAssigned:
1353 dbgs() << " " << printRegUnit(Unit, TRI) << "[P]";
1354 break;
1355 case regLiveIn:
1356 llvm_unreachable("Should not have regLiveIn in map");
1357 default: {
1358 dbgs() << ' ' << printRegUnit(Unit, TRI) << '=' << printReg(VirtReg);
1359 LiveRegMap::const_iterator I = findLiveVirtReg(VirtReg);
1360 assert(I != LiveVirtRegs.end() && "have LiveVirtRegs entry");
1361 if (I->LiveOut || I->Reloaded) {
1362 dbgs() << '[';
1363 if (I->LiveOut)
1364 dbgs() << 'O';
1365 if (I->Reloaded)
1366 dbgs() << 'R';
1367 dbgs() << ']';
1368 }
1369 assert(TRI->hasRegUnit(I->PhysReg, Unit) && "inverse mapping present");
1370 break;
1371 }
1372 }
1373 }
1374 dbgs() << '\n';
1375 // Check that LiveVirtRegs is the inverse.
1376 for (const LiveReg &LR : LiveVirtRegs) {
1377 Register VirtReg = LR.VirtReg;
1378 assert(VirtReg.isVirtual() && "Bad map key");
1379 MCRegister PhysReg = LR.PhysReg;
1380 if (PhysReg) {
1381 assert(PhysReg.isPhysical() && "mapped to physreg");
1382 for (MCRegUnit Unit : TRI->regunits(PhysReg)) {
1383 assert(getRegUnitState(Unit) == VirtReg && "inverse map valid");
1384 }
1385 }
1386 }
1387}
1388#endif
1389
1390/// Count number of defs consumed from each register class by \p Reg
1391void RegAllocFastImpl::addRegClassDefCounts(
1392 MutableArrayRef<unsigned> RegClassDefCounts, Register Reg) const {
1393 assert(RegClassDefCounts.size() == TRI->getNumRegClasses());
1394
1395 if (Reg.isVirtual()) {
1396 if (!shouldAllocateRegister(Reg))
1397 return;
1398 const TargetRegisterClass *OpRC = MRI->getRegClass(Reg);
1399 for (unsigned RCIdx = 0, RCIdxEnd = TRI->getNumRegClasses();
1400 RCIdx != RCIdxEnd; ++RCIdx) {
1401 const TargetRegisterClass *IdxRC = TRI->getRegClass(RCIdx);
1402 // FIXME: Consider aliasing sub/super registers.
1403 if (OpRC->hasSubClassEq(IdxRC))
1404 ++RegClassDefCounts[RCIdx];
1405 }
1406
1407 return;
1408 }
1409
1410 for (unsigned RCIdx = 0, RCIdxEnd = TRI->getNumRegClasses();
1411 RCIdx != RCIdxEnd; ++RCIdx) {
1412 const TargetRegisterClass *IdxRC = TRI->getRegClass(RCIdx);
1413 for (MCRegAliasIterator Alias(Reg, TRI, true); Alias.isValid(); ++Alias) {
1414 if (IdxRC->contains(*Alias)) {
1415 ++RegClassDefCounts[RCIdx];
1416 break;
1417 }
1418 }
1419 }
1420}
1421
1422/// Compute \ref DefOperandIndexes so it contains the indices of "def" operands
1423/// that are to be allocated. Those are ordered in a way that small classes,
1424/// early clobbers and livethroughs are allocated first.
1425void RegAllocFastImpl::findAndSortDefOperandIndexes(const MachineInstr &MI) {
1426 DefOperandIndexes.clear();
1427
1428 LLVM_DEBUG(dbgs() << "Need to assign livethroughs\n");
1429 for (unsigned I = 0, E = MI.getNumOperands(); I < E; ++I) {
1430 const MachineOperand &MO = MI.getOperand(I);
1431 if (!MO.isReg())
1432 continue;
1433 Register Reg = MO.getReg();
1434 if (MO.readsReg()) {
1435 if (Reg.isPhysical()) {
1436 LLVM_DEBUG(dbgs() << "mark extra used: " << printReg(Reg, TRI) << '\n');
1437 markPhysRegUsedInInstr(Reg);
1438 }
1439 }
1440
1441 if (MO.isDef() && Reg.isVirtual() && shouldAllocateRegister(Reg))
1442 DefOperandIndexes.push_back(I);
1443 }
1444
1445 // Most instructions only have one virtual def, so there's no point in
1446 // computing the possible number of defs for every register class.
1447 if (DefOperandIndexes.size() <= 1)
1448 return;
1449
1450 // Track number of defs which may consume a register from the class. This is
1451 // used to assign registers for possibly-too-small classes first. Example:
1452 // defs are eax, 3 * gr32_abcd, 2 * gr32 => we want to assign the gr32_abcd
1453 // registers first so that the gr32 don't use the gr32_abcd registers before
1454 // we assign these.
1455 SmallVector<unsigned> RegClassDefCounts(TRI->getNumRegClasses(), 0);
1456
1457 for (const MachineOperand &MO : MI.all_defs())
1458 addRegClassDefCounts(RegClassDefCounts, MO.getReg());
1459
1460 llvm::sort(DefOperandIndexes, [&](unsigned I0, unsigned I1) {
1461 const MachineOperand &MO0 = MI.getOperand(I0);
1462 const MachineOperand &MO1 = MI.getOperand(I1);
1463 Register Reg0 = MO0.getReg();
1464 Register Reg1 = MO1.getReg();
1465 const TargetRegisterClass &RC0 = *MRI->getRegClass(Reg0);
1466 const TargetRegisterClass &RC1 = *MRI->getRegClass(Reg1);
1467
1468 // Identify regclass that are easy to use up completely just in this
1469 // instruction.
1470 unsigned ClassSize0 = RegClassInfo.getOrder(&RC0).size();
1471 unsigned ClassSize1 = RegClassInfo.getOrder(&RC1).size();
1472
1473 bool SmallClass0 = ClassSize0 < RegClassDefCounts[RC0.getID()];
1474 bool SmallClass1 = ClassSize1 < RegClassDefCounts[RC1.getID()];
1475 if (SmallClass0 > SmallClass1)
1476 return true;
1477 if (SmallClass0 < SmallClass1)
1478 return false;
1479
1480 // Allocate early clobbers and livethrough operands first.
1481 bool Livethrough0 = MO0.isEarlyClobber() || MO0.isTied() ||
1482 (MO0.getSubReg() == 0 && !MO0.isUndef());
1483 bool Livethrough1 = MO1.isEarlyClobber() || MO1.isTied() ||
1484 (MO1.getSubReg() == 0 && !MO1.isUndef());
1485 if (Livethrough0 > Livethrough1)
1486 return true;
1487 if (Livethrough0 < Livethrough1)
1488 return false;
1489
1490 // Tie-break rule: operand index.
1491 return I0 < I1;
1492 });
1493}
1494
1495// Returns true if this def (MO) ties to a use that actually carries a value
1496// (not undef).
1497static bool isTiedToNotUndef(const MachineInstr &MI, const MachineOperand &MO) {
1498 assert(MO.isDef() && "expected a def operand");
1499 if (!MO.isTied())
1500 return false;
1501 unsigned TiedIdx = MI.findTiedOperandIdx(MI.getOperandNo(&MO));
1502 const MachineOperand &TiedMO = MI.getOperand(TiedIdx);
1503 return !TiedMO.isUndef();
1504}
1505
1506void RegAllocFastImpl::allocateInstruction(MachineInstr &MI) {
1507 // Backwards, a def frees a register and a use occupies it. The phases:
1508 // * pre-assigned physreg defs
1509 // * virtual register defs
1510 // * free the def operands' registers
1511 // * displace registers clobbered by regmasks
1512 // * pre-assigned physreg uses
1513 // * virtual register uses, inserting reloads
1514 // * undef uses
1515 // * free early-clobber defs
1516 //
1517 // Freeing follows the def allocation so a def is not handed a register this
1518 // instruction also writes, and precedes the uses so a use may take one. It
1519 // skips tied defs, whose register the tied use reads, and early-clobber defs,
1520 // freed last so that no use lands on them.
1521
1522 InstrGen += 2;
1523 // In the event we ever get more than 2**31 instructions...
1524 if (LLVM_UNLIKELY(InstrGen == 0)) {
1525 UsedInInstr.assign(UsedInInstr.size(), 0);
1526 InstrGen = 2;
1527 }
1528 RegMasks.clear();
1529 BundleVirtRegsMap.clear();
1530
1531 // Scan for special cases; Apply pre-assigned register defs to state.
1532 bool HasPhysRegUse = false;
1533 bool HasRegMask = false;
1534 bool HasVRegDef = false;
1535 bool HasDef = false;
1536 bool HasEarlyClobber = false;
1537 bool NeedToAssignLiveThroughs = false;
1538 for (MachineOperand &MO : MI.operands()) {
1539 if (MO.isReg()) {
1540 Register Reg = MO.getReg();
1541 if (Reg.isVirtual()) {
1542 if (!shouldAllocateRegister(Reg))
1543 continue;
1544 if (MO.isDef()) {
1545 HasDef = true;
1546 HasVRegDef = true;
1547 if (MO.isEarlyClobber()) {
1548 HasEarlyClobber = true;
1549 NeedToAssignLiveThroughs = true;
1550 }
1551 if (isTiedToNotUndef(MI, MO) ||
1552 (MO.getSubReg() != 0 && !MO.isUndef()))
1553 NeedToAssignLiveThroughs = true;
1554 }
1555 } else if (Reg.isPhysical()) {
1556 if (!MRI->isReserved(Reg)) {
1557 if (MO.isDef()) {
1558 HasDef = true;
1559 bool displacedAny = definePhysReg(MI, Reg);
1560 if (MO.isEarlyClobber())
1561 HasEarlyClobber = true;
1562 if (!displacedAny)
1563 MO.setIsDead(true);
1564 }
1565 if (MO.readsReg())
1566 HasPhysRegUse = true;
1567 }
1568 }
1569 } else if (MO.isRegMask()) {
1570 HasRegMask = true;
1571 RegMasks.push_back(MO.getRegMask());
1572 }
1573 }
1574
1575 // Allocate virtreg defs.
1576 if (HasDef) {
1577 if (HasVRegDef) {
1578 // Note that Implicit MOs can get re-arranged by defineVirtReg(), so loop
1579 // multiple times to ensure no operand is missed.
1580 bool ReArrangedImplicitOps = true;
1581
1582 // Special handling for early clobbers, tied operands or subregister defs:
1583 // Compared to "normal" defs these:
1584 // - Must not use a register that is pre-assigned for a use operand.
1585 // - In order to solve tricky inline assembly constraints we change the
1586 // heuristic to figure out a good operand order before doing
1587 // assignments.
1588 if (NeedToAssignLiveThroughs) {
1589 while (ReArrangedImplicitOps) {
1590 ReArrangedImplicitOps = false;
1591 findAndSortDefOperandIndexes(MI);
1592 for (unsigned OpIdx : DefOperandIndexes) {
1593 MachineOperand &MO = MI.getOperand(OpIdx);
1594 LLVM_DEBUG(dbgs() << "Allocating " << MO << '\n');
1595 Register Reg = MO.getReg();
1596 if (MO.isEarlyClobber() || isTiedToNotUndef(MI, MO) ||
1597 (MO.getSubReg() && !MO.isUndef())) {
1598 ReArrangedImplicitOps = defineLiveThroughVirtReg(MI, OpIdx, Reg);
1599 } else {
1600 ReArrangedImplicitOps = defineVirtReg(MI, OpIdx, Reg);
1601 }
1602 // Implicit operands of MI were re-arranged,
1603 // re-compute DefOperandIndexes.
1604 if (ReArrangedImplicitOps)
1605 break;
1606 }
1607 }
1608 } else {
1609 // Assign virtual register defs.
1610 while (ReArrangedImplicitOps) {
1611 ReArrangedImplicitOps = false;
1612 for (MachineOperand &MO : MI.all_defs()) {
1613 Register Reg = MO.getReg();
1614 if (Reg.isVirtual()) {
1615 ReArrangedImplicitOps =
1616 defineVirtReg(MI, MI.getOperandNo(&MO), Reg);
1617 if (ReArrangedImplicitOps)
1618 break;
1619 }
1620 }
1621 }
1622 }
1623 }
1624
1625 // Free registers occupied by defs.
1626 // Iterate operands in reverse order, so we see the implicit super register
1627 // defs first (we added them earlier in case of <def,read-undef>).
1628 for (MachineOperand &MO : reverse(MI.all_defs())) {
1629 Register Reg = MO.getReg();
1630
1631 // subreg defs don't free the full register. We left the subreg number
1632 // around as a marker in setPhysReg() to recognize this case here.
1633 if (Reg.isPhysical() && MO.getSubReg() != 0) {
1634 MO.setSubReg(0);
1635 continue;
1636 }
1637
1638 assert((!MO.isTied() || !isClobberedByRegMasks(MO.getReg())) &&
1639 "tied def assigned to clobbered register");
1640
1641 // Do not free tied operands and early clobbers.
1642 if (isTiedToNotUndef(MI, MO) || MO.isEarlyClobber())
1643 continue;
1644 if (!Reg)
1645 continue;
1646 if (Reg.isVirtual()) {
1647 assert(!shouldAllocateRegister(Reg));
1648 continue;
1649 }
1651 if (MRI->isReserved(Reg))
1652 continue;
1653 freePhysReg(Reg);
1654 unmarkRegUsedInInstr(Reg);
1655 }
1656 }
1657
1658 // A regmask is a def of every clobbered register: reload what lives in one
1659 // below MI. Nothing is reserved, so the uses may still take those registers.
1660 if (HasRegMask) {
1661 assert(!RegMasks.empty() && "expected RegMask");
1662 // MRI bookkeeping.
1663 for (const auto *RM : RegMasks)
1665
1666 for (const LiveReg &LR : LiveVirtRegs) {
1667 MCRegister PhysReg = LR.PhysReg;
1668 if (PhysReg && isClobberedByRegMasks(PhysReg))
1669 displacePhysReg(MI, PhysReg);
1670 }
1671 }
1672
1673 // Apply pre-assigned register uses to state.
1674 if (HasPhysRegUse) {
1675 for (MachineOperand &MO : MI.operands()) {
1676 if (!MO.isReg() || !MO.readsReg())
1677 continue;
1678 Register Reg = MO.getReg();
1679 if (!Reg.isPhysical())
1680 continue;
1681 if (MRI->isReserved(Reg))
1682 continue;
1683 if (!usePhysReg(MI, Reg))
1684 MO.setIsKill(true);
1685 }
1686 }
1687
1688 // Allocate virtreg uses and insert reloads as necessary.
1689 // Implicit MOs can get moved/removed by useVirtReg(), so loop multiple
1690 // times to ensure no operand is missed.
1691 bool HasUndefUse = false;
1692 bool ReArrangedImplicitMOs = true;
1693 while (ReArrangedImplicitMOs) {
1694 ReArrangedImplicitMOs = false;
1695 for (MachineOperand &MO : MI.operands()) {
1696 if (!MO.isReg() || !MO.isUse())
1697 continue;
1698 Register Reg = MO.getReg();
1699 if (!Reg.isVirtual() || !shouldAllocateRegister(Reg))
1700 continue;
1701
1702 if (MO.isUndef()) {
1703 HasUndefUse = true;
1704 continue;
1705 }
1706
1707 // Populate MayLiveAcrossBlocks now: these uses are about to be rewritten
1708 // to physregs, so a def block allocated later can no longer see them.
1709 mayLiveIn(Reg);
1710
1711 assert(!MO.isInternalRead() && "Bundles not supported");
1712 assert(MO.readsReg() && "reading use");
1713 ReArrangedImplicitMOs = useVirtReg(MI, MO, Reg);
1714 if (ReArrangedImplicitMOs)
1715 break;
1716 }
1717 }
1718
1719 // Allocate undef operands. This is a separate step because in a situation
1720 // like ` = OP undef %X, %X` both operands need the same register assign
1721 // so we should perform the normal assignment first.
1722 if (HasUndefUse) {
1723 for (MachineOperand &MO : MI.all_uses()) {
1724 Register Reg = MO.getReg();
1725 if (!Reg.isVirtual() || !shouldAllocateRegister(Reg))
1726 continue;
1727
1728 assert(MO.isUndef() && "Should only have undef virtreg uses left");
1729 allocVirtRegUndef(MO);
1730 }
1731 }
1732
1733 // Free early clobbers. Last, because they must not share a register with any
1734 // use.
1735 if (HasEarlyClobber) {
1736 for (MachineOperand &MO : reverse(MI.all_defs())) {
1737 if (!MO.isEarlyClobber())
1738 continue;
1739 assert(!MO.getSubReg() && "should be already handled in def processing");
1740
1741 Register Reg = MO.getReg();
1742 if (!Reg)
1743 continue;
1744 if (Reg.isVirtual()) {
1745 assert(!shouldAllocateRegister(Reg));
1746 continue;
1747 }
1748 assert(Reg.isPhysical() && "should have register assigned");
1749
1750 // We sometimes get odd situations like:
1751 // early-clobber %x0 = INSTRUCTION %x0
1752 // which is semantically questionable as the early-clobber should
1753 // apply before the use. But in practice we consider the use to
1754 // happen before the early clobber now. Don't free the early clobber
1755 // register in this case.
1756 if (MI.readsRegister(Reg, TRI))
1757 continue;
1758
1759 freePhysReg(Reg);
1760 }
1761 }
1762
1763 LLVM_DEBUG(dbgs() << "<< " << MI);
1764 if (MI.isCopy() &&
1765 (MI.getOperand(0).getReg() == MI.getOperand(1).getReg() ||
1766 MI.getOperand(0).isDead()) &&
1767 MI.getNumOperands() == 2) {
1768 LLVM_DEBUG(dbgs() << "Mark unnecessary copy for removal: " << MI);
1769 Coalesced.push_back(&MI);
1770 }
1771}
1772
1773void RegAllocFastImpl::handleDebugValue(MachineInstr &MI) {
1774 // Ignore DBG_VALUEs that aren't based on virtual registers. These are
1775 // mostly constants and frame indices.
1776 assert(MI.isDebugValue() && "not a DBG_VALUE*");
1777 for (const auto &MO : MI.debug_operands()) {
1778 if (!MO.isReg())
1779 continue;
1780 Register Reg = MO.getReg();
1781 if (!Reg.isVirtual())
1782 continue;
1783 if (!shouldAllocateRegister(Reg))
1784 continue;
1785
1786 // Already spilled to a stackslot?
1787 int SS = StackSlotForVirtReg[Reg];
1788 if (SS != -1) {
1789 // Modify DBG_VALUE now that the value is in a spill slot.
1791 LLVM_DEBUG(dbgs() << "Rewrite DBG_VALUE for spilled memory: " << MI);
1792 continue;
1793 }
1794
1795 // See if this virtual register has already been allocated to a physical
1796 // register or spilled to a stack slot.
1797 LiveRegMap::iterator LRI = findLiveVirtReg(Reg);
1799 llvm::make_pointer_range(MI.getDebugOperandsForReg(Reg)));
1800
1801 if (LRI != LiveVirtRegs.end() && LRI->PhysReg) {
1802 // Update every use of Reg within MI.
1803 for (auto &RegMO : DbgOps)
1804 setPhysReg(MI, *RegMO, *LRI);
1805 } else {
1806 DanglingDbgValues[Reg].push_back(&MI);
1807 }
1808
1809 // If Reg hasn't been spilled, put this DBG_VALUE in LiveDbgValueMap so
1810 // that future spills of Reg will have DBG_VALUEs.
1811 LiveDbgValueMap[Reg].append(DbgOps.begin(), DbgOps.end());
1812 }
1813}
1814
1815void RegAllocFastImpl::handleBundle(MachineInstr &MI) {
1816 MachineBasicBlock::instr_iterator BundledMI = MI.getIterator();
1817 ++BundledMI;
1818 while (BundledMI->isBundledWithPred()) {
1819 for (MachineOperand &MO : BundledMI->operands()) {
1820 if (!MO.isReg())
1821 continue;
1822
1823 Register Reg = MO.getReg();
1824 if (!Reg.isVirtual() || !shouldAllocateRegister(Reg))
1825 continue;
1826
1827 auto DI = BundleVirtRegsMap.find(Reg);
1828 assert(DI != BundleVirtRegsMap.end() && "Unassigned virtual register");
1829
1830 setPhysReg(MI, MO, DI->second);
1831 }
1832
1833 ++BundledMI;
1834 }
1835}
1836
1837void RegAllocFastImpl::allocateBasicBlock(MachineBasicBlock &MBB) {
1838 this->MBB = &MBB;
1839 LLVM_DEBUG(dbgs() << "\nAllocating " << MBB);
1840
1841 PosIndexes.unsetInitialized();
1842 RegUnitStates.assign(TRI->getNumRegUnits(), regFree);
1843 assert(LiveVirtRegs.empty() && "Mapping not cleared from last block?");
1844
1845 for (const auto &LiveReg : MBB.liveouts())
1846 setPhysRegState(LiveReg.PhysReg, regPreAssigned);
1847
1848 Coalesced.clear();
1849
1850 // Traverse block in reverse order allocating instructions one by one.
1851 for (MachineInstr &MI : reverse(MBB)) {
1852 LLVM_DEBUG(dbgs() << "\n>> " << MI << "Regs:"; dumpState());
1853
1854 // Special handling for debug values. Note that they are not allowed to
1855 // affect codegen of the other instructions in any way.
1856 if (MI.isDebugValue()) {
1857 handleDebugValue(MI);
1858 continue;
1859 }
1860
1861 allocateInstruction(MI);
1862
1863 // Once BUNDLE header is assigned registers, same assignments need to be
1864 // done for bundled MIs.
1865 if (MI.getOpcode() == TargetOpcode::BUNDLE) {
1866 handleBundle(MI);
1867 }
1868 }
1869
1870 LLVM_DEBUG(dbgs() << "Begin Regs:"; dumpState());
1871
1872 // Spill all physical registers holding virtual registers now.
1873 LLVM_DEBUG(dbgs() << "Loading live registers at begin of block.\n");
1874 reloadAtBegin(MBB);
1875
1876 // Erase all the coalesced copies. We are delaying it until now because
1877 // LiveVirtRegs might refer to the instrs.
1878 for (MachineInstr *MI : Coalesced)
1879 MBB.erase(MI);
1880 NumCoalesced += Coalesced.size();
1881
1882 for (auto &UDBGPair : DanglingDbgValues) {
1883 for (MachineInstr *DbgValue : UDBGPair.second) {
1884 assert(DbgValue->isDebugValue() && "expected DBG_VALUE");
1885 // Nothing to do if the vreg was spilled in the meantime.
1886 if (!DbgValue->hasDebugOperandForReg(UDBGPair.first))
1887 continue;
1888 LLVM_DEBUG(dbgs() << "Register did not survive for " << *DbgValue
1889 << '\n');
1890 DbgValue->setDebugValueUndef();
1891 }
1892 }
1893 DanglingDbgValues.clear();
1894
1895 LLVM_DEBUG(MBB.dump());
1896}
1897
1898bool RegAllocFastImpl::runOnMachineFunction(MachineFunction &MF) {
1899 LLVM_DEBUG(dbgs() << "********** FAST REGISTER ALLOCATION **********\n"
1900 << "********** Function: " << MF.getName() << '\n');
1901 MRI = &MF.getRegInfo();
1902 const TargetSubtargetInfo &STI = MF.getSubtarget();
1903 TRI = STI.getRegisterInfo();
1904 TII = STI.getInstrInfo();
1905 MFI = &MF.getFrameInfo();
1906 MRI->freezeReservedRegs();
1907 RegClassInfo.runOnMachineFunction(MF);
1908 unsigned NumRegUnits = TRI->getNumRegUnits();
1909 InstrGen = 0;
1910 UsedInInstr.assign(NumRegUnits, 0);
1911
1912 // initialize the virtual->physical register map to have a 'null'
1913 // mapping for all virtual registers
1914 unsigned NumVirtRegs = MRI->getNumVirtRegs();
1915 StackSlotForVirtReg.resize(NumVirtRegs);
1916 LiveVirtRegs.setUniverse(NumVirtRegs);
1917 MayLiveAcrossBlocks.clear();
1918 MayLiveAcrossBlocks.resize(NumVirtRegs);
1919
1920 // Loop over all of the basic blocks, eliminating virtual register references
1921 for (MachineBasicBlock &MBB : MF)
1922 allocateBasicBlock(MBB);
1923
1924 if (ClearVirtRegs) {
1925 // All machine operands and other references to virtual registers have been
1926 // replaced. Remove the virtual registers.
1927 MRI->clearVirtRegs();
1928 }
1929
1930 StackSlotForVirtReg.clear();
1931 LiveDbgValueMap.clear();
1932 return true;
1933}
1934
1937 MFPropsModifier _(*this, MF);
1938 RegAllocFastImpl Impl(Opts.Filter, Opts.ClearVRegs);
1939 bool Changed = Impl.runOnMachineFunction(MF);
1940 if (!Changed)
1941 return PreservedAnalyses::all();
1943 PA.preserveSet<CFGAnalyses>();
1944 return PA;
1945}
1946
1948 raw_ostream &OS, function_ref<StringRef(StringRef)> MapClassName2PassName) {
1949 bool PrintFilterName = Opts.FilterName != "all";
1950 bool PrintNoClearVRegs = !Opts.ClearVRegs;
1951 bool PrintSemicolon = PrintFilterName && PrintNoClearVRegs;
1952
1953 OS << "regallocfast";
1954 if (PrintFilterName || PrintNoClearVRegs) {
1955 OS << '<';
1956 if (PrintFilterName)
1957 OS << "filter=" << Opts.FilterName;
1958 if (PrintSemicolon)
1959 OS << ';';
1960 if (PrintNoClearVRegs)
1961 OS << "no-clear-vregs";
1962 OS << '>';
1963 }
1964}
1965
1966FunctionPass *llvm::createFastRegisterAllocator() { return new RegAllocFast(); }
1967
1969 bool ClearVirtRegs) {
1970 return new RegAllocFast(Ftor, ClearVirtRegs);
1971}
#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:258
iterator end()
Definition DenseMap.h:176
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.
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:1762
auto reverse(ContainerTy &&C)
Definition STLExtras.h:408
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1652
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