Skip to content

Bringup 04 targetmachine subtarget

Mugundan edited this page Nov 27, 2026 · 1 revision

TargetMachine and Subtarget

Relevant source files

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

The target machine is created once per compilation. It fixes the data layout, relocation model and code model, creates the pass pipeline, and hands out a subtarget for each function. The subtarget is created per combination of CPU and features; it owns the objects the code generator actually calls: `TargetLowering`, `TargetInstrInfo`, `TargetRegisterInfo` and `TargetFrameLowering`.

Purpose and Scope

The <T>TargetMachine constructor, the data layout string, per-function subtarget lookup, and what the subtarget must own. The pass pipeline hooks are summarized here; the regalloc wiki's pass config hooks page covers the ones around register allocation.

Object Ownership

classDiagram
    class ToyTargetMachine {
      TLOF : TargetLoweringObjectFile
      SubtargetMap
      getSubtargetImpl(Function)
      createPassConfig(PM)
    }
    class ToySubtarget {
      InstrInfo : ToyInstrInfo
      FrameLowering : ToyFrameLowering
      TLInfo : ToyTargetLowering
      feature bits (generated)
    }
    class ToyInstrInfo { RI : ToyRegisterInfo }
    ToyTargetMachine --> ToySubtarget : creates, caches
    ToySubtarget --> ToyInstrInfo
    ToySubtarget --> ToyFrameLowering
    ToySubtarget --> ToyTargetLowering
    ToyInstrInfo --> ToyRegisterInfo
Loading

The Constructor

AArch64TargetMachine::AArch64TargetMachine(const Target &T, const Triple &TT,
                                           StringRef CPU, StringRef FS,
                                           const TargetOptions &Options,
                                           std::optional<Reloc::Model> RM,
                                           std::optional<CodeModel::Model> CM,
                                           CodeGenOptLevel OL, bool JIT,
                                           bool LittleEndian)
    : CodeGenTargetMachineImpl(T, TT.computeDataLayout(), TT,
                               computeDefaultCPU(TT, CPU), FS, Options,
                               getEffectiveRelocModel(TT, RM),
                               getEffectiveAArch64CodeModel(TT, CM, JIT), OL),
      TLOF(createTLOF(getTargetTriple())), isLittle(LittleEndian) {
  initAsmInfo();
  ...
}
Argument / step What a new target supplies
Data layout TT.computeDataLayout() (see below)
Relocation model A helper that picks a default when RM is empty (AArch64: static on ELF, PIC on Darwin/Windows)
Code model A helper that rejects unsupported models and picks a default
TLOF A TargetLoweringObjectFile subclass (usually TargetLoweringObjectFileELF) that chooses sections for globals
initAsmInfo() Must be called in the constructor: it creates MCAsmInfo, MCRegisterInfo, MCInstrInfo, MCSubtargetInfo from the MC registry

The rest of AArch64's constructor sets target options (trap on unreachable for Mach-O, TLS size, GlobalISel at -O0, the machine outliner); a new target can leave these out.

Sources: llvm/lib/Target/AArch64/AArch64TargetMachine.cpp:304-429

The Data Layout String

At this commit the data layout is not written in the target: Triple::computeDataLayout switches on the architecture and calls one function per target in llvm/lib/TargetParser/TargetDataLayout.cpp. For AArch64 ELF:

  std::string Endian = TT.isLittleEndian() ? "e" : "E";
  std::string Ptr32 = TT.getEnvironment() == Triple::GNUILP32 ? "-p:32:32" : "";
  return Endian + "-m:e" + Ptr32 +
         "-p270:32:32-p271:32:32-p272:64:64-i8:8:32-i16:16:32-i64:64-i128:128-"
         "n32:64-S128-Fn32";
Part Meaning
e Little endian
m:e ELF name mangling (private symbols start with .L)
p270:32:32 ... Pointer sizes for special address spaces (pointer size in address space 0 defaults to 64)
i64:64, i128:128 ABI alignment of integer types
i8:8:32 i8 ABI alignment 8 bits, preferred 32
n32:64 Native integer widths
S128 Stack alignment 128 bits
Fn32 Function pointer alignment is independent of function alignment, 32 bits

A new target adds a case Triple::toy: there returning its string. The string must agree with what TargetLowering says is legal, and with the stack alignment given to TargetFrameLowering.

Sources: llvm/lib/TargetParser/TargetDataLayout.cpp:81-97, llvm/lib/TargetParser/TargetDataLayout.cpp:565-575

Per-Function Subtargets

Functions can carry "target-cpu", "tune-cpu" and "target-features" attributes, so the subtarget is looked up per function. AArch64 builds a key from the CPU, features and other options and caches one subtarget per key:

const AArch64Subtarget *
AArch64TargetMachine::getSubtargetImpl(const Function &F) const {
  Attribute CPUAttr = F.getFnAttribute("target-cpu");
  Attribute TuneAttr = F.getFnAttribute("tune-cpu");
  Attribute FSAttr = F.getFnAttribute("target-features");

  StringRef CPU = CPUAttr.isValid() ? CPUAttr.getValueAsString() : TargetCPU;
  StringRef TuneCPU = TuneAttr.isValid() ? TuneAttr.getValueAsString() : CPU;
  StringRef FS = FSAttr.isValid() ? FSAttr.getValueAsString() : TargetFS;
  ...
  auto &I = SubtargetMap[Key];
  if (!I) {
    I = std::make_unique<AArch64Subtarget>(
        TargetTriple, CPU, TuneCPU, FS, *this, isLittle, MinSVEVectorSize,
        ...);
  }
  ...
  return I.get();
}

A simple target can use CPU + FS as the key.

Sources: llvm/lib/Target/AArch64/AArch64TargetMachine.cpp:437-507

The Subtarget

The subtarget class derives from the generated <T>GenSubtargetInfo and holds the per-CPU objects as members. Member order matters: InstrInfo is initialized from initializeSubtargetDependencies, which parses the features first, so that later members (and the instruction info) see the right feature bits.

AArch64Subtarget::AArch64Subtarget(const Triple &TT, StringRef CPU,
                                   StringRef TuneCPU, StringRef FS,
                                   const TargetMachine &TM, bool LittleEndian,
                                   ...)
    : AArch64GenSubtargetInfo(TT, CPU, TuneCPU, FS),
      ...
      TargetTriple(TT),
      InstrInfo(initializeSubtargetDependencies(FS, CPU, TuneCPU, HasMinSize)),
      TLInfo(TM, *this) {
AArch64Subtarget &AArch64Subtarget::initializeSubtargetDependencies(
    StringRef FS, StringRef CPUString, StringRef TuneCPUString,
    bool HasMinSize) {
  if (CPUString.empty())
    CPUString = "generic";
  if (TuneCPUString.empty())
    TuneCPUString = CPUString;
  ParseSubtargetFeatures(CPUString, TuneCPUString, FS);
  initializeProperties(HasMinSize);
  return *this;
}

The members in AArch64Subtarget.h include AArch64FrameLowering FrameLowering;, AArch64InstrInfo InstrInfo; and AArch64TargetLowering TLInfo;. The subtarget overrides the TargetSubtargetInfo getters to return them:

Getter (TargetSubtargetInfo) Default Must override
getInstrInfo() nullptr Yes
getFrameLowering() nullptr Yes
getTargetLowering() nullptr Yes
getRegisterInfo() pure virtual Yes
getSelectionDAGInfo() nullptr Usually (generated SDNodeInfo)
enableMachineScheduler() false Recommended; AArch64 returns true
enablePostRAScheduler() false Optional

AArch64 also creates its GlobalISel objects in the constructor body; a SelectionDAG-only target does not need them.

Sources: llvm/lib/Target/AArch64/AArch64Subtarget.cpp:110-125, llvm/lib/Target/AArch64/AArch64Subtarget.cpp:351-395, llvm/lib/Target/AArch64/AArch64Subtarget.h:101-104, llvm/lib/Target/AArch64/AArch64Subtarget.h:144-161, llvm/include/llvm/CodeGen/TargetSubtargetInfo.h:111-142, llvm/include/llvm/CodeGen/TargetSubtargetInfo.h:225-255

The Pass Config

createPassConfig returns a TargetPassConfig subclass. The only hook a SelectionDAG target must override is addInstSelector, which adds the target's SelectionDAGISel pass:

TargetPassConfig *AArch64TargetMachine::createPassConfig(PassManagerBase &PM) {
  return new AArch64PassConfig(*this, PM);
}
...
bool AArch64PassConfig::addInstSelector() {
  addPass(createAArch64ISelDag(getAArch64TargetMachine(), getOptLevel()));
  ...
  return false;
}

AArch64PassConfig overrides about twenty hooks (addIRPasses, addPreISel, addPreRegAlloc, addPostRegAlloc, addPreSched2, addPreEmitPass, ...) to add its own passes. Its constructor also swaps the old post-RA list scheduler for the post-RA machine scheduler when optimizing: substitutePass(&PostRASchedulerID, &PostMachineSchedulerID) (see the scheduling wiki).

Sources: llvm/lib/Target/AArch64/AArch64TargetMachine.cpp:580-615, llvm/lib/Target/AArch64/AArch64TargetMachine.cpp:640-642, llvm/lib/Target/AArch64/AArch64TargetMachine.cpp:760-770

Minimal Toy Versions (Illustrative)

Illustrative, not LLVM source.

// ToySubtarget.h (illustrative)
class ToySubtarget : public ToyGenSubtargetInfo {
  bool HasMul = false;              // set by ParseSubtargetFeatures
  ToyInstrInfo InstrInfo;
  ToyFrameLowering FrameLowering;
  ToyTargetLowering TLInfo;
  SelectionDAGTargetInfo TSInfo;
public:
  ToySubtarget(const Triple &TT, StringRef CPU, StringRef FS,
               const TargetMachine &TM)
      : ToyGenSubtargetInfo(TT, CPU, CPU, FS),
        InstrInfo(initDeps(CPU, FS)), FrameLowering(),
        TLInfo(TM, *this) {}
  ToySubtarget &initDeps(StringRef CPU, StringRef FS) {
    ParseSubtargetFeatures(CPU.empty() ? "generic" : CPU, CPU, FS);
    return *this;
  }
  void ParseSubtargetFeatures(StringRef CPU, StringRef TuneCPU, StringRef FS);
  const ToyInstrInfo *getInstrInfo() const override { return &InstrInfo; }
  const ToyRegisterInfo *getRegisterInfo() const override {
    return &InstrInfo.getRegisterInfo();
  }
  const ToyFrameLowering *getFrameLowering() const override { return &FrameLowering; }
  const ToyTargetLowering *getTargetLowering() const override { return &TLInfo; }
  const SelectionDAGTargetInfo *getSelectionDAGInfo() const override { return &TSInfo; }
  bool enableMachineScheduler() const override { return true; }
};
// ToyTargetMachine.cpp (illustrative)
ToyTargetMachine::ToyTargetMachine(const Target &T, const Triple &TT,
    StringRef CPU, StringRef FS, const TargetOptions &Options,
    std::optional<Reloc::Model> RM, std::optional<CodeModel::Model> CM,
    CodeGenOptLevel OL, bool JIT)
    : CodeGenTargetMachineImpl(T, TT.computeDataLayout(), TT, CPU, FS, Options,
                               RM.value_or(Reloc::Static),
                               getEffectiveCodeModel(CM, CodeModel::Small), OL),
      TLOF(std::make_unique<TargetLoweringObjectFileELF>()),
      Subtarget(TT, CPU, FS, *this) {
  initAsmInfo();
}

namespace {
class ToyPassConfig : public TargetPassConfig {
public:
  ToyPassConfig(ToyTargetMachine &TM, PassManagerBase &PM)
      : TargetPassConfig(TM, PM) {}
  bool addInstSelector() override {
    addPass(createToyISelDag(getTM<ToyTargetMachine>(), getOptLevel()));
    return false;
  }
};
}
TargetPassConfig *ToyTargetMachine::createPassConfig(PassManagerBase &PM) {
  return new ToyPassConfig(*this, PM);
}

extern "C" LLVM_EXTERNAL_VISIBILITY void LLVMInitializeToyTarget() {
  RegisterTargetMachine<ToyTargetMachine> X(getTheToyTarget());
}

A single subtarget member is enough until the target needs per-function CPUs or features; then switch to a cache like AArch64's SubtargetMap.

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