blob: 3c7c1bc0288da1c52271a16d1ac34f3d82ecea30 [file] [log] [blame]
Daniel Dunbard69bacc2008-10-21 23:49:24 +00001//===--- 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 "ASTConsumers.h"
Daniel Dunbard69bacc2008-10-21 23:49:24 +000011#include "clang/AST/ASTContext.h"
12#include "clang/AST/ASTConsumer.h"
13#include "clang/AST/TranslationUnit.h"
14#include "clang/Basic/TargetInfo.h"
15#include "clang/CodeGen/ModuleBuilder.h"
Daniel Dunbar70f92432008-10-23 05:50:47 +000016#include "clang/Driver/CompileOptions.h"
Daniel Dunbard69bacc2008-10-21 23:49:24 +000017#include "llvm/Module.h"
18#include "llvm/ModuleProvider.h"
19#include "llvm/PassManager.h"
20#include "llvm/ADT/OwningPtr.h"
21#include "llvm/Assembly/PrintModulePass.h"
Daniel Dunbar70f92432008-10-23 05:50:47 +000022#include "llvm/Analysis/CallGraph.h"
23#include "llvm/Analysis/Verifier.h"
Daniel Dunbard69bacc2008-10-21 23:49:24 +000024#include "llvm/Bitcode/ReaderWriter.h"
25#include "llvm/CodeGen/RegAllocRegistry.h"
26#include "llvm/CodeGen/SchedulerRegistry.h"
Daniel Dunbard69bacc2008-10-21 23:49:24 +000027#include "llvm/Support/raw_ostream.h"
Daniel Dunbard69bacc2008-10-21 23:49:24 +000028#include "llvm/Support/Compiler.h"
Chris Lattner6f114eb2009-02-18 01:37:30 +000029#include "llvm/Support/Timer.h"
Daniel Dunbard69bacc2008-10-21 23:49:24 +000030#include "llvm/System/Path.h"
31#include "llvm/System/Program.h"
Daniel Dunbara034ba82009-02-17 19:47:34 +000032#include "llvm/Target/SubtargetFeature.h"
Daniel Dunbard69bacc2008-10-21 23:49:24 +000033#include "llvm/Target/TargetData.h"
34#include "llvm/Target/TargetMachine.h"
35#include "llvm/Target/TargetMachineRegistry.h"
Daniel Dunbar70f92432008-10-23 05:50:47 +000036#include "llvm/Transforms/Scalar.h"
37#include "llvm/Transforms/IPO.h"
Daniel Dunbard69bacc2008-10-21 23:49:24 +000038using namespace clang;
39using namespace llvm;
40
41namespace {
42 class VISIBILITY_HIDDEN BackendConsumer : public ASTConsumer {
43 BackendAction Action;
Daniel Dunbar70f92432008-10-23 05:50:47 +000044 CompileOptions CompileOpts;
Daniel Dunbard69bacc2008-10-21 23:49:24 +000045 const std::string &InputFile;
46 std::string OutputFile;
Daniel Dunbar90f41302008-10-29 08:50:02 +000047 bool GenerateDebugInfo;
48
Chris Lattner6f114eb2009-02-18 01:37:30 +000049 Timer LLVMIRGeneration;
50 Timer CodeGenerationTime;
51
Daniel Dunbard69bacc2008-10-21 23:49:24 +000052 llvm::OwningPtr<CodeGenerator> Gen;
53
54 llvm::Module *TheModule;
55 llvm::TargetData *TheTargetData;
56 llvm::raw_ostream *AsmOutStream;
57
Nuno Lopesdd492672008-10-24 22:51:00 +000058 mutable llvm::ModuleProvider *ModuleProvider;
Daniel Dunbard69bacc2008-10-21 23:49:24 +000059 mutable FunctionPassManager *CodeGenPasses;
60 mutable PassManager *PerModulePasses;
61 mutable FunctionPassManager *PerFunctionPasses;
62
63 FunctionPassManager *getCodeGenPasses() const;
64 PassManager *getPerModulePasses() const;
65 FunctionPassManager *getPerFunctionPasses() const;
66
67 void CreatePasses();
68
69 /// AddEmitPasses - Add passes necessary to emit assembly or LLVM
70 /// IR.
71 ///
Daniel Dunbard69bacc2008-10-21 23:49:24 +000072 /// \return True on success. On failure \arg Error will be set to
73 /// a user readable error message.
Daniel Dunbar4c877cc2008-10-23 05:59:43 +000074 bool AddEmitPasses(std::string &Error);
Daniel Dunbard69bacc2008-10-21 23:49:24 +000075
76 void EmitAssembly();
77
78 public:
79 BackendConsumer(BackendAction action, Diagnostic &Diags,
Daniel Dunbara034ba82009-02-17 19:47:34 +000080 const LangOptions &langopts, const CompileOptions &compopts,
Daniel Dunbard69bacc2008-10-21 23:49:24 +000081 const std::string& infile, const std::string& outfile,
Daniel Dunbar90f41302008-10-29 08:50:02 +000082 bool debug) :
Daniel Dunbard69bacc2008-10-21 23:49:24 +000083 Action(action),
Daniel Dunbar70f92432008-10-23 05:50:47 +000084 CompileOpts(compopts),
Daniel Dunbard69bacc2008-10-21 23:49:24 +000085 InputFile(infile),
86 OutputFile(outfile),
Daniel Dunbar90f41302008-10-29 08:50:02 +000087 GenerateDebugInfo(debug),
Chris Lattner6f114eb2009-02-18 01:37:30 +000088 LLVMIRGeneration("LLVM IR Generation Time"),
89 CodeGenerationTime("Code Generation Time"),
Daniel Dunbara034ba82009-02-17 19:47:34 +000090 Gen(CreateLLVMCodeGen(Diags, langopts, InputFile, GenerateDebugInfo)),
Nuno Lopesdd492672008-10-24 22:51:00 +000091 TheModule(0), TheTargetData(0), AsmOutStream(0), ModuleProvider(0),
Chris Lattner44502662009-02-18 01:23:44 +000092 CodeGenPasses(0), PerModulePasses(0), PerFunctionPasses(0) {
93
Chris Lattner6f114eb2009-02-18 01:37:30 +000094 // Enable -time-passes if -ftime-report is enabled.
Chris Lattner44502662009-02-18 01:23:44 +000095 llvm::TimePassesIsEnabled = CompileOpts.TimePasses;
96 }
Daniel Dunbard69bacc2008-10-21 23:49:24 +000097
98 ~BackendConsumer() {
Daniel Dunbard69bacc2008-10-21 23:49:24 +000099 delete AsmOutStream;
100 delete TheTargetData;
Nuno Lopesdd492672008-10-24 22:51:00 +0000101 delete ModuleProvider;
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000102 delete CodeGenPasses;
103 delete PerModulePasses;
104 delete PerFunctionPasses;
105 }
106
107 virtual void InitializeTU(TranslationUnit& TU) {
Chris Lattner6f114eb2009-02-18 01:37:30 +0000108
109 if (CompileOpts.TimePasses)
110 LLVMIRGeneration.startTimer();
111
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000112 Gen->InitializeTU(TU);
113
114 TheModule = Gen->GetModule();
Nuno Lopes7d43a312008-10-24 23:27:18 +0000115 ModuleProvider = new ExistingModuleProvider(TheModule);
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000116 TheTargetData =
117 new llvm::TargetData(TU.getContext().Target.getTargetDescription());
Chris Lattner6f114eb2009-02-18 01:37:30 +0000118
119 if (CompileOpts.TimePasses)
120 LLVMIRGeneration.stopTimer();
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000121 }
122
123 virtual void HandleTopLevelDecl(Decl *D) {
Chris Lattner6f114eb2009-02-18 01:37:30 +0000124 if (CompileOpts.TimePasses)
125 LLVMIRGeneration.startTimer();
126
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000127 Gen->HandleTopLevelDecl(D);
Chris Lattner6f114eb2009-02-18 01:37:30 +0000128
129 if (CompileOpts.TimePasses)
130 LLVMIRGeneration.stopTimer();
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000131 }
132
133 virtual void HandleTranslationUnit(TranslationUnit& TU) {
Chris Lattner6f114eb2009-02-18 01:37:30 +0000134 if (CompileOpts.TimePasses)
135 LLVMIRGeneration.startTimer();
136
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000137 Gen->HandleTranslationUnit(TU);
Daniel Dunbard68ba0e2008-11-11 06:35:39 +0000138
Chris Lattner6f114eb2009-02-18 01:37:30 +0000139 if (CompileOpts.TimePasses)
140 LLVMIRGeneration.stopTimer();
141
142 // EmitAssembly times itself.
143 EmitAssembly();
144
Daniel Dunbard68ba0e2008-11-11 06:35:39 +0000145 // Force a flush here in case we never get released.
146 if (AsmOutStream)
147 AsmOutStream->flush();
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000148 }
149
150 virtual void HandleTagDeclDefinition(TagDecl *D) {
151 Gen->HandleTagDeclDefinition(D);
152 }
153 };
154}
155
156FunctionPassManager *BackendConsumer::getCodeGenPasses() const {
157 if (!CodeGenPasses) {
Nuno Lopesdd492672008-10-24 22:51:00 +0000158 CodeGenPasses = new FunctionPassManager(ModuleProvider);
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000159 CodeGenPasses->add(new TargetData(*TheTargetData));
160 }
161
162 return CodeGenPasses;
163}
164
165PassManager *BackendConsumer::getPerModulePasses() const {
166 if (!PerModulePasses) {
167 PerModulePasses = new PassManager();
168 PerModulePasses->add(new TargetData(*TheTargetData));
169 }
170
171 return PerModulePasses;
172}
173
174FunctionPassManager *BackendConsumer::getPerFunctionPasses() const {
175 if (!PerFunctionPasses) {
Nuno Lopes7d43a312008-10-24 23:27:18 +0000176 PerFunctionPasses = new FunctionPassManager(ModuleProvider);
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000177 PerFunctionPasses->add(new TargetData(*TheTargetData));
178 }
179
180 return PerFunctionPasses;
181}
182
Daniel Dunbar4c877cc2008-10-23 05:59:43 +0000183bool BackendConsumer::AddEmitPasses(std::string &Error) {
Daniel Dunbare8e26002009-02-26 22:39:37 +0000184 if (Action == Backend_EmitNothing)
185 return true;
186
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000187 if (OutputFile == "-" || (InputFile == "-" && OutputFile.empty())) {
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000188 AsmOutStream = new raw_stdout_ostream();
189 sys::Program::ChangeStdoutToBinary();
190 } else {
191 if (OutputFile.empty()) {
192 llvm::sys::Path Path(InputFile);
193 Path.eraseSuffix();
194 if (Action == Backend_EmitBC) {
195 Path.appendSuffix("bc");
196 } else if (Action == Backend_EmitLL) {
197 Path.appendSuffix("ll");
198 } else {
199 Path.appendSuffix("s");
200 }
201 OutputFile = Path.toString();
202 }
203
Daniel Dunbar26fb2722008-11-13 05:09:21 +0000204 AsmOutStream = new raw_fd_ostream(OutputFile.c_str(), true, Error);
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000205 if (!Error.empty())
206 return false;
207 }
208
209 if (Action == Backend_EmitBC) {
Daniel Dunbared2cb282008-10-22 17:40:45 +0000210 getPerModulePasses()->add(createBitcodeWriterPass(*AsmOutStream));
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000211 } else if (Action == Backend_EmitLL) {
Daniel Dunbar11292b02008-10-22 03:28:13 +0000212 getPerModulePasses()->add(createPrintModulePass(AsmOutStream));
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000213 } else {
Daniel Dunbar4c877cc2008-10-23 05:59:43 +0000214 bool Fast = CompileOpts.OptimizationLevel == 0;
215
Daniel Dunbar8b7650e2008-10-22 18:29:51 +0000216 // Create the TargetMachine for generating code.
217 const TargetMachineRegistry::entry *TME =
218 TargetMachineRegistry::getClosestStaticTargetForModule(*TheModule, Error);
219 if (!TME) {
220 Error = std::string("Unable to get target machine: ") + Error;
221 return false;
222 }
Daniel Dunbara034ba82009-02-17 19:47:34 +0000223
224 std::string FeaturesStr;
225 if (CompileOpts.CPU.size() || CompileOpts.Features.size()) {
226 SubtargetFeatures Features;
227 Features.setCPU(CompileOpts.CPU);
228 for (std::vector<std::string>::iterator
229 it = CompileOpts.Features.begin(),
230 ie = CompileOpts.Features.end(); it != ie; ++it)
231 Features.AddFeature(*it);
232 FeaturesStr = Features.getString();
233 }
234 TargetMachine *TM = TME->CtorFn(*TheModule, FeaturesStr);
Daniel Dunbar8b7650e2008-10-22 18:29:51 +0000235
236 // Set register scheduler & allocation policy.
237 RegisterScheduler::setDefault(createDefaultScheduler);
238 RegisterRegAlloc::setDefault(Fast ? createLocalRegisterAllocator :
239 createLinearScanRegisterAllocator);
240
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000241 // From llvm-gcc:
242 // If there are passes we have to run on the entire module, we do codegen
243 // as a separate "pass" after that happens.
244 // FIXME: This is disabled right now until bugs can be worked out. Reenable
245 // this for fast -O0 compiles!
246 FunctionPassManager *PM = getCodeGenPasses();
247
248 // Normal mode, emit a .s file by running the code generator.
249 // Note, this also adds codegenerator level optimization passes.
250 switch (TM->addPassesToEmitFile(*PM, *AsmOutStream,
251 TargetMachine::AssemblyFile, Fast)) {
252 default:
253 case FileModel::Error:
254 Error = "Unable to interface with target machine!\n";
255 return false;
256 case FileModel::AsmFile:
257 break;
258 }
259
260 if (TM->addPassesToEmitFileFinish(*CodeGenPasses, 0, Fast)) {
261 Error = "Unable to interface with target machine!\n";
262 return false;
263 }
264 }
265
266 return true;
267}
268
269void BackendConsumer::CreatePasses() {
Daniel Dunbar70f92432008-10-23 05:50:47 +0000270 // In -O0 if checking is disabled, we don't even have per-function passes.
271 if (CompileOpts.VerifyModule)
272 getPerFunctionPasses()->add(createVerifierPass());
273
274 if (CompileOpts.OptimizationLevel > 0) {
275 FunctionPassManager *PM = getPerFunctionPasses();
276 PM->add(createCFGSimplificationPass());
277 if (CompileOpts.OptimizationLevel == 1)
278 PM->add(createPromoteMemoryToRegisterPass());
279 else
280 PM->add(createScalarReplAggregatesPass());
281 PM->add(createInstructionCombiningPass());
282 }
283
284 // For now we always create per module passes.
285 PassManager *PM = getPerModulePasses();
286 if (CompileOpts.OptimizationLevel > 0) {
287 if (CompileOpts.UnitAtATime)
288 PM->add(createRaiseAllocationsPass()); // call %malloc -> malloc inst
289 PM->add(createCFGSimplificationPass()); // Clean up disgusting code
290 PM->add(createPromoteMemoryToRegisterPass()); // Kill useless allocas
291 if (CompileOpts.UnitAtATime) {
292 PM->add(createGlobalOptimizerPass()); // Optimize out global vars
293 PM->add(createGlobalDCEPass()); // Remove unused fns and globs
294 PM->add(createIPConstantPropagationPass()); // IP Constant Propagation
295 PM->add(createDeadArgEliminationPass()); // Dead argument elimination
296 }
297 PM->add(createInstructionCombiningPass()); // Clean up after IPCP & DAE
298 PM->add(createCFGSimplificationPass()); // Clean up after IPCP & DAE
299 if (CompileOpts.UnitAtATime) {
300 PM->add(createPruneEHPass()); // Remove dead EH info
Bill Wendling5c5a7ee2008-12-31 19:51:31 +0000301 PM->add(createFunctionAttrsPass()); // Set readonly/readnone attrs
Daniel Dunbar70f92432008-10-23 05:50:47 +0000302 }
303 if (CompileOpts.InlineFunctions)
304 PM->add(createFunctionInliningPass()); // Inline small functions
305 else
306 PM->add(createAlwaysInlinerPass()); // Respect always_inline
307 if (CompileOpts.OptimizationLevel > 2)
308 PM->add(createArgumentPromotionPass()); // Scalarize uninlined fn args
309 if (CompileOpts.SimplifyLibCalls)
310 PM->add(createSimplifyLibCallsPass()); // Library Call Optimizations
311 PM->add(createInstructionCombiningPass()); // Cleanup for scalarrepl.
312 PM->add(createJumpThreadingPass()); // Thread jumps.
313 PM->add(createCFGSimplificationPass()); // Merge & remove BBs
314 PM->add(createScalarReplAggregatesPass()); // Break up aggregate allocas
315 PM->add(createInstructionCombiningPass()); // Combine silly seq's
316 PM->add(createCondPropagationPass()); // Propagate conditionals
317 PM->add(createTailCallEliminationPass()); // Eliminate tail calls
318 PM->add(createCFGSimplificationPass()); // Merge & remove BBs
319 PM->add(createReassociatePass()); // Reassociate expressions
320 PM->add(createLoopRotatePass()); // Rotate Loop
321 PM->add(createLICMPass()); // Hoist loop invariants
322 PM->add(createLoopUnswitchPass(CompileOpts.OptimizeSize ? true : false));
Devang Patel59db7602008-11-26 05:01:52 +0000323// PM->add(createLoopIndexSplitPass()); // Split loop index
Daniel Dunbar70f92432008-10-23 05:50:47 +0000324 PM->add(createInstructionCombiningPass());
325 PM->add(createIndVarSimplifyPass()); // Canonicalize indvars
326 PM->add(createLoopDeletionPass()); // Delete dead loops
327 if (CompileOpts.UnrollLoops)
328 PM->add(createLoopUnrollPass()); // Unroll small loops
329 PM->add(createInstructionCombiningPass()); // Clean up after the unroller
330 PM->add(createGVNPass()); // Remove redundancies
331 PM->add(createMemCpyOptPass()); // Remove memcpy / form memset
332 PM->add(createSCCPPass()); // Constant prop with SCCP
333
334 // Run instcombine after redundancy elimination to exploit opportunities
335 // opened up by them.
336 PM->add(createInstructionCombiningPass());
337 PM->add(createCondPropagationPass()); // Propagate conditionals
338 PM->add(createDeadStoreEliminationPass()); // Delete dead stores
339 PM->add(createAggressiveDCEPass()); // Delete dead instructions
340 PM->add(createCFGSimplificationPass()); // Merge & remove BBs
341
342 if (CompileOpts.UnitAtATime) {
343 PM->add(createStripDeadPrototypesPass()); // Get rid of dead prototypes
344 PM->add(createDeadTypeEliminationPass()); // Eliminate dead types
345 }
346
347 if (CompileOpts.OptimizationLevel > 1 && CompileOpts.UnitAtATime)
348 PM->add(createConstantMergePass()); // Merge dup global constants
349 } else {
Daniel Dunbarb087ae92008-11-13 05:29:02 +0000350 PM->add(createAlwaysInlinerPass());
Daniel Dunbar70f92432008-10-23 05:50:47 +0000351 }
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000352}
353
354/// EmitAssembly - Handle interaction with LLVM backend to generate
355/// actual machine code.
356void BackendConsumer::EmitAssembly() {
357 // Silently ignore if we weren't initialized for some reason.
358 if (!TheModule || !TheTargetData)
359 return;
Chris Lattner6f114eb2009-02-18 01:37:30 +0000360
Chris Lattner8b76c0d2009-02-18 18:22:50 +0000361
362
363 TimeRegion Region(CompileOpts.TimePasses ? &CodeGenerationTime : 0);
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000364
Daniel Dunbard611bac2008-10-27 20:40:41 +0000365 // Make sure IR generation is happy with the module. This is
366 // released by the module provider.
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000367 Module *M = Gen->ReleaseModule();
368 if (!M) {
Daniel Dunbard611bac2008-10-27 20:40:41 +0000369 // The module has been released by IR gen on failures, do not
370 // double free.
371 ModuleProvider->releaseModule();
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000372 TheModule = 0;
373 return;
374 }
375
376 assert(TheModule == M && "Unexpected module change during IR generation");
377
378 CreatePasses();
379
380 std::string Error;
Daniel Dunbar4c877cc2008-10-23 05:59:43 +0000381 if (!AddEmitPasses(Error)) {
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000382 // FIXME: Don't fail this way.
383 llvm::cerr << "ERROR: " << Error << "\n";
384 ::exit(1);
385 }
386
387 // Run passes. For now we do all passes at once, but eventually we
388 // would like to have the option of streaming code generation.
389
390 if (PerFunctionPasses) {
391 PerFunctionPasses->doInitialization();
392 for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
393 if (!I->isDeclaration())
394 PerFunctionPasses->run(*I);
395 PerFunctionPasses->doFinalization();
396 }
397
398 if (PerModulePasses)
399 PerModulePasses->run(*M);
400
401 if (CodeGenPasses) {
402 CodeGenPasses->doInitialization();
403 for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
404 if (!I->isDeclaration())
405 CodeGenPasses->run(*I);
406 CodeGenPasses->doFinalization();
407 }
408}
409
410ASTConsumer *clang::CreateBackendConsumer(BackendAction Action,
411 Diagnostic &Diags,
Daniel Dunbara034ba82009-02-17 19:47:34 +0000412 const LangOptions &LangOpts,
Daniel Dunbar70f92432008-10-23 05:50:47 +0000413 const CompileOptions &CompileOpts,
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000414 const std::string& InFile,
415 const std::string& OutFile,
416 bool GenerateDebugInfo) {
Chris Lattner05e7c6d2009-02-12 01:50:58 +0000417 // FIXME: If optimizing, disable all debug info generation. The LLVM
418 // optimizer and backend is not ready to handle it when optimizations
419 // are enabled.
420 if (CompileOpts.OptimizationLevel > 0)
421 GenerateDebugInfo = false;
Daniel Dunbara034ba82009-02-17 19:47:34 +0000422
423 return new BackendConsumer(Action, Diags, LangOpts, CompileOpts,
Daniel Dunbar70f92432008-10-23 05:50:47 +0000424 InFile, OutFile, GenerateDebugInfo);
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000425}