Shih-wei Liao | f8fd82b | 2010-02-10 11:10:31 -0800 | [diff] [blame^] | 1 | //===--- Backend.cpp - Interface to LLVM backend technologies -------------===// |
| 2 | // |
| 3 | // The LLVM Compiler Infrastructure |
| 4 | // |
| 5 | // This file is distributed under the University of Illinois Open Source |
| 6 | // License. See LICENSE.TXT for details. |
| 7 | // |
| 8 | //===----------------------------------------------------------------------===// |
| 9 | |
| 10 | #include "clang/Frontend/ASTConsumers.h" |
| 11 | #include "clang/AST/ASTConsumer.h" |
| 12 | #include "clang/AST/ASTContext.h" |
| 13 | #include "clang/AST/DeclGroup.h" |
| 14 | #include "clang/Basic/TargetInfo.h" |
| 15 | #include "clang/Basic/TargetOptions.h" |
| 16 | #include "clang/CodeGen/CodeGenOptions.h" |
| 17 | #include "clang/CodeGen/ModuleBuilder.h" |
| 18 | #include "clang/Frontend/FrontendDiagnostic.h" |
| 19 | #include "llvm/Module.h" |
| 20 | #include "llvm/PassManager.h" |
| 21 | #include "llvm/ADT/OwningPtr.h" |
| 22 | #include "llvm/Assembly/PrintModulePass.h" |
| 23 | #include "llvm/Analysis/CallGraph.h" |
| 24 | #include "llvm/Analysis/Verifier.h" |
| 25 | #include "llvm/Bitcode/ReaderWriter.h" |
| 26 | #include "llvm/CodeGen/RegAllocRegistry.h" |
| 27 | #include "llvm/CodeGen/SchedulerRegistry.h" |
| 28 | #include "llvm/Support/FormattedStream.h" |
| 29 | #include "llvm/Support/StandardPasses.h" |
| 30 | #include "llvm/Support/Timer.h" |
| 31 | #include "llvm/Target/SubtargetFeature.h" |
| 32 | #include "llvm/Target/TargetData.h" |
| 33 | #include "llvm/Target/TargetMachine.h" |
| 34 | #include "llvm/Target/TargetOptions.h" |
| 35 | #include "llvm/Target/TargetRegistry.h" |
| 36 | using namespace clang; |
| 37 | using namespace llvm; |
| 38 | |
| 39 | namespace { |
| 40 | class BackendConsumer : public ASTConsumer { |
| 41 | Diagnostic &Diags; |
| 42 | BackendAction Action; |
| 43 | const CodeGenOptions &CodeGenOpts; |
| 44 | const LangOptions &LangOpts; |
| 45 | const TargetOptions &TargetOpts; |
| 46 | llvm::raw_ostream *AsmOutStream; |
| 47 | llvm::formatted_raw_ostream FormattedOutStream; |
| 48 | ASTContext *Context; |
| 49 | |
| 50 | Timer LLVMIRGeneration; |
| 51 | Timer CodeGenerationTime; |
| 52 | |
| 53 | llvm::OwningPtr<CodeGenerator> Gen; |
| 54 | |
| 55 | llvm::Module *TheModule; |
| 56 | llvm::TargetData *TheTargetData; |
| 57 | |
| 58 | mutable FunctionPassManager *CodeGenPasses; |
| 59 | mutable PassManager *PerModulePasses; |
| 60 | mutable FunctionPassManager *PerFunctionPasses; |
| 61 | |
| 62 | FunctionPassManager *getCodeGenPasses() const; |
| 63 | PassManager *getPerModulePasses() const; |
| 64 | FunctionPassManager *getPerFunctionPasses() const; |
| 65 | |
| 66 | void CreatePasses(); |
| 67 | |
| 68 | /// AddEmitPasses - Add passes necessary to emit assembly or LLVM IR. |
| 69 | /// |
| 70 | /// \return True on success. |
| 71 | bool AddEmitPasses(); |
| 72 | |
| 73 | void EmitAssembly(); |
| 74 | |
| 75 | public: |
| 76 | BackendConsumer(BackendAction action, Diagnostic &_Diags, |
| 77 | const LangOptions &langopts, const CodeGenOptions &compopts, |
| 78 | const TargetOptions &targetopts, bool TimePasses, |
| 79 | const std::string &infile, llvm::raw_ostream *OS, |
| 80 | LLVMContext& C) : |
| 81 | Diags(_Diags), |
| 82 | Action(action), |
| 83 | CodeGenOpts(compopts), |
| 84 | LangOpts(langopts), |
| 85 | TargetOpts(targetopts), |
| 86 | AsmOutStream(OS), |
| 87 | LLVMIRGeneration("LLVM IR Generation Time"), |
| 88 | CodeGenerationTime("Code Generation Time"), |
| 89 | Gen(CreateLLVMCodeGen(Diags, infile, compopts, C)), |
| 90 | TheModule(0), TheTargetData(0), |
| 91 | CodeGenPasses(0), PerModulePasses(0), PerFunctionPasses(0) { |
| 92 | |
| 93 | if (AsmOutStream) |
| 94 | FormattedOutStream.setStream(*AsmOutStream, |
| 95 | formatted_raw_ostream::PRESERVE_STREAM); |
| 96 | |
| 97 | llvm::TimePassesIsEnabled = TimePasses; |
| 98 | } |
| 99 | |
| 100 | ~BackendConsumer() { |
| 101 | delete TheTargetData; |
| 102 | delete TheModule; |
| 103 | delete CodeGenPasses; |
| 104 | delete PerModulePasses; |
| 105 | delete PerFunctionPasses; |
| 106 | } |
| 107 | |
| 108 | virtual void Initialize(ASTContext &Ctx) { |
| 109 | Context = &Ctx; |
| 110 | |
| 111 | if (llvm::TimePassesIsEnabled) |
| 112 | LLVMIRGeneration.startTimer(); |
| 113 | |
| 114 | Gen->Initialize(Ctx); |
| 115 | |
| 116 | TheModule = Gen->GetModule(); |
| 117 | TheTargetData = new llvm::TargetData(Ctx.Target.getTargetDescription()); |
| 118 | |
| 119 | if (llvm::TimePassesIsEnabled) |
| 120 | LLVMIRGeneration.stopTimer(); |
| 121 | } |
| 122 | |
| 123 | virtual void HandleTopLevelDecl(DeclGroupRef D) { |
| 124 | PrettyStackTraceDecl CrashInfo(*D.begin(), SourceLocation(), |
| 125 | Context->getSourceManager(), |
| 126 | "LLVM IR generation of declaration"); |
| 127 | |
| 128 | if (llvm::TimePassesIsEnabled) |
| 129 | LLVMIRGeneration.startTimer(); |
| 130 | |
| 131 | Gen->HandleTopLevelDecl(D); |
| 132 | |
| 133 | if (llvm::TimePassesIsEnabled) |
| 134 | LLVMIRGeneration.stopTimer(); |
| 135 | } |
| 136 | |
| 137 | virtual void HandleTranslationUnit(ASTContext &C) { |
| 138 | { |
| 139 | PrettyStackTraceString CrashInfo("Per-file LLVM IR generation"); |
| 140 | if (llvm::TimePassesIsEnabled) |
| 141 | LLVMIRGeneration.startTimer(); |
| 142 | |
| 143 | Gen->HandleTranslationUnit(C); |
| 144 | |
| 145 | if (llvm::TimePassesIsEnabled) |
| 146 | LLVMIRGeneration.stopTimer(); |
| 147 | } |
| 148 | |
| 149 | // EmitAssembly times and registers crash info itself. |
| 150 | EmitAssembly(); |
| 151 | |
| 152 | // Force a flush here in case we never get released. |
| 153 | if (AsmOutStream) |
| 154 | FormattedOutStream.flush(); |
| 155 | } |
| 156 | |
| 157 | virtual void HandleTagDeclDefinition(TagDecl *D) { |
| 158 | PrettyStackTraceDecl CrashInfo(D, SourceLocation(), |
| 159 | Context->getSourceManager(), |
| 160 | "LLVM IR generation of declaration"); |
| 161 | Gen->HandleTagDeclDefinition(D); |
| 162 | } |
| 163 | |
| 164 | virtual void CompleteTentativeDefinition(VarDecl *D) { |
| 165 | Gen->CompleteTentativeDefinition(D); |
| 166 | } |
| 167 | }; |
| 168 | } |
| 169 | |
| 170 | FunctionPassManager *BackendConsumer::getCodeGenPasses() const { |
| 171 | if (!CodeGenPasses) { |
| 172 | CodeGenPasses = new FunctionPassManager(TheModule); |
| 173 | CodeGenPasses->add(new TargetData(*TheTargetData)); |
| 174 | } |
| 175 | |
| 176 | return CodeGenPasses; |
| 177 | } |
| 178 | |
| 179 | PassManager *BackendConsumer::getPerModulePasses() const { |
| 180 | if (!PerModulePasses) { |
| 181 | PerModulePasses = new PassManager(); |
| 182 | PerModulePasses->add(new TargetData(*TheTargetData)); |
| 183 | } |
| 184 | |
| 185 | return PerModulePasses; |
| 186 | } |
| 187 | |
| 188 | FunctionPassManager *BackendConsumer::getPerFunctionPasses() const { |
| 189 | if (!PerFunctionPasses) { |
| 190 | PerFunctionPasses = new FunctionPassManager(TheModule); |
| 191 | PerFunctionPasses->add(new TargetData(*TheTargetData)); |
| 192 | } |
| 193 | |
| 194 | return PerFunctionPasses; |
| 195 | } |
| 196 | |
| 197 | bool BackendConsumer::AddEmitPasses() { |
| 198 | if (Action == Backend_EmitNothing) |
| 199 | return true; |
| 200 | |
| 201 | if (Action == Backend_EmitBC) { |
| 202 | getPerModulePasses()->add(createBitcodeWriterPass(FormattedOutStream)); |
| 203 | } else if (Action == Backend_EmitLL) { |
| 204 | getPerModulePasses()->add(createPrintModulePass(&FormattedOutStream)); |
| 205 | } else { |
| 206 | bool Fast = CodeGenOpts.OptimizationLevel == 0; |
| 207 | |
| 208 | // Create the TargetMachine for generating code. |
| 209 | std::string Error; |
| 210 | std::string Triple = TheModule->getTargetTriple(); |
| 211 | const llvm::Target *TheTarget = TargetRegistry::lookupTarget(Triple, Error); |
| 212 | if (!TheTarget) { |
| 213 | Diags.Report(diag::err_fe_unable_to_create_target) << Error; |
| 214 | return false; |
| 215 | } |
| 216 | |
| 217 | // FIXME: Expose these capabilities via actual APIs!!!! Aside from just |
| 218 | // being gross, this is also totally broken if we ever care about |
| 219 | // concurrency. |
| 220 | llvm::NoFramePointerElim = CodeGenOpts.DisableFPElim; |
| 221 | if (CodeGenOpts.FloatABI == "soft") |
| 222 | llvm::FloatABIType = llvm::FloatABI::Soft; |
| 223 | else if (CodeGenOpts.FloatABI == "hard") |
| 224 | llvm::FloatABIType = llvm::FloatABI::Hard; |
| 225 | else { |
| 226 | assert(CodeGenOpts.FloatABI.empty() && "Invalid float abi!"); |
| 227 | llvm::FloatABIType = llvm::FloatABI::Default; |
| 228 | } |
| 229 | NoZerosInBSS = CodeGenOpts.NoZeroInitializedInBSS; |
| 230 | llvm::UseSoftFloat = CodeGenOpts.SoftFloat; |
| 231 | UnwindTablesMandatory = CodeGenOpts.UnwindTables; |
| 232 | |
| 233 | TargetMachine::setAsmVerbosityDefault(CodeGenOpts.AsmVerbose); |
| 234 | |
| 235 | // FIXME: Parse this earlier. |
| 236 | if (CodeGenOpts.RelocationModel == "static") { |
| 237 | TargetMachine::setRelocationModel(llvm::Reloc::Static); |
| 238 | } else if (CodeGenOpts.RelocationModel == "pic") { |
| 239 | TargetMachine::setRelocationModel(llvm::Reloc::PIC_); |
| 240 | } else { |
| 241 | assert(CodeGenOpts.RelocationModel == "dynamic-no-pic" && |
| 242 | "Invalid PIC model!"); |
| 243 | TargetMachine::setRelocationModel(llvm::Reloc::DynamicNoPIC); |
| 244 | } |
| 245 | // FIXME: Parse this earlier. |
| 246 | if (CodeGenOpts.CodeModel == "small") { |
| 247 | TargetMachine::setCodeModel(llvm::CodeModel::Small); |
| 248 | } else if (CodeGenOpts.CodeModel == "kernel") { |
| 249 | TargetMachine::setCodeModel(llvm::CodeModel::Kernel); |
| 250 | } else if (CodeGenOpts.CodeModel == "medium") { |
| 251 | TargetMachine::setCodeModel(llvm::CodeModel::Medium); |
| 252 | } else if (CodeGenOpts.CodeModel == "large") { |
| 253 | TargetMachine::setCodeModel(llvm::CodeModel::Large); |
| 254 | } else { |
| 255 | assert(CodeGenOpts.CodeModel.empty() && "Invalid code model!"); |
| 256 | TargetMachine::setCodeModel(llvm::CodeModel::Default); |
| 257 | } |
| 258 | |
| 259 | std::vector<const char *> BackendArgs; |
| 260 | BackendArgs.push_back("clang"); // Fake program name. |
| 261 | if (!CodeGenOpts.DebugPass.empty()) { |
| 262 | BackendArgs.push_back("-debug-pass"); |
| 263 | BackendArgs.push_back(CodeGenOpts.DebugPass.c_str()); |
| 264 | } |
| 265 | if (!CodeGenOpts.LimitFloatPrecision.empty()) { |
| 266 | BackendArgs.push_back("-limit-float-precision"); |
| 267 | BackendArgs.push_back(CodeGenOpts.LimitFloatPrecision.c_str()); |
| 268 | } |
| 269 | if (llvm::TimePassesIsEnabled) |
| 270 | BackendArgs.push_back("-time-passes"); |
| 271 | BackendArgs.push_back(0); |
| 272 | llvm::cl::ParseCommandLineOptions(BackendArgs.size() - 1, |
| 273 | (char**) &BackendArgs[0]); |
| 274 | |
| 275 | std::string FeaturesStr; |
| 276 | if (TargetOpts.CPU.size() || TargetOpts.Features.size()) { |
| 277 | SubtargetFeatures Features; |
| 278 | Features.setCPU(TargetOpts.CPU); |
| 279 | for (std::vector<std::string>::const_iterator |
| 280 | it = TargetOpts.Features.begin(), |
| 281 | ie = TargetOpts.Features.end(); it != ie; ++it) |
| 282 | Features.AddFeature(*it); |
| 283 | FeaturesStr = Features.getString(); |
| 284 | } |
| 285 | TargetMachine *TM = TheTarget->createTargetMachine(Triple, FeaturesStr); |
| 286 | |
| 287 | // Set register scheduler & allocation policy. |
| 288 | RegisterScheduler::setDefault(createDefaultScheduler); |
| 289 | RegisterRegAlloc::setDefault(Fast ? createLocalRegisterAllocator : |
| 290 | createLinearScanRegisterAllocator); |
| 291 | |
| 292 | // From llvm-gcc: |
| 293 | // If there are passes we have to run on the entire module, we do codegen |
| 294 | // as a separate "pass" after that happens. |
| 295 | // FIXME: This is disabled right now until bugs can be worked out. Reenable |
| 296 | // this for fast -O0 compiles! |
| 297 | FunctionPassManager *PM = getCodeGenPasses(); |
| 298 | CodeGenOpt::Level OptLevel = CodeGenOpt::Default; |
| 299 | |
| 300 | switch (CodeGenOpts.OptimizationLevel) { |
| 301 | default: break; |
| 302 | case 0: OptLevel = CodeGenOpt::None; break; |
| 303 | case 3: OptLevel = CodeGenOpt::Aggressive; break; |
| 304 | } |
| 305 | |
| 306 | // Normal mode, emit a .s or .o file by running the code generator. Note, |
| 307 | // this also adds codegenerator level optimization passes. |
| 308 | TargetMachine::CodeGenFileType CGFT = TargetMachine::CGFT_AssemblyFile; |
| 309 | if (Action == Backend_EmitObj) |
| 310 | CGFT = TargetMachine::CGFT_ObjectFile; |
| 311 | if (TM->addPassesToEmitFile(*PM, FormattedOutStream, CGFT, OptLevel)) { |
| 312 | Diags.Report(diag::err_fe_unable_to_interface_with_target); |
| 313 | return false; |
| 314 | } |
| 315 | } |
| 316 | |
| 317 | return true; |
| 318 | } |
| 319 | |
| 320 | void BackendConsumer::CreatePasses() { |
| 321 | unsigned OptLevel = CodeGenOpts.OptimizationLevel; |
| 322 | CodeGenOptions::InliningMethod Inlining = CodeGenOpts.Inlining; |
| 323 | |
| 324 | // Handle disabling of LLVM optimization, where we want to preserve the |
| 325 | // internal module before any optimization. |
| 326 | if (CodeGenOpts.DisableLLVMOpts) { |
| 327 | OptLevel = 0; |
| 328 | Inlining = CodeGenOpts.NoInlining; |
| 329 | } |
| 330 | |
| 331 | // In -O0 if checking is disabled, we don't even have per-function passes. |
| 332 | if (CodeGenOpts.VerifyModule) |
| 333 | getPerFunctionPasses()->add(createVerifierPass()); |
| 334 | |
| 335 | // Assume that standard function passes aren't run for -O0. |
| 336 | if (OptLevel > 0) |
| 337 | llvm::createStandardFunctionPasses(getPerFunctionPasses(), OptLevel); |
| 338 | |
| 339 | llvm::Pass *InliningPass = 0; |
| 340 | switch (Inlining) { |
| 341 | case CodeGenOptions::NoInlining: break; |
| 342 | case CodeGenOptions::NormalInlining: { |
| 343 | // Set the inline threshold following llvm-gcc. |
| 344 | // |
| 345 | // FIXME: Derive these constants in a principled fashion. |
| 346 | unsigned Threshold = 225; |
| 347 | if (CodeGenOpts.OptimizeSize) |
| 348 | Threshold = 75; |
| 349 | else if (OptLevel > 2) |
| 350 | Threshold = 275; |
| 351 | InliningPass = createFunctionInliningPass(Threshold); |
| 352 | break; |
| 353 | } |
| 354 | case CodeGenOptions::OnlyAlwaysInlining: |
| 355 | InliningPass = createAlwaysInlinerPass(); // Respect always_inline |
| 356 | break; |
| 357 | } |
| 358 | |
| 359 | // For now we always create per module passes. |
| 360 | PassManager *PM = getPerModulePasses(); |
| 361 | llvm::createStandardModulePasses(PM, OptLevel, CodeGenOpts.OptimizeSize, |
| 362 | CodeGenOpts.UnitAtATime, |
| 363 | CodeGenOpts.UnrollLoops, |
| 364 | /*SimplifyLibCalls=*/!LangOpts.NoBuiltin, |
| 365 | /*HaveExceptions=*/true, |
| 366 | InliningPass); |
| 367 | } |
| 368 | |
| 369 | /// EmitAssembly - Handle interaction with LLVM backend to generate |
| 370 | /// actual machine code. |
| 371 | void BackendConsumer::EmitAssembly() { |
| 372 | // Silently ignore if we weren't initialized for some reason. |
| 373 | if (!TheModule || !TheTargetData) |
| 374 | return; |
| 375 | |
| 376 | TimeRegion Region(llvm::TimePassesIsEnabled ? &CodeGenerationTime : 0); |
| 377 | |
| 378 | // Make sure IR generation is happy with the module. This is |
| 379 | // released by the module provider. |
| 380 | Module *M = Gen->ReleaseModule(); |
| 381 | if (!M) { |
| 382 | // The module has been released by IR gen on failures, do not |
| 383 | // double free. |
| 384 | TheModule = 0; |
| 385 | return; |
| 386 | } |
| 387 | |
| 388 | assert(TheModule == M && "Unexpected module change during IR generation"); |
| 389 | |
| 390 | CreatePasses(); |
| 391 | if (!AddEmitPasses()) |
| 392 | return; |
| 393 | |
| 394 | // Run passes. For now we do all passes at once, but eventually we |
| 395 | // would like to have the option of streaming code generation. |
| 396 | |
| 397 | if (PerFunctionPasses) { |
| 398 | PrettyStackTraceString CrashInfo("Per-function optimization"); |
| 399 | |
| 400 | PerFunctionPasses->doInitialization(); |
| 401 | for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I) |
| 402 | if (!I->isDeclaration()) |
| 403 | PerFunctionPasses->run(*I); |
| 404 | PerFunctionPasses->doFinalization(); |
| 405 | } |
| 406 | |
| 407 | if (PerModulePasses) { |
| 408 | PrettyStackTraceString CrashInfo("Per-module optimization passes"); |
| 409 | PerModulePasses->run(*M); |
| 410 | } |
| 411 | |
| 412 | if (CodeGenPasses) { |
| 413 | PrettyStackTraceString CrashInfo("Code generation"); |
| 414 | CodeGenPasses->doInitialization(); |
| 415 | for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I) |
| 416 | if (!I->isDeclaration()) |
| 417 | CodeGenPasses->run(*I); |
| 418 | CodeGenPasses->doFinalization(); |
| 419 | } |
| 420 | } |
| 421 | |
| 422 | ASTConsumer *clang::CreateBackendConsumer(BackendAction Action, |
| 423 | Diagnostic &Diags, |
| 424 | const LangOptions &LangOpts, |
| 425 | const CodeGenOptions &CodeGenOpts, |
| 426 | const TargetOptions &TargetOpts, |
| 427 | bool TimePasses, |
| 428 | const std::string& InFile, |
| 429 | llvm::raw_ostream* OS, |
| 430 | LLVMContext& C) { |
| 431 | return new BackendConsumer(Action, Diags, LangOpts, CodeGenOpts, |
| 432 | TargetOpts, TimePasses, InFile, OS, C); |
| 433 | } |