Skip to content

SelectionDAG 07 scheduling emission

Mugundan edited this page Nov 27, 2026 · 1 revision

Scheduling and MIR Emission

Relevant source files

The following files were used as context for generating this wiki page:

A DAG says what depends on what; it does not say what comes first. Scheduling picks one total order for the machine nodes that respects every data, chain and glue edge, and emission walks that order and creates one `MachineInstr` per node, with virtual registers for values.

Purpose and Scope

This page covers phases 6 and 7 of the pipeline: choosing the scheduler, building the scheduling graph, list scheduling, and InstrEmitter. It is the step where the graph becomes the linear MIR you see in -stop-after dumps.

Choosing the Scheduler

CodeGenAndEmitDAG calls CreateScheduler(), which honours the -pre-RA-sched= option (default: createDefaultScheduler). That function decides in this order:

  1. If the subtarget supplies its own DAG scheduler (getDAGScheduler), use it.
  2. If the optimisation level is -O0, or the subtarget enables the MachineScheduler and lets it be the default (enableMachineScheduler() && enableMachineSchedDefaultSched()), or the target's preference is Sched::Source: use the source-order list scheduler.
  3. Otherwise pick by TLI->getSchedulingPreference(): RegPressure gives the bottom-up register-pressure scheduler, then Hybrid, VLIW, Fast, Linearize, or by default ILP.

On AArch64, AArch64Subtarget::enableMachineScheduler() returns true and the base class returns true for enableMachineSchedDefaultSched(), so rule 2 applies even though the constructor calls setSchedulingPreference(Sched::Hybrid). The DAG scheduler on AArch64 therefore keeps instructions in roughly the original IR order, and the performance scheduling is left to the MachineScheduler that runs later on MIR with real latency and resource models.

Sources: llvm/lib/CodeGen/SelectionDAG/SelectionDAGISel.cpp:301-330, llvm/lib/CodeGen/SelectionDAG/SelectionDAGISel.cpp:1164-1183, llvm/lib/Target/AArch64/AArch64ISelLowering.cpp:1276, llvm/lib/Target/AArch64/AArch64Subtarget.h:160, llvm/include/llvm/CodeGen/TargetSubtargetInfo.h:210-214

Building the Scheduling Graph

flowchart LR
  R["ScheduleDAGSDNodes::Run"] --> S["Schedule"]
  S --> U["BuildSchedUnits<br/>one SUnit per node, glued nodes merged"]
  U --> E["AddSchedEdges<br/>data, order, physreg edges"]
  E --> L["ListScheduleBottomUp<br/>priority queue from the exit node"]
  L --> V["Reverse the sequence"]
  V --> EM["EmitSchedule<br/>InstrEmitter per SUnit"]
Loading
  1. BuildSchedUnits creates an SUnit per node, but nodes joined by glue are merged into one unit, since glue means "emit these back to back". For example, the CopyToReg nodes that place outgoing arguments in registers and the BL that reads them form one unit.
  2. AddSchedEdges adds dependency edges (SDep): data edges for operands, order edges for chains, and physical-register edges where an instruction implicitly defines or uses a register (such as NZCV). Latencies come from the target's itineraries or scheduling model when available.
  3. Each SUnit records a source-order number (SDNodeOrder from the builder), used as the tie-breaker.

Sources: llvm/lib/CodeGen/SelectionDAG/ScheduleDAGSDNodes.cpp:55-65, llvm/lib/CodeGen/SelectionDAG/ScheduleDAGSDNodes.cpp:324-439, llvm/lib/CodeGen/SelectionDAG/ScheduleDAGSDNodes.cpp:441-530

List Scheduling

ScheduleDAGRRList::ListScheduleBottomUp builds the order from the bottom: it starts at the exit unit (the root) and repeatedly picks one available unit (one whose users have all been scheduled) from a priority queue, schedules it, then makes its operands available. The priority function for the source-order variant (src_ls_rr_sort) prefers the node with the higher source order, so the bottom-up walk reproduces the program order. At the end the sequence is reversed (std::reverse(Sequence...)) to get top-down order. The other variants add heuristics for register pressure, ILP, and two-address and physical-register constraints.

Sources: llvm/lib/CodeGen/SelectionDAG/ScheduleDAGRRList.cpp:1580-1621, llvm/lib/CodeGen/SelectionDAG/ScheduleDAGRRList.cpp:1662-1673

Emission: EmitSchedule and InstrEmitter

ScheduleDAGSDNodes::EmitSchedule creates an InstrEmitter positioned in the MachineBasicBlock, then for each SUnit in Sequence emits its node(s) with Emitter.EmitNode. What each node kind becomes:

Node Emitted as
Machine node (ADDWrr, LDRWui, BL, ...) EmitMachineNode: a MachineInstr built from the instruction's descriptor. Defs get a new virtual register whose register class comes from the instruction's operand constraint (gpr32, gpr64, fpr128); uses come from VRBaseMap (a map from (SDNode, result number) to its vreg); constants become immediate operands; MachineMemOperands and IR flags are attached
CopyToReg dst, src A COPY into dst (a physical register such as $w0, or a virtual register for a value that leaves the block). If the source is IMPLICIT_DEF, an IMPLICIT_DEF instruction instead
CopyFromReg src If src is virtual: no instruction; the node's result aliases that vreg in VRBaseMap. If physical: a COPY from it into a fresh vreg
COPY_TO_REGCLASS, EXTRACT_SUBREG, INSERT_SUBREG, SUBREG_TO_REG, REG_SEQUENCE COPY with subregister indices or the right register class (special-cased in EmitSubregNode, EmitRegSequence)
EntryToken, TokenFactor Nothing: they only carried ordering

Two details explain visible features of MIR (as produced by the 23.1.4 llc the examples use):

  • Kill flags. In AddRegisterOperand a use is marked killed when its defining node has a single use, is not a CopyFromReg, and the instruction operand is not tied. That is why %3 is killed in ADDWrr killed %3, %2 below while %0 and %1, which come from CopyFromReg, never are.
  • Register class constraints. For each virtual-register use the emitter calls MRI->constrainRegClass to narrow the class of the vreg to what the instruction accepts, or inserts a COPY into a new vreg if narrowing is impossible. This is why an incoming pointer becomes %0:gpr64common (a class that excludes xzr, which cannot be a base address) in load examples, while an i64 argument that is only added stays gpr64.

Sources: llvm/lib/CodeGen/SelectionDAG/ScheduleDAGSDNodes.cpp:848-1093, llvm/lib/CodeGen/SelectionDAG/InstrEmitter.cpp:88-183, llvm/lib/CodeGen/SelectionDAG/InstrEmitter.cpp:185-263, llvm/lib/CodeGen/SelectionDAG/InstrEmitter.cpp:340-392, llvm/lib/CodeGen/SelectionDAG/InstrEmitter.cpp:503-634, llvm/lib/CodeGen/SelectionDAG/InstrEmitter.cpp:1003-1258, llvm/lib/CodeGen/SelectionDAG/InstrEmitter.cpp:1263-1310

Live-In Copies and finalize-isel

After all blocks of the function have been selected, SelectionDAGISel::runOnMachineFunction calls MachineRegisterInfo::EmitLiveInCopies for the entry block. It inserts one COPY per live-in physical register at the very top, each placed at the block's beginning, which is why they appear in reverse (%2 = COPY $w2, %1 = COPY $w1, %0 = COPY $w0). A later pass, finalize-isel ("Finalize ISel and expand pseudo-instructions"), handles instructions that need a custom inserter and applies post-ISel hooks.

Sources: llvm/lib/CodeGen/SelectionDAG/SelectionDAGISel.cpp:688

Complete Example: (a * b) + c

The DAG from Core Data Structures after selection, scheduling and emission produces exactly this MIR (real output from llc -mtriple=aarch64 -O2 -stop-after=finalize-isel):

bb.0 (%ir-block.0):
  liveins: $w0, $w1, $w2

  %2:gpr32 = COPY $w2                  ; live-in copies, inserted at the top, in reverse
  %1:gpr32 = COPY $w1
  %0:gpr32 = COPY $w0
  %3:gpr32 = MADDWrrr %0, %1, $wzr     ; mul a, b   (a multiply is a MADD with the zero register)
  %4:gpr32 = ADDWrr killed %3, %2      ; add, %3 is single-use so it is killed
  $w0 = COPY %4                        ; CopyToReg $w0
  RET_ReallyLR implicit $w0            ; AArch64ISD::RET_GLUE, glued to the copy

Every MIR instruction maps back to one DAG node: three CopyFromReg (which became no instruction; the COPYs at the top are the live-in copies of the physical registers, and %0..%2 are the vregs they alias), the mul, the add, the CopyToReg, and the glued return.

Start here

Computer Organization & Architecture

Hexagon ISA

Operating Systems

C++ for LLVM Development

LLVM IR

SelectionDAG

Backend Assignments

Target Bring-up

Calling Conventions

Frame Lowering

MC Layer

Register Allocation

Scheduling

Clone this wiki locally