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/// Where the target enables it, TwoAddressInstructionPass is left out of the
21/// pipeline: this pass lowers tied operands and expands REG_SEQUENCE and
22/// INSERT_SUBREG itself.
23//
24//===----------------------------------------------------------------------===//
25
27#include "llvm/ADT/ArrayRef.h"
28#include "llvm/ADT/DenseMap.h"
29#include "llvm/ADT/IndexedMap.h"
30#include "llvm/ADT/MapVector.h"
31#include "llvm/ADT/SmallSet.h"
33#include "llvm/ADT/SparseSet.h"
34#include "llvm/ADT/Statistic.h"
52#include "llvm/Pass.h"
53#include "llvm/Support/Debug.h"
56#include <cassert>
57#include <tuple>
58#include <vector>
59
60using namespace llvm;
61
62#define DEBUG_TYPE "regalloc"
63
64STATISTIC(NumStores, "Number of stores added");
65STATISTIC(NumLoads, "Number of loads added");
66STATISTIC(NumCoalesced, "Number of copies coalesced");
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 = nullptr;
198 const RegAllocFilterFunc ShouldAllocateRegisterImpl;
199
200 /// Tied operands reach this pass unrewritten (TwoAddressInstructionPass was
201 /// left out of the pipeline): lower them here.
202 bool LowerTiedOps = false;
203
204 /// Basic block currently being allocated.
205 MachineBasicBlock *MBB = nullptr;
206
207 /// Maps virtual regs to the frame index where these values are spilled.
208 IndexedMap<int, VirtReg2IndexFunctor> StackSlotForVirtReg;
209
210 /// A virtual register live at the current point of the backward walk.
211 /// Created at its last reference, cleared only when the block is done.
212 struct LiveReg {
213 MachineInstr *LastUse = nullptr; ///< Last instr to use reg.
214 Register VirtReg; ///< Virtual register number.
215 MCRegister PhysReg; ///< Currently held here, 0 if none.
216 bool LiveOut = false; ///< May be live out; the def spills.
217 bool Reloaded = false; ///< Reloaded below; the def spills.
218 bool Error = false; ///< Could not allocate.
219
220 explicit LiveReg(Register VirtReg) : VirtReg(VirtReg) {}
221 explicit LiveReg() = default;
222
223 unsigned getSparseSetIndex() const { return VirtReg.virtRegIndex(); }
224 };
225
226 using LiveRegMap = SparseSet<LiveReg, unsigned, identity, uint16_t>;
227 /// This map contains entries for each virtual register that is currently
228 /// available in a physical register.
229 LiveRegMap LiveVirtRegs;
230
231 /// Stores assigned virtual registers present in the bundle MI.
232 DenseMap<Register, LiveReg> BundleVirtRegsMap;
233
234 DenseMap<Register, SmallVector<MachineOperand *, 2>> LiveDbgValueMap;
235 /// List of DBG_VALUE that we encountered without the vreg being assigned
236 /// because they were placed after the last use of the vreg.
237 DenseMap<Register, SmallVector<MachineInstr *, 1>> DanglingDbgValues;
238
239 /// Has a bit set for every virtual register for which it was determined
240 /// that it is alive across blocks.
241 BitVector MayLiveAcrossBlocks;
242
243 /// What occupies a register unit. Registers interfere exactly when their
244 /// unit sets intersect, so overlap needs no alias walk.
245 enum RegUnitState {
246 /// Not in use; a register is allocatable iff all of its units are free.
247 regFree,
248
249 /// Not available to the allocator and not a virtual register: a physreg
250 /// operand or a block live-out. Cannot be spilled.
251 regPreAssigned,
252
253 /// Scratch marker: reloadAtBegin() stamps MBB.liveins() over the finished
254 /// map, and a virtual register left in a live-in register is not reloaded.
255 regLiveIn,
256
257 /// Any other value is a virtual register number (>= VirtualRegFlag);
258 /// LiveVirtRegs holds the inverse mapping.
259 };
260
261 /// State of each register unit, indexed by MCRegUnit.
262 std::vector<unsigned> RegUnitStates;
263
265
266 /// Track register units that are used in the current instruction, and so
267 /// cannot be allocated.
268 ///
269 /// In the first phase (tied defs/early clobber), we consider also physical
270 /// uses, afterwards, we don't. If the lowest bit isn't set, it's a solely
271 /// physical use (markPhysRegUsedInInstr), otherwise, it's a normal use. To
272 /// avoid resetting the entire vector after every instruction, we track the
273 /// instruction "generation" in the remaining 31 bits -- this means, that if
274 /// UsedInInstr[Idx] < InstrGen, the register unit is unused. InstrGen is
275 /// never zero and always incremented by two.
276 ///
277 /// Don't allocate inline storage: the number of register units is typically
278 /// quite large (e.g., AArch64 > 100, X86 > 200, AMDGPU > 1000).
279 uint32_t InstrGen;
280 SmallVector<unsigned, 0> UsedInInstr;
281
282 /// Physical registers with a non-dead def on the current instruction.
283 SmallVector<MCRegister, 4> LiveDefRegs;
284
285 SmallVector<unsigned, 8> DefOperandIndexes;
286
287 /// Set if an error assignment was used for a def in the current instruction.
288 bool HasErrorDef = false;
289
290 // Register masks attached to the current instruction.
292
293 // Assign index for each instruction to quickly determine dominance.
294 InstrPosIndexes PosIndexes;
295
296 void setRegUnitState(MCRegUnit Unit, unsigned NewState);
297 unsigned getRegUnitState(MCRegUnit Unit) const;
298
299 void setPhysRegState(MCRegister PhysReg, unsigned NewState);
300 bool isPhysRegFree(MCRegister PhysReg) const;
301
302 /// Mark a physreg as used in this instruction.
303 void markRegUsedInInstr(MCRegister PhysReg) {
304 for (MCRegUnit Unit : TRI->regunits(PhysReg))
305 UsedInInstr[static_cast<unsigned>(Unit)] = InstrGen | 1;
306 }
307
308 // Check if physreg is clobbered by instruction's regmask(s).
309 bool isClobberedByRegMasks(MCRegister PhysReg) const {
310 return llvm::any_of(RegMasks, [PhysReg](const uint32_t *Mask) {
311 return MachineOperand::clobbersPhysReg(Mask, PhysReg);
312 });
313 }
314
315 /// Check if a physreg or any of its aliases are used in this instruction.
316 bool isRegUsedInInstr(MCRegister PhysReg, bool LookAtPhysRegUses) const {
317 if (LookAtPhysRegUses && isClobberedByRegMasks(PhysReg))
318 return true;
319 for (MCRegUnit Unit : TRI->regunits(PhysReg))
320 if (UsedInInstr[static_cast<unsigned>(Unit)] >=
321 (InstrGen | !LookAtPhysRegUses))
322 return true;
323 return false;
324 }
325
326 /// Mark physical register as being used in a register use operand.
327 /// This is only used by the special livethrough handling code.
328 void markPhysRegUsedInInstr(MCRegister PhysReg) {
329 for (MCRegUnit Unit : TRI->regunits(PhysReg)) {
330 assert(UsedInInstr[static_cast<unsigned>(Unit)] <= InstrGen &&
331 "non-phys use before phys use?");
332 UsedInInstr[static_cast<unsigned>(Unit)] = InstrGen;
333 }
334 }
335
336 /// Remove mark of physical register being used in the instruction.
337 void unmarkRegUsedInInstr(MCRegister PhysReg) {
338 for (MCRegUnit Unit : TRI->regunits(PhysReg))
339 UsedInInstr[static_cast<unsigned>(Unit)] = 0;
340 }
341
342 /// Check if \p PhysReg or a super-register has a non-dead def on the current
343 /// instruction.
344 bool hasLiveDefOfSuperReg(MCRegister PhysReg) const {
345 return any_of(LiveDefRegs, [&](MCRegister LiveReg) {
346 return TRI->isSuperRegisterEq(PhysReg, LiveReg);
347 });
348 }
349
350 enum : unsigned {
351 spillClean = 50,
352 spillDirty = 100,
353 spillPrefBonus = 20,
354 spillImpossible = ~0u
355 };
356
357public:
358 bool ClearVirtRegs;
359
360 bool runOnMachineFunction(MachineFunction &MF, RegisterClassInfo &RCI);
361
362private:
363 void allocateBasicBlock(MachineBasicBlock &MBB);
364 void expandSubregPseudo(MachineInstr &MI);
365
366 void addRegClassDefCounts(MutableArrayRef<unsigned> RegClassDefCounts,
367 Register Reg) const;
368
369 void findAndSortDefOperandIndexes(const MachineInstr &MI);
370
371 void allocateInstruction(MachineInstr &MI);
372 void handleDebugValue(MachineInstr &MI);
373 void handleBundle(MachineInstr &MI);
374
375 bool usePhysReg(MachineInstr &MI, MCRegister PhysReg);
376 bool definePhysReg(MachineInstr &MI, MCRegister PhysReg);
377 bool displacePhysReg(MachineInstr &MI, MCRegister PhysReg);
378 void freePhysReg(MCRegister PhysReg);
379
380 unsigned calcSpillCost(MCPhysReg PhysReg) const;
381
382 LiveRegMap::iterator findLiveVirtReg(Register VirtReg) {
383 return LiveVirtRegs.find(VirtReg.virtRegIndex());
384 }
385
386 LiveRegMap::const_iterator findLiveVirtReg(Register VirtReg) const {
387 return LiveVirtRegs.find(VirtReg.virtRegIndex());
388 }
389
390 void assignVirtToPhysReg(MachineInstr &MI, LiveReg &, MCRegister PhysReg);
391 void allocVirtReg(MachineInstr &MI, LiveReg &LR, Register Hint,
392 bool LookAtPhysRegUses = false);
393 void allocVirtRegUndef(MachineOperand &MO);
394 void assignDanglingDebugValues(MachineInstr &Def, Register VirtReg,
395 MCRegister Reg);
396 bool defineLiveThroughVirtReg(MachineInstr &MI, unsigned OpNum,
397 Register VirtReg);
398 bool defineVirtReg(MachineInstr &MI, unsigned OpNum, Register VirtReg,
399 bool LookAtPhysRegUses = false);
400 bool useVirtReg(MachineInstr &MI, MachineOperand &MO, Register VirtReg);
401 bool lowerTiedUse(MachineInstr &MI, MachineOperand &MO, LiveReg &LR);
402
403 MCPhysReg getErrorAssignment(const LiveReg &LR, MachineInstr &MI,
404 const TargetRegisterClass &RC);
405
407 getMBBBeginInsertionPoint(MachineBasicBlock &MBB,
408 SmallSet<Register, 2> &PrologLiveIns) const;
409
410 void reloadAtBegin(MachineBasicBlock &MBB);
411 bool setPhysReg(MachineInstr &MI, MachineOperand &MO,
412 const LiveReg &Assignment);
413
414 Register traceCopies(Register VirtReg) const;
415 Register traceCopyChain(Register Reg) const;
416
417 bool shouldAllocateRegister(const Register Reg) const;
418 int getStackSpaceFor(Register VirtReg);
419 void spill(MachineBasicBlock::iterator Before, Register VirtReg,
420 MCRegister AssignedReg, bool Kill, bool LiveOut);
421 void reload(MachineBasicBlock::iterator Before, Register VirtReg,
422 MCRegister PhysReg);
423
424 bool mayLiveOut(Register VirtReg);
425 bool mayLiveIn(Register VirtReg);
426
427 bool mayBeSpillFromInlineAsmBr(const MachineInstr &MI) const;
428
429 void dumpState() const;
430};
431
432class RegAllocFast : public MachineFunctionPass {
433 RegAllocFastImpl Impl;
434
435public:
436 static char ID;
437
438 RegAllocFast(const RegAllocFilterFunc F = nullptr, bool ClearVirtRegs_ = true)
439 : MachineFunctionPass(ID), Impl(F, ClearVirtRegs_) {}
440
441 bool runOnMachineFunction(MachineFunction &MF) override {
442 return Impl.runOnMachineFunction(
443 MF, getAnalysis<MachineRegisterClassInfoWrapperPass>().getRCI());
444 }
445
446 StringRef getPassName() const override { return "Fast Register Allocator"; }
447
448 void getAnalysisUsage(AnalysisUsage &AU) const override {
449 AU.addRequired<MachineRegisterClassInfoWrapperPass>();
450 AU.setPreservesCFG();
452 }
453
454 MachineFunctionProperties getRequiredProperties() const override {
455 return MachineFunctionProperties().setNoPHIs();
456 }
457
458 MachineFunctionProperties getSetProperties() const override {
459 MachineFunctionProperties P;
460 if (Impl.ClearVirtRegs)
461 P.setNoVRegs().setTiedOpsRewritten();
462 return P;
463 }
464
465 MachineFunctionProperties getClearedProperties() const override {
466 return MachineFunctionProperties().setIsSSA();
467 }
468};
469
470} // end anonymous namespace
471
472char RegAllocFast::ID = 0;
473
474INITIALIZE_PASS_BEGIN(RegAllocFast, "regallocfast", "Fast Register Allocator",
475 false, false)
477INITIALIZE_PASS_END(RegAllocFast, "regallocfast", "Fast Register Allocator",
479
480bool RegAllocFastImpl::shouldAllocateRegister(const Register Reg) const {
481 assert(Reg.isVirtual());
482 if (!ShouldAllocateRegisterImpl)
483 return true;
484
485 return ShouldAllocateRegisterImpl(*TRI, *MRI, Reg);
486}
487
488void RegAllocFastImpl::setRegUnitState(MCRegUnit Unit, unsigned NewState) {
489 RegUnitStates[static_cast<unsigned>(Unit)] = NewState;
490}
491
492unsigned RegAllocFastImpl::getRegUnitState(MCRegUnit Unit) const {
493 return RegUnitStates[static_cast<unsigned>(Unit)];
494}
495
496void RegAllocFastImpl::setPhysRegState(MCRegister PhysReg, unsigned NewState) {
497 for (MCRegUnit Unit : TRI->regunits(PhysReg))
498 setRegUnitState(Unit, NewState);
499}
500
501bool RegAllocFastImpl::isPhysRegFree(MCRegister PhysReg) const {
502 for (MCRegUnit Unit : TRI->regunits(PhysReg)) {
503 if (getRegUnitState(Unit) != regFree)
504 return false;
505 }
506 return true;
507}
508
509/// This allocates space for the specified virtual register to be held on the
510/// stack.
511int RegAllocFastImpl::getStackSpaceFor(Register VirtReg) {
512 // Find the location Reg would belong...
513 int SS = StackSlotForVirtReg[VirtReg];
514 // Already has space allocated?
515 if (SS != -1)
516 return SS;
517
518 // Allocate a new stack object for this spill location...
519 const TargetRegisterClass &RC = *MRI->getRegClass(VirtReg);
520 unsigned Size = TRI->getSpillSize(RC);
521 Align Alignment = TRI->getSpillAlign(RC);
522
523 const MachineFunction &MF = MRI->getMF();
524 auto &ST = MF.getSubtarget();
525 Align CurrentAlign = ST.getFrameLowering()->getStackAlign();
526 if (Alignment > CurrentAlign && !TRI->canRealignStack(MF))
527 Alignment = CurrentAlign;
528
529 int FrameIdx =
530 MFI->CreateSpillStackObject(Size, Alignment, TRI->getSpillStackID(RC));
531
532 // Assign the slot.
533 StackSlotForVirtReg[VirtReg] = FrameIdx;
534 return FrameIdx;
535}
536
537static bool dominates(InstrPosIndexes &PosIndexes, const MachineInstr &A,
538 const MachineInstr &B) {
539 uint64_t IndexA, IndexB;
540 PosIndexes.getIndex(A, IndexA);
541 // getIndex() returns true when it renumbered the block, invalidating IndexA.
542 if (LLVM_UNLIKELY(PosIndexes.getIndex(B, IndexB)))
543 PosIndexes.getIndex(A, IndexA);
544 return IndexA < IndexB;
545}
546
547/// Returns true if \p MI is a spill of a live-in physical register in a block
548/// targeted by an INLINEASM_BR. Such spills must precede reloads of live-in
549/// virtual registers, so that we do not reload from an uninitialized stack
550/// slot.
551bool RegAllocFastImpl::mayBeSpillFromInlineAsmBr(const MachineInstr &MI) const {
552 int FI;
553 auto *MBB = MI.getParent();
555 MFI->isSpillSlotObjectIndex(FI))
556 for (const auto &Op : MI.operands())
557 if (Op.isReg() && Op.getReg().isValid() && MBB->isLiveIn(Op.getReg()))
558 return true;
559 return false;
560}
561
562/// Returns false if \p VirtReg is known to not live out of the current block.
563bool RegAllocFastImpl::mayLiveOut(Register VirtReg) {
564 if (MayLiveAcrossBlocks.test(VirtReg.virtRegIndex())) {
565 // Cannot be live-out if there are no successors.
566 return !MBB->succ_empty();
567 }
568
569 const MachineInstr *SelfLoopDef = nullptr;
570
571 // If this block loops back to itself, it is necessary to check whether the
572 // use comes after the def.
573 if (MBB->isSuccessor(MBB)) {
574 // Find the first def in the self loop MBB.
575 for (const MachineInstr &DefInst : MRI->def_instructions(VirtReg)) {
576 if (DefInst.getParent() != MBB) {
577 MayLiveAcrossBlocks.set(VirtReg.virtRegIndex());
578 return true;
579 } else {
580 if (!SelfLoopDef || dominates(PosIndexes, DefInst, *SelfLoopDef))
581 SelfLoopDef = &DefInst;
582 }
583 }
584 if (!SelfLoopDef) {
585 MayLiveAcrossBlocks.set(VirtReg.virtRegIndex());
586 return true;
587 }
588 }
589
590 // See if the first \p Limit uses of the register are all in the current
591 // block.
592 static const unsigned Limit = 8;
593 unsigned C = 0;
594 for (const MachineInstr &UseInst : MRI->use_nodbg_instructions(VirtReg)) {
595 if (UseInst.getParent() != MBB || ++C >= Limit) {
596 MayLiveAcrossBlocks.set(VirtReg.virtRegIndex());
597 // Cannot be live-out if there are no successors.
598 return !MBB->succ_empty();
599 }
600
601 if (SelfLoopDef) {
602 // Try to handle some simple cases to avoid spilling and reloading every
603 // value inside a self looping block.
604 if (SelfLoopDef == &UseInst ||
605 !dominates(PosIndexes, *SelfLoopDef, UseInst)) {
606 MayLiveAcrossBlocks.set(VirtReg.virtRegIndex());
607 return true;
608 }
609 }
610 }
611
612 return false;
613}
614
615/// Returns false if \p VirtReg is known to not be live into the current block.
616bool RegAllocFastImpl::mayLiveIn(Register VirtReg) {
617 if (MayLiveAcrossBlocks.test(VirtReg.virtRegIndex()))
618 return !MBB->pred_empty();
619
620 // See if the first \p Limit def of the register are all in the current block.
621 static const unsigned Limit = 8;
622 unsigned C = 0;
623 for (const MachineInstr &DefInst : MRI->def_instructions(VirtReg)) {
624 if (DefInst.getParent() != MBB || ++C >= Limit) {
625 MayLiveAcrossBlocks.set(VirtReg.virtRegIndex());
626 return !MBB->pred_empty();
627 }
628 }
629
630 return false;
631}
632
633/// Insert spill instruction for \p AssignedReg before \p Before. Update
634/// DBG_VALUEs with \p VirtReg operands with the stack slot.
635void RegAllocFastImpl::spill(MachineBasicBlock::iterator Before,
636 Register VirtReg, MCRegister AssignedReg,
637 bool Kill, bool LiveOut) {
638 LLVM_DEBUG(dbgs() << "Spilling " << printReg(VirtReg, TRI) << " in "
639 << printReg(AssignedReg, TRI));
640 int FI = getStackSpaceFor(VirtReg);
641 LLVM_DEBUG(dbgs() << " to stack slot #" << FI << '\n');
642
643 const TargetRegisterClass &RC = *MRI->getRegClass(VirtReg);
644 TII->storeRegToStackSlot(*MBB, Before, AssignedReg, Kill, FI, &RC, VirtReg);
645 ++NumStores;
646
648
649 // When we spill a virtual register, we will have spill instructions behind
650 // every definition of it, meaning we can switch all the DBG_VALUEs over
651 // to just reference the stack slot.
652 SmallVectorImpl<MachineOperand *> &LRIDbgOperands = LiveDbgValueMap[VirtReg];
653 SmallMapVector<MachineInstr *, SmallVector<const MachineOperand *>, 2>
654 SpilledOperandsMap;
655 for (MachineOperand *MO : LRIDbgOperands)
656 SpilledOperandsMap[MO->getParent()].push_back(MO);
657 for (const auto &MISpilledOperands : SpilledOperandsMap) {
658 MachineInstr &DBG = *MISpilledOperands.first;
659 // We don't have enough support for tracking operands of DBG_VALUE_LISTs.
660 if (DBG.isDebugValueList())
661 continue;
662 MachineInstr *NewDV = buildDbgValueForSpill(
663 *MBB, Before, *MISpilledOperands.first, FI, MISpilledOperands.second);
664 assert(NewDV->getParent() == MBB && "dangling parent pointer");
665 (void)NewDV;
666 LLVM_DEBUG(dbgs() << "Inserting debug info due to spill:\n" << *NewDV);
667
668 if (LiveOut) {
669 // We need to insert a DBG_VALUE at the end of the block if the spill slot
670 // is live out, but there is another use of the value after the
671 // spill. This will allow LiveDebugValues to see the correct live out
672 // value to propagate to the successors.
673 MachineInstr *ClonedDV = MBB->getParent()->CloneMachineInstr(NewDV);
674 MBB->insert(FirstTerm, ClonedDV);
675 LLVM_DEBUG(dbgs() << "Cloning debug info due to live out spill\n");
676 }
677
678 // Rewrite unassigned dbg_values to use the stack slot.
679 // TODO We can potentially do this for list debug values as well if we know
680 // how the dbg_values are getting unassigned.
681 if (DBG.isNonListDebugValue()) {
682 MachineOperand &MO = DBG.getDebugOperand(0);
683 if (MO.isReg() && !MO.getReg()) {
685 }
686 }
687 }
688 // Now this register is spilled there is should not be any DBG_VALUE
689 // pointing to this register because they are all pointing to spilled value
690 // now.
691 LRIDbgOperands.clear();
692}
693
694/// Insert reload instruction for \p PhysReg before \p Before.
695void RegAllocFastImpl::reload(MachineBasicBlock::iterator Before,
696 Register VirtReg, MCRegister PhysReg) {
697 LLVM_DEBUG(dbgs() << "Reloading " << printReg(VirtReg, TRI) << " into "
698 << printReg(PhysReg, TRI) << '\n');
699 int FI = getStackSpaceFor(VirtReg);
700 const TargetRegisterClass &RC = *MRI->getRegClass(VirtReg);
701 TII->loadRegFromStackSlot(*MBB, Before, PhysReg, FI, &RC, VirtReg);
702 ++NumLoads;
703}
704
705/// Get basic block begin insertion point.
706/// This is not just MBB.begin() because surprisingly we have EH_LABEL
707/// instructions marking the begin of a basic block. This means we must insert
708/// new instructions after such labels...
709MachineBasicBlock::iterator RegAllocFastImpl::getMBBBeginInsertionPoint(
710 MachineBasicBlock &MBB, SmallSet<Register, 2> &PrologLiveIns) const {
712 while (I != MBB.end()) {
713 if (I->isLabel()) {
714 ++I;
715 continue;
716 }
717
718 // Skip prologues and inlineasm_br spills to place reloads afterwards.
719 if (!TII->isBasicBlockPrologue(*I) && !mayBeSpillFromInlineAsmBr(*I))
720 break;
721
722 // However if a prolog instruction reads a register that needs to be
723 // reloaded, the reload should be inserted before the prolog.
724 for (MachineOperand &MO : I->operands()) {
725 if (MO.isReg())
726 PrologLiveIns.insert(MO.getReg());
727 }
728
729 ++I;
730 }
731
732 return I;
733}
734
735/// Reload all currently assigned virtual registers.
736void RegAllocFastImpl::reloadAtBegin(MachineBasicBlock &MBB) {
737 if (LiveVirtRegs.empty())
738 return;
739
740 // Mark live-in registers so the loop below skips reloads into them. The
741 // virtual register mappings this overwrites are not needed anymore.
742 for (MachineBasicBlock::RegisterMaskPair P : MBB.liveins())
743 setPhysRegState(P.PhysReg, regLiveIn);
744
745 SmallSet<Register, 2> PrologLiveIns;
746
747 // The LiveRegMap is keyed by an unsigned (the virtreg number), so the order
748 // of spilling here is deterministic, if arbitrary.
749 MachineBasicBlock::iterator InsertBefore =
750 getMBBBeginInsertionPoint(MBB, PrologLiveIns);
751 for (const LiveReg &LR : LiveVirtRegs) {
752 MCRegister PhysReg = LR.PhysReg;
753 if (!PhysReg || LR.Error)
754 continue;
755
756 MCRegUnit FirstUnit = *TRI->regunits(PhysReg).begin();
757 if (getRegUnitState(FirstUnit) == regLiveIn)
758 continue;
759
760 assert(&MBB != &MBB.getParent()->front() &&
761 "no reload in start block. Missing vreg def?");
762
763 if (PrologLiveIns.count(PhysReg)) {
764 // FIXME: Theoretically this should use an insert point skipping labels
765 // but I'm not sure how labels should interact with prolog instruction
766 // that need reloads.
767 reload(MBB.begin(), LR.VirtReg, PhysReg);
768 } else
769 reload(InsertBefore, LR.VirtReg, PhysReg);
770 }
771 LiveVirtRegs.clear();
772}
773
774/// Handle the direct use of a physical register. Displace whatever occupies it
775/// and mark it pre-assigned: backwards, a use means live from here upward.
776/// Returns false if nothing was displaced, so the use is a kill. This may add
777/// implicit kills to MO->getParent() and invalidate MO.
778bool RegAllocFastImpl::usePhysReg(MachineInstr &MI, MCRegister Reg) {
779 assert(Reg.isPhysical() && "expected physreg");
780 bool displacedAny = displacePhysReg(MI, Reg);
781 setPhysRegState(Reg, regPreAssigned);
782 markRegUsedInInstr(Reg);
783 return displacedAny;
784}
785
786/// Displace whatever holds \p Reg and reserve it, so a virtual register def
787/// cannot land on a register this instruction already writes. Released in the
788/// free-def-operands step, after the uses for an early clobber, or by
789/// lowerTiedUse(); if the instruction also reads \p Reg it ends up reserved
790/// for the code above.
791bool RegAllocFastImpl::definePhysReg(MachineInstr &MI, MCRegister Reg) {
792 bool displacedAny = displacePhysReg(MI, Reg);
793 setPhysRegState(Reg, regPreAssigned);
794 return displacedAny;
795}
796
797/// Mark PhysReg as reserved or free after spilling any virtregs. This is very
798/// similar to defineVirtReg except the physreg is reserved instead of
799/// allocated.
800bool RegAllocFastImpl::displacePhysReg(MachineInstr &MI, MCRegister PhysReg) {
801 bool displacedAny = false;
802
803 for (MCRegUnit Unit : TRI->regunits(PhysReg)) {
804 switch (unsigned VirtReg = getRegUnitState(Unit)) {
805 default: {
806 LiveRegMap::iterator LRI = findLiveVirtReg(VirtReg);
807 assert(LRI != LiveVirtRegs.end() && "datastructures in sync");
808 MachineBasicBlock::iterator ReloadBefore =
809 std::next((MachineBasicBlock::iterator)MI.getIterator());
810 while (mayBeSpillFromInlineAsmBr(*ReloadBefore))
811 ++ReloadBefore;
812 reload(ReloadBefore, VirtReg, LRI->PhysReg);
813
814 setPhysRegState(LRI->PhysReg, regFree);
815 LRI->PhysReg = MCRegister();
816 LRI->Reloaded = true;
817 displacedAny = true;
818 break;
819 }
820 case regPreAssigned:
821 setRegUnitState(Unit, regFree);
822 displacedAny = true;
823 break;
824 case regFree:
825 break;
826 }
827 }
828 return displacedAny;
829}
830
831void RegAllocFastImpl::freePhysReg(MCRegister PhysReg) {
832 LLVM_DEBUG(dbgs() << "Freeing " << printReg(PhysReg, TRI) << ':');
833
834 MCRegUnit FirstUnit = *TRI->regunits(PhysReg).begin();
835 switch (unsigned VirtReg = getRegUnitState(FirstUnit)) {
836 case regFree:
837 LLVM_DEBUG(dbgs() << '\n');
838 return;
839 case regPreAssigned:
840 LLVM_DEBUG(dbgs() << '\n');
841 setPhysRegState(PhysReg, regFree);
842 return;
843 default: {
844 LiveRegMap::iterator LRI = findLiveVirtReg(VirtReg);
845 assert(LRI != LiveVirtRegs.end());
846 LLVM_DEBUG(dbgs() << ' ' << printReg(LRI->VirtReg, TRI) << '\n');
847 setPhysRegState(LRI->PhysReg, regFree);
848 LRI->PhysReg = MCRegister();
849 }
850 return;
851 }
852}
853
854/// Return the cost of spilling clearing out PhysReg and aliases so it is free
855/// for allocation. Returns 0 when PhysReg is free or disabled with all aliases
856/// disabled - it can be allocated directly.
857/// \returns spillImpossible when PhysReg or an alias can't be spilled.
858unsigned RegAllocFastImpl::calcSpillCost(MCPhysReg PhysReg) const {
859 for (MCRegUnit Unit : TRI->regunits(PhysReg)) {
860 switch (unsigned VirtReg = getRegUnitState(Unit)) {
861 case regFree:
862 break;
863 case regPreAssigned:
864 LLVM_DEBUG(dbgs() << "Cannot spill pre-assigned "
865 << printReg(PhysReg, TRI) << '\n');
866 return spillImpossible;
867 default: {
868 bool SureSpill = StackSlotForVirtReg[VirtReg] != -1 ||
869 findLiveVirtReg(VirtReg)->LiveOut;
870 return SureSpill ? spillClean : spillDirty;
871 }
872 }
873 }
874 return 0;
875}
876
877void RegAllocFastImpl::assignDanglingDebugValues(MachineInstr &Definition,
878 Register VirtReg,
879 MCRegister Reg) {
880 auto UDBGValIter = DanglingDbgValues.find(VirtReg);
881 if (UDBGValIter == DanglingDbgValues.end())
882 return;
883
884 SmallVectorImpl<MachineInstr *> &Dangling = UDBGValIter->second;
885 for (MachineInstr *DbgValue : Dangling) {
886 assert(DbgValue->isDebugValue());
887 if (!DbgValue->hasDebugOperandForReg(VirtReg))
888 continue;
889
890 // Test whether the physreg survives from the definition to the DBG_VALUE.
891 // A tied use that took over its def's register is assigned at an
892 // instruction that overwrites it, so start the scan there.
893 MCRegister SetToReg = Reg;
894 unsigned Limit = 20;
895 MachineBasicBlock::iterator I = Definition.getIterator();
896 if (!Definition.definesRegister(Reg, TRI))
897 ++I;
898 for (MachineBasicBlock::iterator E = DbgValue->getIterator(); I != E; ++I) {
899 if (I->modifiesRegister(Reg, TRI) || --Limit == 0) {
900 LLVM_DEBUG(dbgs() << "Register did not survive for " << *DbgValue
901 << '\n');
902 SetToReg = MCRegister();
903 break;
904 }
905 }
906 for (MachineOperand &MO : DbgValue->getDebugOperandsForReg(VirtReg)) {
907 MO.setReg(SetToReg);
908 if (SetToReg)
909 MO.setIsRenamable();
910 }
911 }
912 Dangling.clear();
913}
914
915/// This method updates local state so that we know that PhysReg is the
916/// proper container for VirtReg now. The physical register must not be used
917/// for anything else when this is called.
918void RegAllocFastImpl::assignVirtToPhysReg(MachineInstr &AtMI, LiveReg &LR,
919 MCRegister PhysReg) {
920 Register VirtReg = LR.VirtReg;
921 LLVM_DEBUG(dbgs() << "Assigning " << printReg(VirtReg, TRI) << " to "
922 << printReg(PhysReg, TRI) << '\n');
923 assert(!LR.PhysReg && "Already assigned a physreg");
924 assert(PhysReg && "Trying to assign no register");
925 LR.PhysReg = PhysReg;
926 setPhysRegState(PhysReg, VirtReg.id());
927
928 assignDanglingDebugValues(AtMI, VirtReg, PhysReg);
929}
930
931static bool isCoalescable(const MachineInstr &MI) { return MI.isFullCopy(); }
932
933/// The operand \p MO is tied to.
935 const MachineOperand &MO) {
936 return MI.getOperand(MI.findTiedOperandIdx(MI.getOperandNo(&MO)));
937}
938
939/// The register \p DefMO's tied use reads, when the two end up in the same
940/// register: a subregister index on either side makes them differ.
942 const MachineOperand &DefMO) {
943 if (!DefMO.isTied() || DefMO.getSubReg())
944 return Register();
945 const MachineOperand &UseMO = getTiedOperand(MI, DefMO);
946 return UseMO.getSubReg() ? Register() : UseMO.getReg();
947}
948
949Register RegAllocFastImpl::traceCopyChain(Register Reg) const {
950 static const unsigned ChainLengthLimit = 3;
951 for (unsigned C = 0; C <= ChainLengthLimit; ++C) {
952 if (Reg.isPhysical())
953 return Reg;
955
956 const MachineOperand *DefMO = MRI->getOneDef(Reg);
957 if (!DefMO)
958 return Register();
959 const MachineInstr *Def = DefMO->getParent();
960 if (isCoalescable(*Def)) {
961 Reg = Def->getOperand(1).getReg();
962 continue;
963 }
964 // A two-address instruction's def and tied use end up in the same
965 // register, so the tie continues the chain.
966 Reg = LowerTiedOps ? getTiedUseReg(*Def, *DefMO) : Register();
967 if (!Reg)
968 return Register();
969 }
970 return Register();
971}
972
973/// Check if any of \p VirtReg's definitions is a copy or a tied def. If it is
974/// follow the chain of copies to check whether we reach a physical register we
975/// can coalesce with.
976Register RegAllocFastImpl::traceCopies(Register VirtReg) const {
977 static const unsigned DefLimit = 3;
978 unsigned C = 0;
979 for (const MachineOperand &DefMO : MRI->def_operands(VirtReg)) {
980 const MachineInstr &MI = *DefMO.getParent();
982 if (isCoalescable(MI))
983 Reg = MI.getOperand(1).getReg();
984 else if (LowerTiedOps)
985 Reg = getTiedUseReg(MI, DefMO);
986 if (Reg) {
987 Reg = traceCopyChain(Reg);
988 if (Reg.isValid())
989 return Reg;
990 }
991
992 if (++C >= DefLimit)
993 break;
994 }
995 return Register();
996}
997
998/// Allocates a physical register for VirtReg.
999void RegAllocFastImpl::allocVirtReg(MachineInstr &MI, LiveReg &LR,
1000 Register Hint0, bool LookAtPhysRegUses) {
1001 const Register VirtReg = LR.VirtReg;
1002 assert(!LR.PhysReg);
1003
1004 const TargetRegisterClass &RC = *MRI->getRegClass(VirtReg);
1005 LLVM_DEBUG(dbgs() << "Search register for " << printReg(VirtReg)
1006 << " in class " << TRI->getRegClassName(&RC)
1007 << " with hint " << printReg(Hint0, TRI) << '\n');
1008
1009 // Take hint when possible.
1010 if (Hint0.isPhysical() && MRI->isAllocatable(Hint0) && RC.contains(Hint0) &&
1011 !isRegUsedInInstr(Hint0, LookAtPhysRegUses)) {
1012 // Take hint if the register is currently free.
1013 if (isPhysRegFree(Hint0)) {
1014 LLVM_DEBUG(dbgs() << "\tPreferred Register 1: " << printReg(Hint0, TRI)
1015 << '\n');
1016 assignVirtToPhysReg(MI, LR, Hint0);
1017 return;
1018 } else {
1019 LLVM_DEBUG(dbgs() << "\tPreferred Register 0: " << printReg(Hint0, TRI)
1020 << " occupied\n");
1021 }
1022 } else {
1023 Hint0 = Register();
1024 }
1025
1026 // Try other hint.
1027 Register Hint1 = traceCopies(VirtReg);
1028 if (Hint1.isPhysical() && MRI->isAllocatable(Hint1) && RC.contains(Hint1) &&
1029 !isRegUsedInInstr(Hint1, LookAtPhysRegUses)) {
1030 // Take hint if the register is currently free.
1031 if (isPhysRegFree(Hint1)) {
1032 LLVM_DEBUG(dbgs() << "\tPreferred Register 0: " << printReg(Hint1, TRI)
1033 << '\n');
1034 assignVirtToPhysReg(MI, LR, Hint1);
1035 return;
1036 } else {
1037 LLVM_DEBUG(dbgs() << "\tPreferred Register 1: " << printReg(Hint1, TRI)
1038 << " occupied\n");
1039 }
1040 } else {
1041 Hint1 = Register();
1042 }
1043
1044 MCPhysReg BestReg = 0;
1045 unsigned BestCost = spillImpossible;
1046 ArrayRef<MCPhysReg> AllocationOrder = RegClassInfo->getOrder(&RC);
1047 for (MCPhysReg PhysReg : AllocationOrder) {
1048 LLVM_DEBUG(dbgs() << "\tRegister: " << printReg(PhysReg, TRI) << ' ');
1049 if (isRegUsedInInstr(PhysReg, LookAtPhysRegUses)) {
1050 LLVM_DEBUG(dbgs() << "already used in instr.\n");
1051 continue;
1052 }
1053
1054 unsigned Cost = calcSpillCost(PhysReg);
1055 LLVM_DEBUG(dbgs() << "Cost: " << Cost << " BestCost: " << BestCost << '\n');
1056 // Immediate take a register with cost 0.
1057 if (Cost == 0) {
1058 assignVirtToPhysReg(MI, LR, PhysReg);
1059 return;
1060 }
1061
1062 if (PhysReg == Hint0 || PhysReg == Hint1)
1063 Cost -= spillPrefBonus;
1064
1065 if (Cost < BestCost) {
1066 BestReg = PhysReg;
1067 BestCost = Cost;
1068 }
1069 }
1070
1071 if (!BestReg) {
1072 // Nothing we can do: Report an error and keep going with an invalid
1073 // allocation.
1074 LR.PhysReg = getErrorAssignment(LR, MI, RC);
1075 LR.Error = true;
1076 return;
1077 }
1078
1079 displacePhysReg(MI, BestReg);
1080 assignVirtToPhysReg(MI, LR, BestReg);
1081}
1082
1083void RegAllocFastImpl::allocVirtRegUndef(MachineOperand &MO) {
1084 assert(MO.isUndef() && "expected undef use");
1085 Register VirtReg = MO.getReg();
1086 assert(VirtReg.isVirtual() && "Expected virtreg");
1087 if (!shouldAllocateRegister(VirtReg))
1088 return;
1089
1090 // If there are multiple undef uses, give them the same register. The def is
1091 // already freed, so take the register from the tie, not the lookup below.
1092 MachineInstr &MI = *MO.getParent();
1093 for (const MachineOperand &Tied : MI.all_uses()) {
1094 if (!Tied.isTied() || Tied.getReg() != VirtReg)
1095 continue;
1096 MCRegister DefReg = getTiedOperand(MI, Tied).getReg().asMCReg();
1097 for (MachineOperand &O : MI.all_uses()) {
1098 if (O.getReg() != VirtReg)
1099 continue;
1100 // The def is already narrowed, so a tie takes its register whole.
1101 unsigned SubIdx = O.isTied() ? 0 : O.getSubReg();
1102 O.setReg(SubIdx ? TRI->getSubReg(DefReg, SubIdx) : DefReg);
1103 O.setSubReg(0);
1104 O.setIsRenamable(!MRI->isReserved(O.getReg()));
1105 }
1106 return;
1107 }
1108
1109 LiveRegMap::iterator LRI = findLiveVirtReg(VirtReg);
1110 MCRegister PhysReg;
1111 bool IsRenamable = true;
1112 if (LRI != LiveVirtRegs.end() && LRI->PhysReg) {
1113 PhysReg = LRI->PhysReg;
1114 } else {
1115 const TargetRegisterClass &RC = *MRI->getRegClass(VirtReg);
1116 ArrayRef<MCPhysReg> AllocationOrder = RegClassInfo->getOrder(&RC);
1117 if (AllocationOrder.empty()) {
1118 // All registers in the class were reserved.
1119 //
1120 // It might be OK to take any entry from the class as this is an undef
1121 // use, but accepting this would give different behavior than greedy and
1122 // basic.
1123 PhysReg = getErrorAssignment(*LRI, *MO.getParent(), RC);
1124 LRI->Error = true;
1125 IsRenamable = false;
1126 } else
1127 PhysReg = AllocationOrder.front();
1128 }
1129
1130 unsigned SubRegIdx = MO.getSubReg();
1131 if (SubRegIdx != 0) {
1132 PhysReg = TRI->getSubReg(PhysReg, SubRegIdx);
1133 MO.setSubReg(0);
1134 }
1135 MO.setReg(PhysReg);
1136 MO.setIsRenamable(IsRenamable);
1137}
1138
1139/// Variation of defineVirtReg() with special handling for livethrough regs
1140/// (tied or earlyclobber) that may interfere with preassigned uses.
1141/// \return true if MI's MachineOperands were re-arranged/invalidated.
1142bool RegAllocFastImpl::defineLiveThroughVirtReg(MachineInstr &MI,
1143 unsigned OpNum,
1144 Register VirtReg) {
1145 if (!shouldAllocateRegister(VirtReg))
1146 return false;
1147 LiveRegMap::iterator LRI = findLiveVirtReg(VirtReg);
1148 if (LRI != LiveVirtRegs.end()) {
1149 MCRegister PrevReg = LRI->PhysReg;
1150 if (PrevReg && isRegUsedInInstr(PrevReg, true)) {
1151 LLVM_DEBUG(dbgs() << "Need new assignment for " << printReg(PrevReg, TRI)
1152 << " (tied/earlyclobber resolution)\n");
1153 freePhysReg(PrevReg);
1154 LRI->PhysReg = MCRegister();
1155 allocVirtReg(MI, *LRI, Register(), true);
1156 MachineBasicBlock::iterator InsertBefore =
1157 std::next((MachineBasicBlock::iterator)MI.getIterator());
1158 LLVM_DEBUG(dbgs() << "Copy " << printReg(LRI->PhysReg, TRI) << " to "
1159 << printReg(PrevReg, TRI) << '\n');
1160 BuildMI(*MBB, InsertBefore, MI.getDebugLoc(),
1161 TII->get(TargetOpcode::COPY), PrevReg)
1162 .addReg(LRI->PhysReg, llvm::RegState::Kill);
1163 }
1164 MachineOperand &MO = MI.getOperand(OpNum);
1165 if (MO.getSubReg() && !MO.isUndef()) {
1166 LRI->LastUse = &MI;
1167 }
1168 }
1169 return defineVirtReg(MI, OpNum, VirtReg, true);
1170}
1171
1172/// Allocates a register for VirtReg definition. Typically the register is
1173/// already assigned from a use of the virtreg, however we still need to
1174/// perform an allocation if:
1175/// - It is a dead definition without any uses.
1176/// - The value is live out and all uses are in different basic blocks.
1177///
1178/// \return true if MI's MachineOperands were re-arranged/invalidated.
1179bool RegAllocFastImpl::defineVirtReg(MachineInstr &MI, unsigned OpNum,
1180 Register VirtReg, bool LookAtPhysRegUses) {
1181 assert(VirtReg.isVirtual() && "Not a virtual register");
1182 if (!shouldAllocateRegister(VirtReg))
1183 return false;
1184 MachineOperand &MO = MI.getOperand(OpNum);
1185 LiveRegMap::iterator LRI;
1186 bool New;
1187 std::tie(LRI, New) = LiveVirtRegs.insert(LiveReg(VirtReg));
1188 if (New) {
1189 if (!MO.isDead()) {
1190 if (mayLiveOut(VirtReg)) {
1191 LRI->LiveOut = true;
1192 } else {
1193 // It is a dead def without the dead flag; add the flag now.
1194 MO.setIsDead(true);
1195 }
1196 }
1197 }
1198 if (!LRI->PhysReg) {
1199 allocVirtReg(MI, *LRI, Register(), LookAtPhysRegUses);
1200 } else {
1201 assert((!isRegUsedInInstr(LRI->PhysReg, LookAtPhysRegUses) || LRI->Error) &&
1202 "TODO: preassign mismatch");
1203 LLVM_DEBUG(dbgs() << "In def of " << printReg(VirtReg, TRI)
1204 << " use existing assignment to "
1205 << printReg(LRI->PhysReg, TRI) << '\n');
1206 }
1207
1208 MCRegister PhysReg = LRI->PhysReg;
1209 // Either flag means a reader below depends on the slot.
1210 if (LRI->Reloaded || LRI->LiveOut) {
1211 if (!MI.isImplicitDef()) {
1212 MachineBasicBlock::iterator SpillBefore =
1213 std::next((MachineBasicBlock::iterator)MI.getIterator());
1214 LLVM_DEBUG(dbgs() << "Spill Reason: LO: " << LRI->LiveOut
1215 << " RL: " << LRI->Reloaded << '\n');
1216 bool Kill = LRI->LastUse == nullptr;
1217 spill(SpillBefore, VirtReg, PhysReg, Kill, LRI->LiveOut);
1218
1219 // We need to place additional spills for each indirect destination of an
1220 // INLINEASM_BR.
1221 if (MI.getOpcode() == TargetOpcode::INLINEASM_BR) {
1222 int FI = StackSlotForVirtReg[VirtReg];
1223 const TargetRegisterClass &RC = *MRI->getRegClass(VirtReg);
1224 for (MachineOperand &MO : MI.operands()) {
1225 if (MO.isMBB()) {
1226 MachineBasicBlock *Succ = MO.getMBB();
1227 TII->storeRegToStackSlot(*Succ, Succ->begin(), PhysReg, Kill, FI,
1228 &RC, VirtReg);
1229 ++NumStores;
1230 Succ->addLiveIn(PhysReg);
1231 }
1232 }
1233 }
1234
1235 LRI->LastUse = nullptr;
1236 } else if (!LRI->LastUse) {
1237 // No spill was inserted, so nothing below reads this def.
1238 MO.setIsDead(true);
1239 }
1240 // A def above spills only if a displacement above reloads again.
1241 LRI->LiveOut = false;
1242 LRI->Reloaded = false;
1243 }
1244 if (MI.getOpcode() == TargetOpcode::BUNDLE) {
1245 BundleVirtRegsMap[VirtReg] = *LRI;
1246 }
1247 markRegUsedInInstr(PhysReg);
1248 return setPhysReg(MI, MO, *LRI);
1249}
1250
1251/// Place MO's value in its tied def's register, by taking the register over or
1252/// copying into it. Return false if useVirtReg() should finish MO.
1253bool RegAllocFastImpl::lowerTiedUse(MachineInstr &MI, MachineOperand &MO,
1254 LiveReg &LR) {
1255 const MachineOperand &DefMO = getTiedOperand(MI, MO);
1256 assert(DefMO.getReg().isPhysical() && "tied def allocated before its use");
1257 MCRegister DefReg = DefMO.getReg().asMCReg();
1258 unsigned SubReg = MO.getSubReg();
1259 if (!LR.PhysReg) {
1260 // No register holds the value below MI, so it can live in DefReg, unless
1261 // MO reads a subregister, DefReg cannot hold the value, or an early-clobber
1262 // def would overwrite DefReg before another operand reads the value.
1263 bool MustCopy = SubReg || !MRI->isAllocatable(DefReg) ||
1264 !MRI->getRegClass(LR.VirtReg)->contains(DefReg) ||
1265 (DefMO.isEarlyClobber() &&
1266 any_of(MI.all_uses(), [&](const MachineOperand &O) {
1267 return &O != &MO && O.getReg() == LR.VirtReg;
1268 }));
1269 if (!MustCopy) {
1270 // The def is not live above MI, so the value can occupy DefReg there.
1271 freePhysReg(DefReg);
1272 assignVirtToPhysReg(MI, LR, DefReg);
1273 return false;
1274 }
1275 allocVirtReg(MI, LR, Register(), false);
1276 // The def phase marked DefReg used in MI, so allocVirtReg skips it.
1277 assert((LR.Error || !TRI->regsOverlap(LR.PhysReg, DefReg)) &&
1278 "copy source overlaps the tied def");
1279 }
1280
1281 MCRegister SrcReg = SubReg ? TRI->getSubReg(LR.PhysReg, SubReg) : LR.PhysReg;
1282 // Only an already rewritten tie (%x = OP %x) finds the value in DefReg.
1283 if (SrcReg == DefReg)
1284 return false;
1285
1286 // The copy reads SrcReg above MI, so no other operand may take it.
1287 BuildMI(*MBB, MI, MI.getDebugLoc(), TII->get(TargetOpcode::COPY), DefReg)
1288 .addReg(SrcReg);
1289 LR.LastUse = &MI;
1290 markRegUsedInInstr(LR.PhysReg);
1291
1292 bool Renamable = !MRI->isReserved(DefReg);
1293 auto ReadDefReg = [&](MachineOperand &O) {
1294 O.setReg(DefReg);
1295 O.setSubReg(0);
1296 O.setIsRenamable(Renamable);
1297 };
1298 ReadDefReg(MO);
1299 // The other reads of the value follow it into DefReg, so SrcReg dies at the
1300 // copy. They cannot when an early-clobber def overwrites DefReg first, and a
1301 // read tied to another def owes that def's register.
1302 if (!DefMO.isEarlyClobber()) {
1303 for (MachineOperand &O : MI.all_uses()) {
1304 if (O.isTied() || O.getReg() != LR.VirtReg || O.getSubReg() != SubReg)
1305 continue;
1306 ReadDefReg(O);
1307 O.setIsKill(false);
1308 }
1309 }
1310
1311 // The free-defs step skips tied defs, so DefReg still holds the def.
1312 freePhysReg(DefReg);
1313 return true;
1314}
1315
1316/// Allocates a register for a VirtReg use.
1317/// \return true if MI's MachineOperands were re-arranged/invalidated.
1318bool RegAllocFastImpl::useVirtReg(MachineInstr &MI, MachineOperand &MO,
1319 Register VirtReg) {
1320 assert(VirtReg.isVirtual() && "Not a virtual register");
1321 if (!shouldAllocateRegister(VirtReg))
1322 return false;
1323 LiveRegMap::iterator LRI;
1324 bool New;
1325 std::tie(LRI, New) = LiveVirtRegs.insert(LiveReg(VirtReg));
1326 if (New) {
1327 if (!MO.isKill()) {
1328 if (mayLiveOut(VirtReg)) {
1329 LRI->LiveOut = true;
1330 } else {
1331 // It is a last (killing) use without the kill flag; add the flag now.
1332 MO.setIsKill(true);
1333 }
1334 }
1335 } else {
1336 assert((!MO.isKill() || LRI->LastUse == &MI) && "Invalid kill flag");
1337 }
1338
1339 if (LowerTiedOps && MO.isTied() && lowerTiedUse(MI, MO, *LRI))
1340 return false;
1341
1342 // If necessary allocate a register.
1343 if (!LRI->PhysReg) {
1344 assert(!MO.isTied() && "tied op should be allocated");
1345 Register Hint;
1346 if (MI.isCopy() && MI.getOperand(1).getSubReg() == 0) {
1347 Hint = MI.getOperand(0).getReg();
1348 if (Hint.isVirtual()) {
1349 assert(!shouldAllocateRegister(Hint));
1350 Hint = Register();
1351 } else {
1352 assert(Hint.isPhysical() &&
1353 "Copy destination should already be assigned");
1354 }
1355 }
1356 allocVirtReg(MI, *LRI, Hint, false);
1357 }
1358
1359 LRI->LastUse = &MI;
1360
1361 if (MI.getOpcode() == TargetOpcode::BUNDLE) {
1362 BundleVirtRegsMap[VirtReg] = *LRI;
1363 }
1364 markRegUsedInInstr(LRI->PhysReg);
1365 return setPhysReg(MI, MO, *LRI);
1366}
1367
1368/// Clear dead flags on defs of any register which also has a live def on \p MI.
1370 for (const MachineOperand &MO : MI.all_defs()) {
1371 if (!MO.isDead())
1372 MI.clearRegisterDeads(MO.getReg());
1373 }
1374}
1375
1376/// Query a physical register to use as a filler in contexts where the
1377/// allocation has failed. This will raise an error, but not abort the
1378/// compilation.
1379MCPhysReg RegAllocFastImpl::getErrorAssignment(const LiveReg &LR,
1380 MachineInstr &MI,
1381 const TargetRegisterClass &RC) {
1382 MachineFunction &MF = *MI.getMF();
1383
1384 // Avoid repeating the error every time a register is used.
1385 bool EmitError = !MF.getProperties().hasFailedRegAlloc();
1386 if (EmitError)
1387 MF.getProperties().setFailedRegAlloc();
1388
1389 // If the allocation order was empty, all registers in the class were
1390 // probably reserved. Fall back to taking the first register in the class,
1391 // even if it's reserved.
1392 ArrayRef<MCPhysReg> AllocationOrder = RegClassInfo->getOrder(&RC);
1393 if (AllocationOrder.empty()) {
1394 const Function &Fn = MF.getFunction();
1395 if (EmitError) {
1396 Fn.getContext().diagnose(DiagnosticInfoRegAllocFailure(
1397 "no registers from class available to allocate", Fn,
1398 MI.getDebugLoc()));
1399 }
1400
1401 ArrayRef<MCPhysReg> RawRegs = RC.getRegisters();
1402 assert(!RawRegs.empty() && "register classes cannot have no registers");
1403 return RawRegs.front();
1404 }
1405
1406 if (!LR.Error && EmitError) {
1407 // Nothing we can do: Report an error and keep going with an invalid
1408 // allocation.
1409 if (MI.isInlineAsm()) {
1410 MI.emitInlineAsmError(
1411 "inline assembly requires more registers than available");
1412 } else {
1413 const Function &Fn = MBB->getParent()->getFunction();
1414 Fn.getContext().diagnose(DiagnosticInfoRegAllocFailure(
1415 "ran out of registers during register allocation", Fn,
1416 MI.getDebugLoc()));
1417 }
1418 }
1419
1420 return AllocationOrder.front();
1421}
1422
1423/// Changes operand OpNum in MI the refer the PhysReg, considering subregs.
1424/// \return true if MI's MachineOperands were re-arranged/invalidated.
1425bool RegAllocFastImpl::setPhysReg(MachineInstr &MI, MachineOperand &MO,
1426 const LiveReg &Assignment) {
1427 MCRegister PhysReg = Assignment.PhysReg;
1428 assert(PhysReg && "assignments should always be to a valid physreg");
1429
1430 if (LLVM_UNLIKELY(Assignment.Error)) {
1431 // Make sure we don't set renamable in error scenarios, as we may have
1432 // assigned to a reserved register.
1433 if (MO.isUse())
1434 MO.setIsUndef(true);
1435 else
1436 HasErrorDef = true;
1437 }
1438
1439 if (!MO.getSubReg()) {
1440 MO.setReg(PhysReg);
1441 MO.setIsRenamable(!Assignment.Error);
1442 return false;
1443 }
1444
1445 // Handle subregister index.
1446 MO.setReg(TRI->getSubReg(PhysReg, MO.getSubReg()));
1447 MO.setIsRenamable(!Assignment.Error);
1448
1449 // Note: We leave the subreg number around a little longer in case of defs.
1450 // This is so that the register freeing logic in allocateInstruction can still
1451 // recognize this as subregister defs. The code there will clear the number.
1452 if (!MO.isDef())
1453 MO.setSubReg(0);
1454
1455 // A kill flag implies killing the full register. Add corresponding super
1456 // register kill.
1457 if (MO.isKill()) {
1458 MI.addRegisterKilled(PhysReg, TRI, true);
1459 // Conservatively assume implicit MOs were re-arranged
1460 return true;
1461 }
1462
1463 // A <def,read-undef> of a sub-register requires an implicit def of the full
1464 // register.
1465 if (MO.isDef() && MO.isUndef()) {
1466 if (MO.isDead())
1467 MI.addRegisterDead(PhysReg, TRI, true);
1468 else
1469 MI.addRegisterDefined(PhysReg, TRI);
1470 // Conservatively assume implicit MOs were re-arranged
1471 return true;
1472 }
1473 return false;
1474}
1475
1476#ifndef NDEBUG
1477
1478void RegAllocFastImpl::dumpState() const {
1479 for (MCRegUnit Unit : TRI->regunits()) {
1480 switch (unsigned VirtReg = getRegUnitState(Unit)) {
1481 case regFree:
1482 break;
1483 case regPreAssigned:
1484 dbgs() << " " << printRegUnit(Unit, TRI) << "[P]";
1485 break;
1486 case regLiveIn:
1487 llvm_unreachable("Should not have regLiveIn in map");
1488 default: {
1489 dbgs() << ' ' << printRegUnit(Unit, TRI) << '=' << printReg(VirtReg);
1490 LiveRegMap::const_iterator I = findLiveVirtReg(VirtReg);
1491 assert(I != LiveVirtRegs.end() && "have LiveVirtRegs entry");
1492 if (I->LiveOut || I->Reloaded) {
1493 dbgs() << '[';
1494 if (I->LiveOut)
1495 dbgs() << 'O';
1496 if (I->Reloaded)
1497 dbgs() << 'R';
1498 dbgs() << ']';
1499 }
1500 assert(TRI->hasRegUnit(I->PhysReg, Unit) && "inverse mapping present");
1501 break;
1502 }
1503 }
1504 }
1505 dbgs() << '\n';
1506 // Check that LiveVirtRegs is the inverse.
1507 for (const LiveReg &LR : LiveVirtRegs) {
1508 Register VirtReg = LR.VirtReg;
1509 assert(VirtReg.isVirtual() && "Bad map key");
1510 MCRegister PhysReg = LR.PhysReg;
1511 if (PhysReg) {
1512 assert(PhysReg.isPhysical() && "mapped to physreg");
1513 for (MCRegUnit Unit : TRI->regunits(PhysReg)) {
1514 assert(getRegUnitState(Unit) == VirtReg && "inverse map valid");
1515 }
1516 }
1517 }
1518}
1519#endif
1520
1521/// Count number of defs consumed from each register class by \p Reg
1522void RegAllocFastImpl::addRegClassDefCounts(
1523 MutableArrayRef<unsigned> RegClassDefCounts, Register Reg) const {
1524 assert(RegClassDefCounts.size() == TRI->getNumRegClasses());
1525
1526 if (Reg.isVirtual()) {
1527 if (!shouldAllocateRegister(Reg))
1528 return;
1529 const TargetRegisterClass *OpRC = MRI->getRegClass(Reg);
1530 for (unsigned RCIdx = 0, RCIdxEnd = TRI->getNumRegClasses();
1531 RCIdx != RCIdxEnd; ++RCIdx) {
1532 const TargetRegisterClass *IdxRC = TRI->getRegClass(RCIdx);
1533 // FIXME: Consider aliasing sub/super registers.
1534 if (OpRC->hasSubClassEq(IdxRC))
1535 ++RegClassDefCounts[RCIdx];
1536 }
1537
1538 return;
1539 }
1540
1541 for (unsigned RCIdx = 0, RCIdxEnd = TRI->getNumRegClasses();
1542 RCIdx != RCIdxEnd; ++RCIdx) {
1543 const TargetRegisterClass *IdxRC = TRI->getRegClass(RCIdx);
1544 for (MCRegAliasIterator Alias(Reg, TRI, true); Alias.isValid(); ++Alias) {
1545 if (IdxRC->contains(*Alias)) {
1546 ++RegClassDefCounts[RCIdx];
1547 break;
1548 }
1549 }
1550 }
1551}
1552
1553/// Early clobber, partial def, or tied to a use that carries a value: the
1554/// register is occupied while the uses are read.
1555static bool isLiveThroughDef(const MachineInstr &MI, const MachineOperand &MO) {
1556 assert(MO.isDef() && "expected def operand");
1557 if (MO.isEarlyClobber() || MO.readsReg())
1558 return true;
1559 return MO.isTied() &&
1560 !MI.getOperand(MI.findTiedOperandIdx(MI.getOperandNo(&MO))).isUndef();
1561}
1562
1563/// Compute \ref DefOperandIndexes so it contains the indices of "def" operands
1564/// that are to be allocated. Those are ordered in a way that small classes,
1565/// early clobbers and livethroughs are allocated first.
1566void RegAllocFastImpl::findAndSortDefOperandIndexes(const MachineInstr &MI) {
1567 DefOperandIndexes.clear();
1568
1569 LLVM_DEBUG(dbgs() << "Need to assign livethroughs\n");
1570 for (unsigned I = 0, E = MI.getNumOperands(); I < E; ++I) {
1571 const MachineOperand &MO = MI.getOperand(I);
1572 if (!MO.isReg())
1573 continue;
1574 Register Reg = MO.getReg();
1575 if (MO.readsReg()) {
1576 if (Reg.isPhysical()) {
1577 LLVM_DEBUG(dbgs() << "mark extra used: " << printReg(Reg, TRI) << '\n');
1578 markPhysRegUsedInInstr(Reg);
1579 }
1580 }
1581
1582 if (MO.isDef() && Reg.isVirtual() && shouldAllocateRegister(Reg))
1583 DefOperandIndexes.push_back(I);
1584 }
1585
1586 // Most instructions only have one virtual def, so there's no point in
1587 // computing the possible number of defs for every register class.
1588 if (DefOperandIndexes.size() <= 1)
1589 return;
1590
1591 // Track number of defs which may consume a register from the class. This is
1592 // used to assign registers for possibly-too-small classes first. Example:
1593 // defs are eax, 3 * gr32_abcd, 2 * gr32 => we want to assign the gr32_abcd
1594 // registers first so that the gr32 don't use the gr32_abcd registers before
1595 // we assign these.
1596 SmallVector<unsigned> RegClassDefCounts(TRI->getNumRegClasses(), 0);
1597
1598 for (const MachineOperand &MO : MI.all_defs())
1599 addRegClassDefCounts(RegClassDefCounts, MO.getReg());
1600
1601 llvm::sort(DefOperandIndexes, [&](unsigned I0, unsigned I1) {
1602 const MachineOperand &MO0 = MI.getOperand(I0);
1603 const MachineOperand &MO1 = MI.getOperand(I1);
1604 Register Reg0 = MO0.getReg();
1605 Register Reg1 = MO1.getReg();
1606 const TargetRegisterClass &RC0 = *MRI->getRegClass(Reg0);
1607 const TargetRegisterClass &RC1 = *MRI->getRegClass(Reg1);
1608
1609 // Identify regclass that are easy to use up completely just in this
1610 // instruction.
1611 unsigned ClassSize0 = RegClassInfo->getOrder(&RC0).size();
1612 unsigned ClassSize1 = RegClassInfo->getOrder(&RC1).size();
1613
1614 bool SmallClass0 = ClassSize0 < RegClassDefCounts[RC0.getID()];
1615 bool SmallClass1 = ClassSize1 < RegClassDefCounts[RC1.getID()];
1616 if (SmallClass0 > SmallClass1)
1617 return true;
1618 if (SmallClass0 < SmallClass1)
1619 return false;
1620
1621 // Allocate early clobbers and livethrough operands first.
1622 bool Livethrough0 = isLiveThroughDef(MI, MO0);
1623 bool Livethrough1 = isLiveThroughDef(MI, MO1);
1624 if (Livethrough0 > Livethrough1)
1625 return true;
1626 if (Livethrough0 < Livethrough1)
1627 return false;
1628
1629 // Tie-break rule: operand index.
1630 return I0 < I1;
1631 });
1632}
1633
1634void RegAllocFastImpl::allocateInstruction(MachineInstr &MI) {
1635 // Backwards, a def frees a register and a use occupies it. The phases:
1636 // * pre-assigned physreg defs
1637 // * virtual register defs
1638 // * free the def operands' registers
1639 // * displace registers clobbered by regmasks
1640 // * pre-assigned physreg uses
1641 // * virtual register uses, inserting reloads and tied-operand copies
1642 // * undef uses
1643 // * free early-clobber defs
1644 //
1645 // Freeing follows the def allocation so a def is not handed a register this
1646 // instruction also writes, and precedes the uses so a use may take one. It
1647 // skips tied defs, whose register the tied use reads, and early-clobber defs,
1648 // freed last so that no use lands on them.
1649
1650 InstrGen += 2;
1651 // In the event we ever get more than 2**31 instructions...
1652 if (LLVM_UNLIKELY(InstrGen == 0)) {
1653 UsedInInstr.assign(UsedInInstr.size(), 0);
1654 InstrGen = 2;
1655 }
1656 RegMasks.clear();
1657 LiveDefRegs.clear();
1658 BundleVirtRegsMap.clear();
1659
1660 // Scan for special cases; Apply pre-assigned register defs to state.
1661 bool HasPhysRegUse = false;
1662 bool HasRegMask = false;
1663 bool HasVRegDef = false;
1664 bool HasDef = false;
1665 bool HasEarlyClobber = false;
1666 bool HasTiedDef = false;
1667 bool NeedToAssignLiveThroughs = false;
1668 for (MachineOperand &MO : MI.operands()) {
1669 if (MO.isReg()) {
1670 Register Reg = MO.getReg();
1671 if (Reg.isVirtual()) {
1672 if (!shouldAllocateRegister(Reg))
1673 continue;
1674 if (MO.isDef()) {
1675 HasDef = true;
1676 HasVRegDef = true;
1677 if (MO.isEarlyClobber())
1678 HasEarlyClobber = true;
1679 if (LowerTiedOps && MO.isTied())
1680 HasTiedDef = true;
1681 if (isLiveThroughDef(MI, MO))
1682 NeedToAssignLiveThroughs = true;
1683 }
1684 } else if (Reg.isPhysical()) {
1685 if (!MRI->isReserved(Reg)) {
1686 if (MO.isDef()) {
1687 HasDef = true;
1688 bool displacedAny = definePhysReg(MI, Reg);
1689 if (MO.isEarlyClobber())
1690 HasEarlyClobber = true;
1691 if (!displacedAny)
1692 MO.setIsDead(true);
1693 if (!MO.isDead())
1694 LiveDefRegs.push_back(Reg.asMCReg());
1695 }
1696 if (MO.readsReg())
1697 HasPhysRegUse = true;
1698 }
1699 }
1700 } else if (MO.isRegMask()) {
1701 HasRegMask = true;
1702 RegMasks.push_back(MO.getRegMask());
1703 }
1704 }
1705
1706 // Allocate virtreg defs.
1707 if (HasDef) {
1708 if (HasVRegDef) {
1709 // Note that Implicit MOs can get re-arranged by defineVirtReg(), so loop
1710 // multiple times to ensure no operand is missed.
1711 bool ReArrangedImplicitOps = true;
1712
1713 // Special handling for early clobbers, tied operands or subregister defs:
1714 // Compared to "normal" defs these:
1715 // - Must not use a register that is pre-assigned for a use operand.
1716 // - In order to solve tricky inline assembly constraints we change the
1717 // heuristic to figure out a good operand order before doing
1718 // assignments.
1719 if (NeedToAssignLiveThroughs) {
1720 while (ReArrangedImplicitOps) {
1721 ReArrangedImplicitOps = false;
1722 findAndSortDefOperandIndexes(MI);
1723 for (unsigned OpIdx : DefOperandIndexes) {
1724 MachineOperand &MO = MI.getOperand(OpIdx);
1725 LLVM_DEBUG(dbgs() << "Allocating " << MO << '\n');
1726 Register Reg = MO.getReg();
1727 if (isLiveThroughDef(MI, MO)) {
1728 ReArrangedImplicitOps = defineLiveThroughVirtReg(MI, OpIdx, Reg);
1729 } else {
1730 ReArrangedImplicitOps = defineVirtReg(MI, OpIdx, Reg);
1731 }
1732 // Implicit operands of MI were re-arranged,
1733 // re-compute DefOperandIndexes.
1734 if (ReArrangedImplicitOps)
1735 break;
1736 }
1737 }
1738 } else {
1739 // Assign virtual register defs.
1740 while (ReArrangedImplicitOps) {
1741 ReArrangedImplicitOps = false;
1742 for (MachineOperand &MO : MI.all_defs()) {
1743 Register Reg = MO.getReg();
1744 if (Reg.isVirtual()) {
1745 ReArrangedImplicitOps =
1746 defineVirtReg(MI, MI.getOperandNo(&MO), Reg);
1747 if (ReArrangedImplicitOps)
1748 break;
1749 }
1750 }
1751 }
1752 }
1753 }
1754
1755 // Free registers occupied by defs.
1756 // Iterate operands in reverse order, so we see the implicit super register
1757 // defs first (we added them earlier in case of <def,read-undef>).
1758 for (MachineOperand &MO : reverse(MI.all_defs())) {
1759 Register Reg = MO.getReg();
1760
1761 // A dead def is kept alive by a non-dead def of the same register or a
1762 // super-register, so clear the inconsistent dead flag.
1763 if (Reg.isPhysical() && MO.isDead() &&
1764 hasLiveDefOfSuperReg(Reg.asMCReg()))
1765 MO.setIsDead(false);
1766
1767 // subreg defs don't free the full register. We left the subreg number
1768 // around as a marker in setPhysReg() to recognize this case here.
1769 if (Reg.isPhysical() && MO.getSubReg() != 0) {
1770 MO.setSubReg(0);
1771 continue;
1772 }
1773
1774 assert((!MO.isTied() || !isClobberedByRegMasks(MO.getReg())) &&
1775 "tied def assigned to clobbered register");
1776
1777 // Do not free live-through defs.
1778 if (isLiveThroughDef(MI, MO))
1779 continue;
1780 if (!Reg)
1781 continue;
1782 if (Reg.isVirtual()) {
1783 assert(!shouldAllocateRegister(Reg));
1784 continue;
1785 }
1787 if (MRI->isReserved(Reg))
1788 continue;
1789 freePhysReg(Reg);
1790 unmarkRegUsedInInstr(Reg);
1791 }
1792 }
1793
1794 // A regmask is a def of every clobbered register: reload what lives in one
1795 // below MI. Nothing is reserved, so the uses may still take those registers.
1796 if (HasRegMask) {
1797 assert(!RegMasks.empty() && "expected RegMask");
1798 // MRI bookkeeping.
1799 for (const auto *RM : RegMasks)
1801
1802 for (const LiveReg &LR : LiveVirtRegs) {
1803 MCRegister PhysReg = LR.PhysReg;
1804 if (PhysReg && isClobberedByRegMasks(PhysReg))
1805 displacePhysReg(MI, PhysReg);
1806 }
1807 }
1808
1809 // Apply pre-assigned register uses to state.
1810 if (HasPhysRegUse) {
1811 for (MachineOperand &MO : MI.operands()) {
1812 if (!MO.isReg() || !MO.readsReg())
1813 continue;
1814 Register Reg = MO.getReg();
1815 if (!Reg.isPhysical())
1816 continue;
1817 if (MRI->isReserved(Reg))
1818 continue;
1819 if (!usePhysReg(MI, Reg))
1820 MO.setIsKill(true);
1821 }
1822 }
1823
1824 // Allocate virtreg uses and insert reloads as necessary.
1825 // Implicit MOs can get moved/removed by useVirtReg(), so loop multiple
1826 // times to ensure no operand is missed.
1827 bool HasUndefUse = false;
1828 bool TiedOnly = HasTiedDef;
1829 bool ReArrangedImplicitMOs = true;
1830 while (ReArrangedImplicitMOs) {
1831 ReArrangedImplicitMOs = false;
1832 for (MachineOperand &MO : MI.operands()) {
1833 if (!MO.isReg() || !MO.isUse())
1834 continue;
1835 Register Reg = MO.getReg();
1836 if (!Reg.isVirtual() || !shouldAllocateRegister(Reg) ||
1837 (TiedOnly && !MO.isTied()))
1838 continue;
1839
1840 if (MO.isUndef()) {
1841 HasUndefUse = true;
1842 continue;
1843 }
1844
1845 // Populate MayLiveAcrossBlocks now: these uses are about to be rewritten
1846 // to physregs, so a def block allocated later can no longer see them.
1847 mayLiveIn(Reg);
1848
1849 assert(!MO.isInternalRead() && "Bundles not supported");
1850 assert(MO.readsReg() && "reading use");
1851 ReArrangedImplicitMOs = useVirtReg(MI, MO, Reg);
1852 if (ReArrangedImplicitMOs)
1853 break;
1854 }
1855 // Given %1 = OP %0, %0(tied-def 0), allocate tied %0 first, so that %0
1856 // takes %1's register. In operand order, the untied %0 would take another
1857 // register and the tied use would need a copy.
1858 if (TiedOnly && !ReArrangedImplicitMOs) {
1859 TiedOnly = false;
1860 ReArrangedImplicitMOs = true;
1861 }
1862 }
1863
1864 // Allocate undef operands. This is a separate step because in a situation
1865 // like ` = OP undef %X, %X` both operands need the same register assign
1866 // so we should perform the normal assignment first.
1867 if (HasUndefUse) {
1868 for (MachineOperand &MO : MI.all_uses()) {
1869 Register Reg = MO.getReg();
1870 if (!Reg.isVirtual() || !shouldAllocateRegister(Reg))
1871 continue;
1872
1873 assert(MO.isUndef() && "Should only have undef virtreg uses left");
1874 allocVirtRegUndef(MO);
1875 }
1876 }
1877
1878 // Free early clobbers. Last, because they must not share a register with any
1879 // use.
1880 if (HasEarlyClobber) {
1881 for (MachineOperand &MO : reverse(MI.all_defs())) {
1882 if (!MO.isEarlyClobber())
1883 continue;
1884 assert(!MO.getSubReg() && "should be already handled in def processing");
1885
1886 Register Reg = MO.getReg();
1887 if (!Reg)
1888 continue;
1889 if (Reg.isVirtual()) {
1890 assert(!shouldAllocateRegister(Reg));
1891 continue;
1892 }
1893 assert(Reg.isPhysical() && "should have register assigned");
1894
1895 // We sometimes get odd situations like:
1896 // early-clobber %x0 = INSTRUCTION %x0
1897 // which is semantically questionable as the early-clobber should
1898 // apply before the use. But in practice we consider the use to
1899 // happen before the early clobber now. Don't free the early clobber
1900 // register in this case.
1901 if (MI.readsRegister(Reg, TRI))
1902 continue;
1903
1904 freePhysReg(Reg);
1905 }
1906 }
1907
1908 LLVM_DEBUG(dbgs() << "<< " << MI);
1909 if (MI.isCopy() &&
1910 (MI.getOperand(0).getReg() == MI.getOperand(1).getReg() ||
1911 MI.getOperand(0).isDead()) &&
1912 MI.getNumOperands() == 2) {
1913 LLVM_DEBUG(dbgs() << "Mark unnecessary copy for removal: " << MI);
1914 Coalesced.push_back(&MI);
1915 }
1916}
1917
1918void RegAllocFastImpl::handleDebugValue(MachineInstr &MI) {
1919 // Ignore DBG_VALUEs that aren't based on virtual registers. These are
1920 // mostly constants and frame indices.
1921 assert(MI.isDebugValue() && "not a DBG_VALUE*");
1922 for (const auto &MO : MI.debug_operands()) {
1923 if (!MO.isReg())
1924 continue;
1925 Register Reg = MO.getReg();
1926 if (!Reg.isVirtual())
1927 continue;
1928 if (!shouldAllocateRegister(Reg))
1929 continue;
1930
1931 // Already spilled to a stackslot?
1932 int SS = StackSlotForVirtReg[Reg];
1933 if (SS != -1) {
1934 // Modify DBG_VALUE now that the value is in a spill slot.
1936 LLVM_DEBUG(dbgs() << "Rewrite DBG_VALUE for spilled memory: " << MI);
1937 continue;
1938 }
1939
1940 // See if this virtual register has already been allocated to a physical
1941 // register or spilled to a stack slot.
1942 LiveRegMap::iterator LRI = findLiveVirtReg(Reg);
1944 llvm::make_pointer_range(MI.getDebugOperandsForReg(Reg)));
1945
1946 if (LRI != LiveVirtRegs.end() && LRI->PhysReg) {
1947 // Update every use of Reg within MI.
1948 for (auto &RegMO : DbgOps)
1949 setPhysReg(MI, *RegMO, *LRI);
1950 } else {
1951 DanglingDbgValues[Reg].push_back(&MI);
1952 }
1953
1954 // If Reg hasn't been spilled, put this DBG_VALUE in LiveDbgValueMap so
1955 // that future spills of Reg will have DBG_VALUEs.
1956 LiveDbgValueMap[Reg].append(DbgOps.begin(), DbgOps.end());
1957 }
1958}
1959
1960void RegAllocFastImpl::handleBundle(MachineInstr &MI) {
1961 MachineBasicBlock::instr_iterator BundledMI = MI.getIterator();
1962 ++BundledMI;
1963 while (BundledMI->isBundledWithPred()) {
1964 for (MachineOperand &MO : BundledMI->operands()) {
1965 if (!MO.isReg())
1966 continue;
1967
1968 Register Reg = MO.getReg();
1969 if (!Reg.isVirtual() || !shouldAllocateRegister(Reg))
1970 continue;
1971
1972 auto DI = BundleVirtRegsMap.find(Reg);
1973 assert(DI != BundleVirtRegsMap.end() && "Unassigned virtual register");
1974
1975 setPhysReg(MI, MO, DI->second);
1976 }
1977
1978 ++BundledMI;
1979 }
1980}
1981
1982void RegAllocFastImpl::allocateBasicBlock(MachineBasicBlock &MBB) {
1983 this->MBB = &MBB;
1984 LLVM_DEBUG(dbgs() << "\nAllocating " << MBB);
1985
1986 PosIndexes.unsetInitialized();
1987 RegUnitStates.assign(TRI->getNumRegUnits(), regFree);
1988 assert(LiveVirtRegs.empty() && "Mapping not cleared from last block?");
1989
1990 for (const auto &LiveReg : MBB.liveouts())
1991 setPhysRegState(LiveReg.PhysReg, regPreAssigned);
1992
1993 Coalesced.clear();
1994
1995 // Lowering a tied operand inserts a copy ahead of MI. Its registers are
1996 // already assigned, so visiting it would evict what still lives in the
1997 // source.
1998 for (MachineInstr &MI : make_early_inc_range(reverse(MBB))) {
1999 LLVM_DEBUG(dbgs() << "\n>> " << MI << "Regs:"; dumpState());
2000
2001 // Special handling for debug values. Note that they are not allowed to
2002 // affect codegen of the other instructions in any way.
2003 if (MI.isDebugValue()) {
2004 handleDebugValue(MI);
2005 continue;
2006 }
2007
2008 allocateInstruction(MI);
2009
2010 // An error assignment may give a live and a dead def the same register.
2011 if (HasErrorDef) {
2013 HasErrorDef = false;
2014 }
2015
2016 // Once BUNDLE header is assigned registers, same assignments need to be
2017 // done for bundled MIs.
2018 if (MI.getOpcode() == TargetOpcode::BUNDLE) {
2019 handleBundle(MI);
2020 }
2021 }
2022
2023 LLVM_DEBUG(dbgs() << "Begin Regs:"; dumpState());
2024
2025 // Spill all physical registers holding virtual registers now.
2026 LLVM_DEBUG(dbgs() << "Loading live registers at begin of block.\n");
2027 reloadAtBegin(MBB);
2028
2029 // Erase all the coalesced copies. We are delaying it until now because
2030 // LiveVirtRegs might refer to the instrs.
2031 for (MachineInstr *MI : Coalesced)
2032 MBB.erase(MI);
2033 NumCoalesced += Coalesced.size();
2034
2035 for (auto &UDBGPair : DanglingDbgValues) {
2036 for (MachineInstr *DbgValue : UDBGPair.second) {
2037 assert(DbgValue->isDebugValue() && "expected DBG_VALUE");
2038 // Nothing to do if the vreg was spilled in the meantime.
2039 if (!DbgValue->hasDebugOperandForReg(UDBGPair.first))
2040 continue;
2041 LLVM_DEBUG(dbgs() << "Register did not survive for " << *DbgValue
2042 << '\n');
2043 DbgValue->setDebugValueUndef();
2044 }
2045 }
2046 DanglingDbgValues.clear();
2047
2048 LLVM_DEBUG(MBB.dump());
2049}
2050
2051/// Expand REG_SEQUENCE and INSERT_SUBREG into subregister COPYs: the lowering
2052/// TwoAddressInstructionPass performs when it runs before allocation, plus the
2053/// base-value copy its tie processing provides.
2054void RegAllocFastImpl::expandSubregPseudo(MachineInstr &MI) {
2055 MachineBasicBlock &MBB = *MI.getParent();
2056 const DebugLoc &DL = MI.getDebugLoc();
2057 if (MI.isInsertSubreg()) {
2058 // %d = INSERT_SUBREG %base, %sub, idx -> %d = COPY %base
2059 // %d.idx = COPY %sub
2060 const MachineOperand &BaseMO = MI.getOperand(1);
2061 if (!BaseMO.isUndef())
2062 BuildMI(MBB, MI, DL, TII->get(TargetOpcode::COPY),
2063 MI.getOperand(0).getReg())
2064 .addReg(BaseMO.getReg(), RegState::NoFlags, BaseMO.getSubReg());
2065 unsigned SubIdx = MI.getOperand(3).getImm();
2066 MI.removeOperand(3);
2067 assert(MI.getOperand(0).getSubReg() == 0 && "Unexpected subreg idx");
2068 MI.getOperand(0).setSubReg(SubIdx);
2069 MI.getOperand(0).setIsUndef(MI.getOperand(1).isUndef());
2070 MI.removeOperand(1);
2071 MI.setDesc(TII->get(TargetOpcode::COPY));
2072 return;
2073 }
2074
2075 // %d = REG_SEQUENCE %s1, idx1, ... -> undef %d.idx1 = COPY %s1
2076 // %d.idx2 = COPY %s2 ...
2077 assert(MI.isRegSequence());
2078 Register Dst = MI.getOperand(0).getReg();
2079 // An undef source needs no copy: the read-undef flag on the first copy
2080 // defines the whole register. One is still needed where a use reads that
2081 // lane on its own, which would otherwise read an undefined subregister.
2082 LaneBitmask ReadLanes = LaneBitmask::getNone();
2083 for (const MachineOperand &Use : MRI->use_nodbg_operands(Dst))
2084 if (unsigned UseSubIdx = Use.getSubReg())
2085 ReadLanes |= TRI->getSubRegIndexLaneMask(UseSubIdx);
2086
2087 bool DefEmitted = false;
2088 for (unsigned I = 1, E = MI.getNumOperands(); I + 1 < E; I += 2) {
2089 const MachineOperand &SrcMO = MI.getOperand(I);
2090 unsigned SubIdx = MI.getOperand(I + 1).getImm();
2091 if (SrcMO.isUndef() &&
2092 (ReadLanes & TRI->getSubRegIndexLaneMask(SubIdx)).none())
2093 continue;
2094 BuildMI(MBB, MI, DL, TII->get(TargetOpcode::COPY))
2095 .addReg(Dst, RegState::Define | getUndefRegState(!DefEmitted), SubIdx)
2096 .addReg(SrcMO.getReg(), getUndefRegState(SrcMO.isUndef()),
2097 SrcMO.getSubReg());
2098 DefEmitted = true;
2099 }
2100 // Every source was undef: uses of Dst still need a definition.
2101 if (!DefEmitted) {
2102 MI.setDesc(TII->get(TargetOpcode::IMPLICIT_DEF));
2103 while (MI.getNumOperands() > 1)
2104 MI.removeOperand(MI.getNumOperands() - 1);
2105 return;
2106 }
2107 MI.eraseFromParent();
2108}
2109
2110bool RegAllocFastImpl::runOnMachineFunction(MachineFunction &MF,
2111 RegisterClassInfo &RCI) {
2112 LLVM_DEBUG(dbgs() << "********** FAST REGISTER ALLOCATION **********\n"
2113 << "********** Function: " << MF.getName() << '\n');
2114 MRI = &MF.getRegInfo();
2115 const TargetSubtargetInfo &STI = MF.getSubtarget();
2116 TRI = STI.getRegisterInfo();
2117 TII = STI.getInstrInfo();
2118 MFI = &MF.getFrameInfo();
2119 RegClassInfo = &RCI;
2121 // Keep the shared analysis in step with the set just frozen.
2122 RegClassInfo->updateReservedRegs(MRI->getReservedRegs());
2123 unsigned NumRegUnits = TRI->getNumRegUnits();
2124 InstrGen = 0;
2125 UsedInInstr.assign(NumRegUnits, 0);
2126
2127 // MIR that already went through TwoAddressInstructionPass carries
2128 // TiedOpsRewritten, so partial pipelines (-run-pass, -start-before) follow
2129 // the input they are given.
2130 LowerTiedOps = !MF.getProperties().hasTiedOpsRewritten();
2131 if (LowerTiedOps) {
2132 for (MachineBasicBlock &MBB : MF)
2133 for (MachineInstr &MI : make_early_inc_range(MBB))
2134 if (MI.isRegSequence() || MI.isInsertSubreg())
2135 expandSubregPseudo(MI);
2136 }
2137
2138 // initialize the virtual->physical register map to have a 'null'
2139 // mapping for all virtual registers
2140 unsigned NumVirtRegs = MRI->getNumVirtRegs();
2141 StackSlotForVirtReg.resize(NumVirtRegs);
2142 LiveVirtRegs.setUniverse(NumVirtRegs);
2143 MayLiveAcrossBlocks.clear();
2144 MayLiveAcrossBlocks.resize(NumVirtRegs);
2145
2146 // Loop over all of the basic blocks, eliminating virtual register references
2147 for (MachineBasicBlock &MBB : MF)
2148 allocateBasicBlock(MBB);
2149
2150 if (ClearVirtRegs) {
2151 // All machine operands and other references to virtual registers have been
2152 // replaced. Remove the virtual registers.
2153 MRI->clearVirtRegs();
2154 }
2155
2156 StackSlotForVirtReg.clear();
2157 LiveDbgValueMap.clear();
2158 return true;
2159}
2160
2163 MFPropsModifier _(*this, MF);
2164 RegAllocFastImpl Impl(Opts.Filter, Opts.ClearVRegs);
2165 bool Changed = Impl.runOnMachineFunction(
2167 if (!Changed)
2168 return PreservedAnalyses::all();
2170 PA.preserveSet<CFGAnalyses>();
2171 return PA;
2172}
2173
2175 raw_ostream &OS, function_ref<StringRef(StringRef)> MapClassName2PassName) {
2176 bool PrintFilterName = Opts.FilterName != "all";
2177 bool PrintNoClearVRegs = !Opts.ClearVRegs;
2178 bool PrintSemicolon = PrintFilterName && PrintNoClearVRegs;
2179
2180 OS << "regallocfast";
2181 if (PrintFilterName || PrintNoClearVRegs) {
2182 OS << '<';
2183 if (PrintFilterName)
2184 OS << "filter=" << Opts.FilterName;
2185 if (PrintSemicolon)
2186 OS << ';';
2187 if (PrintNoClearVRegs)
2188 OS << "no-clear-vregs";
2189 OS << '>';
2190 }
2191}
2192
2193FunctionPass *llvm::createFastRegisterAllocator() { return new RegAllocFast(); }
2194
2196 bool ClearVirtRegs) {
2197 return new RegAllocFast(Ftor, ClearVirtRegs);
2198}
#define DBG(...)
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
aarch64 promote const
uint64_t uint64_t
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
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:348
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_DEPENDENCY(depName)
Definition PassSupport.h:42
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
Definition PassSupport.h:44
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
Definition PassSupport.h:39
MachineRegisterInfo & MRI
static Register getTiedUseReg(const MachineInstr &MI, const MachineOperand &DefMO)
The register DefMO's tied use reads, when the two end up in the same register: a subregister index on...
static bool isCoalescable(const MachineInstr &MI)
static const MachineOperand & getTiedOperand(const MachineInstr &MI, const MachineOperand &MO)
The operand MO is tied to.
static bool isLiveThroughDef(const MachineInstr &MI, const MachineOperand &MO)
Early clobber, partial def, or tied to a use that carries a value: the register is occupied while the...
static bool dominates(InstrPosIndexes &PosIndexes, const MachineInstr &A, const MachineInstr &B)
static RegisterRegAlloc fastRegAlloc("fast", "fast register allocator", createFastRegisterAllocator)
static void clearDeadsOfLiveDefs(MachineInstr &MI)
Clear dead flags on defs of any register which also has a live def on MI.
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
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
AnalysisUsage & addRequired()
LLVM_ABI void setPreservesCFG()
This function should be called by the pass, iff they do not:
Definition Pass.cpp:280
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:766
iterator end()
Definition DenseMap.h:686
FunctionPass class - This class is used to implement most global optimizations.
Definition Pass.h:312
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function.
Definition Function.cpp:352
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
iterator_range< use_nodbg_iterator > use_nodbg_operands(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,...
const BitVector & getReservedRegs() const
getReservedRegs - Returns a reference to the frozen set of reserved registers.
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
iterator_range< def_iterator > def_operands(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 updateReservedRegs(const BitVector &ReservedInput)
Update cached register class information using ReservedInput, MRI's current reserved-register set.
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
MCRegister asMCReg() const
Utility to check-convert this value to a MCRegister.
Definition Register.h:107
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
#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
NodeAddr< UseNode * > Use
Definition RDFGraph.h:385
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.
@ Renamable
Register that may be renamed.
LLVM_ABI void updateDbgValueForSpill(MachineInstr &Orig, int FrameIndex, Register Reg)
Update a DBG_VALUE whose value has been spilled to FrameIndex.
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
Definition STLExtras.h:649
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
@ End
Run the machine verifier once, at the end of the pipeline.
Definition CodeGen.h:320
constexpr RegState getUndefRegState(bool B)
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
static constexpr LaneBitmask getNone()
Definition LaneBitmask.h:81