Files
llvm-tms34010/llvm/lib/Target/TMS34010/TMS34010TargetMachine.cpp
T

222 lines
8.0 KiB
C++

//===-- TMS34010TargetMachine.cpp - TMS34010 target machine ---------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include "TMS34010TargetMachine.h"
#include "TMS34010.h"
#include "TargetInfo/TMS34010TargetInfo.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
#include "llvm/CodeGen/TargetPassConfig.h"
#include "llvm/IR/CFG.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/GlobalValue.h"
#include "llvm/IR/Mangler.h"
#include "llvm/IR/Module.h"
#include "llvm/MC/MCContext.h"
#include "llvm/MC/MCSymbol.h"
#include "llvm/MC/TargetRegistry.h"
#include "llvm/Pass.h"
#include "llvm/Support/Compiler.h"
#include "llvm/Target/TargetOptions.h"
#include "llvm/Transforms/Utils/BasicBlockUtils.h"
#include <optional>
using namespace llvm;
// TMS34010 code is bit-addressed. GSPA-compatible assembly uses a leading
// underscore on symbols, while the IR data layout keeps the M0 ELF-style
// mangling so clang and llc agree on the target description.
static const char *const TMS34010DataLayout =
"e-m:e-p:32:16-i8:8-i16:16-i32:16-i64:16-f32:16-f64:16-n8:16:32";
// GSPA 2.00 identifiers accept only alphanumerics and `_`; in particular a
// private IR symbol such as `@.str` becomes `_.str`, which the assembler
// rejects as an invalid opcode/expression. Encode every other character as
// `_HH` so the mapping is deterministic and GSPA-safe. It is not injective:
// `_` is left unchanged, so `@x.y` and `@x_2Ey` both map to `_x_2Ey`.
static void sanitizeGSPASymbolName(SmallVectorImpl<char> &Name) {
bool NeedsSanitizing = false;
for (char C : Name) {
if (!isAlnum(C) && C != '_') {
NeedsSanitizing = true;
break;
}
}
if (!NeedsSanitizing)
return;
SmallString<128> Sanitized;
Sanitized.reserve(Name.size());
for (char C : Name) {
if (isAlnum(C) || C == '_') {
Sanitized.push_back(C);
} else {
unsigned char Byte = static_cast<unsigned char>(C);
Sanitized.push_back('_');
Sanitized.push_back(hexdigit(Byte >> 4));
Sanitized.push_back(hexdigit(Byte & 0xF));
}
}
Name.assign(Sanitized.begin(), Sanitized.end());
}
// Private/local IR symbols are module-scoped, but GSPA links every translation
// unit into one flat symbol table. Two modules that both contain `.str` would
// otherwise emit the same ``__.str`` label and GSPA reports a duplicate
// definition. Append a deterministic token derived from the module identifier
// to every local symbol; public names are left exactly as the IR spells them.
//
// llc gives a file input the file name as the module identifier (or the IR's
// own source_filename) and "<stdin>" for standard input, so the token is
// deterministic for a given input and stable for lit's stdin RUN lines.
static void appendModuleToken(SmallVectorImpl<char> &Name,
const GlobalValue *GV) {
const Module *M = GV->getParent();
StringRef ID = M ? M->getModuleIdentifier() : StringRef();
// FNV-1a, folded to 32 bits. Eight uppercase hex digits stay GSPA-safe and
// are short enough not to stress the 1987 assembler's identifier limits.
uint64_t Hash = 1469598103934665603ULL;
for (unsigned char C : ID) {
Hash ^= C;
Hash *= 1099511628211ULL;
}
unsigned Token = static_cast<unsigned>(Hash ^ (Hash >> 32));
Name.push_back('_');
for (int Shift = 28; Shift >= 0; Shift -= 4)
Name.push_back(hexdigit((Token >> Shift) & 0xF));
}
namespace {
class TMS34010ObjectFile : public TargetLoweringObjectFileELF {
public:
MCSymbol *getTargetSymbol(const GlobalValue *GV,
const TargetMachine &TM) const override {
SmallString<128> Name("_");
getMangler().getNameWithPrefix(Name, GV, /*CannotUsePrivateLabel=*/false);
sanitizeGSPASymbolName(Name);
if (GV->hasLocalLinkage())
appendModuleToken(Name, GV);
return getContext().getOrCreateSymbol(Name);
}
void getNameWithPrefix(SmallVectorImpl<char> &OutName, const GlobalValue *GV,
const TargetMachine &TM) const override {
SmallString<128> Name;
getMangler().getNameWithPrefix(Name, GV, /*CannotUsePrivateLabel=*/false);
OutName.push_back('_');
OutName.append(Name.begin(), Name.end());
sanitizeGSPASymbolName(OutName);
if (GV->hasLocalLinkage())
appendModuleToken(OutName, GV);
}
};
} // end anonymous namespace
static Reloc::Model getEffectiveRelocModel(std::optional<Reloc::Model> RM) {
return RM.value_or(Reloc::Static);
}
namespace {
/// Every register-to-register MOVE writes the status flags. PHI elimination
/// inserts a loop backedge's copy immediately before the terminator; if the
/// terminator is a conditional branch, that copy lands between the CMP and the
/// JA<cc> and the branch tests the copy's flags. Splitting critical edges
/// moves the copy onto the edge. The new blocks are appended at the end of
/// the function so the source block's fallthrough is its false successor,
/// which keeps the original branch polarity (and so its condition code).
class TMS34010SplitCriticalEdges : public FunctionPass {
public:
static char ID;
TMS34010SplitCriticalEdges() : FunctionPass(ID) {}
bool runOnFunction(Function &F) override {
SmallPtrSet<BasicBlock *, 8> Before;
for (BasicBlock &BB : F)
Before.insert(&BB);
if (!SplitAllCriticalEdges(F))
return false;
SmallVector<BasicBlock *, 8> NewBlocks;
for (BasicBlock &BB : F)
if (!Before.count(&BB))
NewBlocks.push_back(&BB);
for (BasicBlock *BB : NewBlocks)
BB->moveAfter(&F.back());
return true;
}
};
char TMS34010SplitCriticalEdges::ID = 0;
class TMS34010PassConfig : public TargetPassConfig {
public:
TMS34010PassConfig(TMS34010TargetMachine &TM, PassManagerBase &PM)
: TargetPassConfig(TM, PM) {}
TMS34010TargetMachine &getTMS34010TargetMachine() const {
return getTM<TMS34010TargetMachine>();
}
bool addInstSelector() override;
void addIRPasses() override {
TargetPassConfig::addIRPasses();
addPass(new TMS34010SplitCriticalEdges());
}
// M1 has no stack. The fast register allocator relies on being able to
// spill and reload values; with four argument registers and a fixed A0
// return register, a `-O0` leaf function can hit its spill path even though
// nothing needs a stack slot. Use the greedy allocator at -O0 as well.
// This is a machine-level choice only: llc still skips the IR pipeline at
// -O0, so late GEPs keep their bit offsets.
void addFastRegAlloc() override { addOptimizedRegAlloc(); }
};
} // end anonymous namespace
bool TMS34010PassConfig::addInstSelector() {
addPass(createTMS34010ISelDag(getTMS34010TargetMachine(), getOptLevel()));
return false;
}
TMS34010TargetMachine::TMS34010TargetMachine(
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, TMS34010DataLayout, TT, CPU, FS, Options,
getEffectiveRelocModel(RM),
getEffectiveCodeModel(CM, CodeModel::Small), OL),
TLOF(std::make_unique<TMS34010ObjectFile>()),
Subtarget(TT, CPU, FS, *this) {
(void)JIT;
initAsmInfo();
}
TargetPassConfig *
TMS34010TargetMachine::createPassConfig(PassManagerBase &PM) {
return new TMS34010PassConfig(*this, PM);
}
extern "C" LLVM_ABI LLVM_EXTERNAL_VISIBILITY void
LLVMInitializeTMS34010Target() {
RegisterTargetMachine<TMS34010TargetMachine> X(getTheTMS34010Target());
PassRegistry &PR = *PassRegistry::getPassRegistry();
initializeTMS34010AsmPrinterPass(PR);
initializeTMS34010DAGToDAGISelLegacyPass(PR);
}