opnsense-src/lib/Frontend/Backend.cpp

434 lines
15 KiB
C++
Raw Normal View History

2009-06-02 13:58:47 -04:00
//===--- Backend.cpp - Interface to LLVM backend technologies -------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "clang/Frontend/ASTConsumers.h"
#include "clang/AST/ASTConsumer.h"
2009-11-18 09:59:57 -05:00
#include "clang/AST/ASTContext.h"
2009-06-02 13:58:47 -04:00
#include "clang/AST/DeclGroup.h"
#include "clang/Basic/TargetInfo.h"
2009-11-18 09:59:57 -05:00
#include "clang/Basic/TargetOptions.h"
#include "clang/CodeGen/CodeGenOptions.h"
#include "clang/CodeGen/ModuleBuilder.h"
2009-12-15 13:49:47 -05:00
#include "clang/Frontend/FrontendDiagnostic.h"
2009-06-02 13:58:47 -04:00
#include "llvm/Module.h"
#include "llvm/PassManager.h"
#include "llvm/ADT/OwningPtr.h"
#include "llvm/Assembly/PrintModulePass.h"
#include "llvm/Analysis/CallGraph.h"
#include "llvm/Analysis/Verifier.h"
#include "llvm/Bitcode/ReaderWriter.h"
#include "llvm/CodeGen/RegAllocRegistry.h"
#include "llvm/CodeGen/SchedulerRegistry.h"
2009-10-14 14:03:49 -04:00
#include "llvm/Support/FormattedStream.h"
2009-06-03 17:11:25 -04:00
#include "llvm/Support/StandardPasses.h"
2009-06-02 13:58:47 -04:00
#include "llvm/Support/Timer.h"
#include "llvm/Target/SubtargetFeature.h"
#include "llvm/Target/TargetData.h"
#include "llvm/Target/TargetMachine.h"
2009-12-15 13:49:47 -05:00
#include "llvm/Target/TargetOptions.h"
2009-10-14 14:03:49 -04:00
#include "llvm/Target/TargetRegistry.h"
2009-06-02 13:58:47 -04:00
using namespace clang;
using namespace llvm;
namespace {
2009-12-01 06:08:04 -05:00
class BackendConsumer : public ASTConsumer {
2009-12-15 13:49:47 -05:00
Diagnostic &Diags;
2009-06-02 13:58:47 -04:00
BackendAction Action;
2009-12-01 06:08:04 -05:00
const CodeGenOptions &CodeGenOpts;
const LangOptions &LangOpts;
const TargetOptions &TargetOpts;
2009-06-02 13:58:47 -04:00
llvm::raw_ostream *AsmOutStream;
2009-10-14 14:03:49 -04:00
llvm::formatted_raw_ostream FormattedOutStream;
2009-06-02 13:58:47 -04:00
ASTContext *Context;
Timer LLVMIRGeneration;
Timer CodeGenerationTime;
2009-10-14 14:03:49 -04:00
2009-06-02 13:58:47 -04:00
llvm::OwningPtr<CodeGenerator> Gen;
2009-10-14 14:03:49 -04:00
2009-06-02 13:58:47 -04:00
llvm::Module *TheModule;
llvm::TargetData *TheTargetData;
mutable FunctionPassManager *CodeGenPasses;
mutable PassManager *PerModulePasses;
mutable FunctionPassManager *PerFunctionPasses;
FunctionPassManager *getCodeGenPasses() const;
PassManager *getPerModulePasses() const;
FunctionPassManager *getPerFunctionPasses() const;
void CreatePasses();
2009-12-15 13:49:47 -05:00
/// AddEmitPasses - Add passes necessary to emit assembly or LLVM IR.
2009-06-02 13:58:47 -04:00
///
2009-12-15 13:49:47 -05:00
/// \return True on success.
bool AddEmitPasses();
2009-06-02 13:58:47 -04:00
void EmitAssembly();
2009-10-14 14:03:49 -04:00
public:
2009-12-15 13:49:47 -05:00
BackendConsumer(BackendAction action, Diagnostic &_Diags,
2009-11-18 09:59:57 -05:00
const LangOptions &langopts, const CodeGenOptions &compopts,
2009-12-01 06:08:04 -05:00
const TargetOptions &targetopts, bool TimePasses,
const std::string &infile, llvm::raw_ostream *OS,
LLVMContext& C) :
2009-12-15 13:49:47 -05:00
Diags(_Diags),
2009-10-14 14:03:49 -04:00
Action(action),
2009-11-18 09:59:57 -05:00
CodeGenOpts(compopts),
2009-12-01 06:08:04 -05:00
LangOpts(langopts),
2009-11-18 09:59:57 -05:00
TargetOpts(targetopts),
2009-10-14 14:03:49 -04:00
AsmOutStream(OS),
2009-06-02 13:58:47 -04:00
LLVMIRGeneration("LLVM IR Generation Time"),
CodeGenerationTime("Code Generation Time"),
2009-07-04 09:58:54 -04:00
Gen(CreateLLVMCodeGen(Diags, infile, compopts, C)),
2010-02-16 04:31:36 -05:00
TheModule(0), TheTargetData(0),
2009-06-02 13:58:47 -04:00
CodeGenPasses(0), PerModulePasses(0), PerFunctionPasses(0) {
2009-10-14 14:03:49 -04:00
if (AsmOutStream)
FormattedOutStream.setStream(*AsmOutStream,
formatted_raw_ostream::PRESERVE_STREAM);
2009-12-01 06:08:04 -05:00
llvm::TimePassesIsEnabled = TimePasses;
2009-06-02 13:58:47 -04:00
}
~BackendConsumer() {
delete TheTargetData;
2010-02-16 04:31:36 -05:00
delete TheModule;
2009-06-02 13:58:47 -04:00
delete CodeGenPasses;
delete PerModulePasses;
delete PerFunctionPasses;
}
virtual void Initialize(ASTContext &Ctx) {
Context = &Ctx;
2009-10-14 14:03:49 -04:00
2009-12-01 06:08:04 -05:00
if (llvm::TimePassesIsEnabled)
2009-06-02 13:58:47 -04:00
LLVMIRGeneration.startTimer();
2009-10-14 14:03:49 -04:00
2009-06-02 13:58:47 -04:00
Gen->Initialize(Ctx);
TheModule = Gen->GetModule();
TheTargetData = new llvm::TargetData(Ctx.Target.getTargetDescription());
2009-10-14 14:03:49 -04:00
2009-12-01 06:08:04 -05:00
if (llvm::TimePassesIsEnabled)
2009-06-02 13:58:47 -04:00
LLVMIRGeneration.stopTimer();
}
2009-10-14 14:03:49 -04:00
2009-06-02 13:58:47 -04:00
virtual void HandleTopLevelDecl(DeclGroupRef D) {
PrettyStackTraceDecl CrashInfo(*D.begin(), SourceLocation(),
Context->getSourceManager(),
"LLVM IR generation of declaration");
2009-10-14 14:03:49 -04:00
2009-12-01 06:08:04 -05:00
if (llvm::TimePassesIsEnabled)
2009-06-02 13:58:47 -04:00
LLVMIRGeneration.startTimer();
Gen->HandleTopLevelDecl(D);
2009-12-01 06:08:04 -05:00
if (llvm::TimePassesIsEnabled)
2009-06-02 13:58:47 -04:00
LLVMIRGeneration.stopTimer();
}
2009-10-14 14:03:49 -04:00
2009-06-02 13:58:47 -04:00
virtual void HandleTranslationUnit(ASTContext &C) {
{
PrettyStackTraceString CrashInfo("Per-file LLVM IR generation");
2009-12-01 06:08:04 -05:00
if (llvm::TimePassesIsEnabled)
2009-06-02 13:58:47 -04:00
LLVMIRGeneration.startTimer();
Gen->HandleTranslationUnit(C);
2009-12-01 06:08:04 -05:00
if (llvm::TimePassesIsEnabled)
2009-06-02 13:58:47 -04:00
LLVMIRGeneration.stopTimer();
}
// EmitAssembly times and registers crash info itself.
EmitAssembly();
2009-10-14 14:03:49 -04:00
2009-06-02 13:58:47 -04:00
// Force a flush here in case we never get released.
if (AsmOutStream)
2009-10-14 14:03:49 -04:00
FormattedOutStream.flush();
2009-06-02 13:58:47 -04:00
}
2009-10-14 14:03:49 -04:00
2009-06-02 13:58:47 -04:00
virtual void HandleTagDeclDefinition(TagDecl *D) {
PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
Context->getSourceManager(),
"LLVM IR generation of declaration");
Gen->HandleTagDeclDefinition(D);
}
virtual void CompleteTentativeDefinition(VarDecl *D) {
Gen->CompleteTentativeDefinition(D);
}
2009-10-14 14:03:49 -04:00
};
2009-06-02 13:58:47 -04:00
}
FunctionPassManager *BackendConsumer::getCodeGenPasses() const {
if (!CodeGenPasses) {
2010-02-16 04:31:36 -05:00
CodeGenPasses = new FunctionPassManager(TheModule);
2009-06-02 13:58:47 -04:00
CodeGenPasses->add(new TargetData(*TheTargetData));
}
return CodeGenPasses;
}
PassManager *BackendConsumer::getPerModulePasses() const {
if (!PerModulePasses) {
PerModulePasses = new PassManager();
PerModulePasses->add(new TargetData(*TheTargetData));
}
return PerModulePasses;
}
FunctionPassManager *BackendConsumer::getPerFunctionPasses() const {
if (!PerFunctionPasses) {
2010-02-16 04:31:36 -05:00
PerFunctionPasses = new FunctionPassManager(TheModule);
2009-06-02 13:58:47 -04:00
PerFunctionPasses->add(new TargetData(*TheTargetData));
}
return PerFunctionPasses;
}
2009-12-15 13:49:47 -05:00
bool BackendConsumer::AddEmitPasses() {
2009-06-02 13:58:47 -04:00
if (Action == Backend_EmitNothing)
return true;
if (Action == Backend_EmitBC) {
2009-10-14 14:03:49 -04:00
getPerModulePasses()->add(createBitcodeWriterPass(FormattedOutStream));
2009-06-02 13:58:47 -04:00
} else if (Action == Backend_EmitLL) {
2009-10-14 14:03:49 -04:00
getPerModulePasses()->add(createPrintModulePass(&FormattedOutStream));
2009-06-02 13:58:47 -04:00
} else {
2009-11-18 09:59:57 -05:00
bool Fast = CodeGenOpts.OptimizationLevel == 0;
2009-06-02 13:58:47 -04:00
// Create the TargetMachine for generating code.
2009-12-15 13:49:47 -05:00
std::string Error;
2009-10-14 14:03:49 -04:00
std::string Triple = TheModule->getTargetTriple();
const llvm::Target *TheTarget = TargetRegistry::lookupTarget(Triple, Error);
if (!TheTarget) {
2009-12-15 13:49:47 -05:00
Diags.Report(diag::err_fe_unable_to_create_target) << Error;
2009-06-02 13:58:47 -04:00
return false;
}
2009-12-01 06:08:04 -05:00
// FIXME: Expose these capabilities via actual APIs!!!! Aside from just
// being gross, this is also totally broken if we ever care about
// concurrency.
2009-12-15 13:49:47 -05:00
llvm::NoFramePointerElim = CodeGenOpts.DisableFPElim;
if (CodeGenOpts.FloatABI == "soft")
llvm::FloatABIType = llvm::FloatABI::Soft;
else if (CodeGenOpts.FloatABI == "hard")
llvm::FloatABIType = llvm::FloatABI::Hard;
else {
assert(CodeGenOpts.FloatABI.empty() && "Invalid float abi!");
llvm::FloatABIType = llvm::FloatABI::Default;
}
NoZerosInBSS = CodeGenOpts.NoZeroInitializedInBSS;
llvm::UseSoftFloat = CodeGenOpts.SoftFloat;
UnwindTablesMandatory = CodeGenOpts.UnwindTables;
TargetMachine::setAsmVerbosityDefault(CodeGenOpts.AsmVerbose);
// FIXME: Parse this earlier.
if (CodeGenOpts.RelocationModel == "static") {
TargetMachine::setRelocationModel(llvm::Reloc::Static);
} else if (CodeGenOpts.RelocationModel == "pic") {
TargetMachine::setRelocationModel(llvm::Reloc::PIC_);
} else {
assert(CodeGenOpts.RelocationModel == "dynamic-no-pic" &&
"Invalid PIC model!");
TargetMachine::setRelocationModel(llvm::Reloc::DynamicNoPIC);
}
// FIXME: Parse this earlier.
if (CodeGenOpts.CodeModel == "small") {
TargetMachine::setCodeModel(llvm::CodeModel::Small);
} else if (CodeGenOpts.CodeModel == "kernel") {
TargetMachine::setCodeModel(llvm::CodeModel::Kernel);
} else if (CodeGenOpts.CodeModel == "medium") {
TargetMachine::setCodeModel(llvm::CodeModel::Medium);
} else if (CodeGenOpts.CodeModel == "large") {
TargetMachine::setCodeModel(llvm::CodeModel::Large);
} else {
assert(CodeGenOpts.CodeModel.empty() && "Invalid code model!");
TargetMachine::setCodeModel(llvm::CodeModel::Default);
}
2009-12-01 06:08:04 -05:00
std::vector<const char *> BackendArgs;
BackendArgs.push_back("clang"); // Fake program name.
if (!CodeGenOpts.DebugPass.empty()) {
BackendArgs.push_back("-debug-pass");
BackendArgs.push_back(CodeGenOpts.DebugPass.c_str());
}
if (!CodeGenOpts.LimitFloatPrecision.empty()) {
BackendArgs.push_back("-limit-float-precision");
BackendArgs.push_back(CodeGenOpts.LimitFloatPrecision.c_str());
}
if (llvm::TimePassesIsEnabled)
BackendArgs.push_back("-time-passes");
BackendArgs.push_back(0);
llvm::cl::ParseCommandLineOptions(BackendArgs.size() - 1,
(char**) &BackendArgs[0]);
2009-06-02 13:58:47 -04:00
std::string FeaturesStr;
2009-11-18 09:59:57 -05:00
if (TargetOpts.CPU.size() || TargetOpts.Features.size()) {
2009-06-02 13:58:47 -04:00
SubtargetFeatures Features;
2009-11-18 09:59:57 -05:00
Features.setCPU(TargetOpts.CPU);
2009-12-01 06:08:04 -05:00
for (std::vector<std::string>::const_iterator
2009-11-18 09:59:57 -05:00
it = TargetOpts.Features.begin(),
ie = TargetOpts.Features.end(); it != ie; ++it)
2009-06-02 13:58:47 -04:00
Features.AddFeature(*it);
FeaturesStr = Features.getString();
}
2009-10-14 14:03:49 -04:00
TargetMachine *TM = TheTarget->createTargetMachine(Triple, FeaturesStr);
2009-06-02 13:58:47 -04:00
// Set register scheduler & allocation policy.
RegisterScheduler::setDefault(createDefaultScheduler);
2009-10-14 14:03:49 -04:00
RegisterRegAlloc::setDefault(Fast ? createLocalRegisterAllocator :
createLinearScanRegisterAllocator);
2009-06-02 13:58:47 -04:00
// From llvm-gcc:
// If there are passes we have to run on the entire module, we do codegen
// as a separate "pass" after that happens.
// FIXME: This is disabled right now until bugs can be worked out. Reenable
// this for fast -O0 compiles!
FunctionPassManager *PM = getCodeGenPasses();
CodeGenOpt::Level OptLevel = CodeGenOpt::Default;
2009-11-18 09:59:57 -05:00
switch (CodeGenOpts.OptimizationLevel) {
2009-06-02 13:58:47 -04:00
default: break;
case 0: OptLevel = CodeGenOpt::None; break;
case 3: OptLevel = CodeGenOpt::Aggressive; break;
}
2010-02-16 04:31:36 -05:00
// Normal mode, emit a .s or .o file by running the code generator. Note,
// this also adds codegenerator level optimization passes.
TargetMachine::CodeGenFileType CGFT = TargetMachine::CGFT_AssemblyFile;
if (Action == Backend_EmitObj)
CGFT = TargetMachine::CGFT_ObjectFile;
if (TM->addPassesToEmitFile(*PM, FormattedOutStream, CGFT, OptLevel)) {
2009-12-15 13:49:47 -05:00
Diags.Report(diag::err_fe_unable_to_interface_with_target);
2009-06-02 13:58:47 -04:00
return false;
}
}
return true;
}
void BackendConsumer::CreatePasses() {
2009-11-18 09:59:57 -05:00
unsigned OptLevel = CodeGenOpts.OptimizationLevel;
CodeGenOptions::InliningMethod Inlining = CodeGenOpts.Inlining;
// Handle disabling of LLVM optimization, where we want to preserve the
// internal module before any optimization.
if (CodeGenOpts.DisableLLVMOpts) {
OptLevel = 0;
Inlining = CodeGenOpts.NoInlining;
}
2009-06-02 13:58:47 -04:00
// In -O0 if checking is disabled, we don't even have per-function passes.
2009-11-18 09:59:57 -05:00
if (CodeGenOpts.VerifyModule)
2009-06-02 13:58:47 -04:00
getPerFunctionPasses()->add(createVerifierPass());
2009-06-03 17:11:25 -04:00
// Assume that standard function passes aren't run for -O0.
2009-11-18 09:59:57 -05:00
if (OptLevel > 0)
llvm::createStandardFunctionPasses(getPerFunctionPasses(), OptLevel);
2009-06-03 17:11:25 -04:00
llvm::Pass *InliningPass = 0;
2009-11-18 09:59:57 -05:00
switch (Inlining) {
case CodeGenOptions::NoInlining: break;
case CodeGenOptions::NormalInlining: {
2009-12-15 13:49:47 -05:00
// Set the inline threshold following llvm-gcc.
//
// FIXME: Derive these constants in a principled fashion.
2010-02-16 04:31:36 -05:00
unsigned Threshold = 225;
2009-12-15 13:49:47 -05:00
if (CodeGenOpts.OptimizeSize)
2010-02-16 04:31:36 -05:00
Threshold = 75;
2009-12-15 13:49:47 -05:00
else if (OptLevel > 2)
2010-02-16 04:31:36 -05:00
Threshold = 275;
2009-06-14 05:24:02 -04:00
InliningPass = createFunctionInliningPass(Threshold);
2009-06-03 17:11:25 -04:00
break;
2009-06-14 05:24:02 -04:00
}
2009-11-18 09:59:57 -05:00
case CodeGenOptions::OnlyAlwaysInlining:
2009-06-03 17:11:25 -04:00
InliningPass = createAlwaysInlinerPass(); // Respect always_inline
break;
2009-06-02 13:58:47 -04:00
}
// For now we always create per module passes.
PassManager *PM = getPerModulePasses();
2009-11-18 09:59:57 -05:00
llvm::createStandardModulePasses(PM, OptLevel, CodeGenOpts.OptimizeSize,
CodeGenOpts.UnitAtATime,
CodeGenOpts.UnrollLoops,
2009-12-01 06:08:04 -05:00
/*SimplifyLibCalls=*/!LangOpts.NoBuiltin,
2009-06-03 17:11:25 -04:00
/*HaveExceptions=*/true,
InliningPass);
2009-06-02 13:58:47 -04:00
}
/// EmitAssembly - Handle interaction with LLVM backend to generate
2009-10-14 14:03:49 -04:00
/// actual machine code.
2009-06-02 13:58:47 -04:00
void BackendConsumer::EmitAssembly() {
// Silently ignore if we weren't initialized for some reason.
if (!TheModule || !TheTargetData)
return;
2009-10-14 14:03:49 -04:00
2009-12-01 06:08:04 -05:00
TimeRegion Region(llvm::TimePassesIsEnabled ? &CodeGenerationTime : 0);
2009-06-02 13:58:47 -04:00
// Make sure IR generation is happy with the module. This is
// released by the module provider.
Module *M = Gen->ReleaseModule();
if (!M) {
// The module has been released by IR gen on failures, do not
// double free.
TheModule = 0;
return;
}
assert(TheModule == M && "Unexpected module change during IR generation");
CreatePasses();
2009-12-15 13:49:47 -05:00
if (!AddEmitPasses())
return;
2009-06-02 13:58:47 -04:00
// Run passes. For now we do all passes at once, but eventually we
// would like to have the option of streaming code generation.
if (PerFunctionPasses) {
PrettyStackTraceString CrashInfo("Per-function optimization");
2009-10-14 14:03:49 -04:00
2009-06-02 13:58:47 -04:00
PerFunctionPasses->doInitialization();
for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
if (!I->isDeclaration())
PerFunctionPasses->run(*I);
PerFunctionPasses->doFinalization();
}
2009-10-14 14:03:49 -04:00
2009-06-02 13:58:47 -04:00
if (PerModulePasses) {
PrettyStackTraceString CrashInfo("Per-module optimization passes");
PerModulePasses->run(*M);
}
2009-10-14 14:03:49 -04:00
2009-06-02 13:58:47 -04:00
if (CodeGenPasses) {
PrettyStackTraceString CrashInfo("Code generation");
CodeGenPasses->doInitialization();
for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
if (!I->isDeclaration())
CodeGenPasses->run(*I);
CodeGenPasses->doFinalization();
}
}
ASTConsumer *clang::CreateBackendConsumer(BackendAction Action,
Diagnostic &Diags,
const LangOptions &LangOpts,
2009-11-18 09:59:57 -05:00
const CodeGenOptions &CodeGenOpts,
const TargetOptions &TargetOpts,
2009-12-01 06:08:04 -05:00
bool TimePasses,
2009-06-02 13:58:47 -04:00
const std::string& InFile,
2009-07-04 09:58:54 -04:00
llvm::raw_ostream* OS,
LLVMContext& C) {
2009-11-18 09:59:57 -05:00
return new BackendConsumer(Action, Diags, LangOpts, CodeGenOpts,
2009-12-01 06:08:04 -05:00
TargetOpts, TimePasses, InFile, OS, C);
2009-06-02 13:58:47 -04:00
}