blob: fe26f1170cebc6a8c9d334c0f71ecd88255c8c91 [file] [log] [blame]
Daniel Dunbar85e44e22008-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"
11
12#include "clang/AST/ASTContext.h"
13#include "clang/AST/ASTConsumer.h"
14#include "clang/AST/TranslationUnit.h"
15#include "clang/Basic/TargetInfo.h"
16#include "clang/CodeGen/ModuleBuilder.h"
Daniel Dunbaraa7a0662008-10-23 05:50:47 +000017#include "clang/Driver/CompileOptions.h"
Daniel Dunbar85e44e22008-10-21 23:49:24 +000018#include "llvm/Module.h"
19#include "llvm/ModuleProvider.h"
20#include "llvm/PassManager.h"
21#include "llvm/ADT/OwningPtr.h"
22#include "llvm/Assembly/PrintModulePass.h"
Daniel Dunbaraa7a0662008-10-23 05:50:47 +000023#include "llvm/Analysis/CallGraph.h"
24#include "llvm/Analysis/Verifier.h"
Daniel Dunbar85e44e22008-10-21 23:49:24 +000025#include "llvm/Bitcode/ReaderWriter.h"
26#include "llvm/CodeGen/RegAllocRegistry.h"
27#include "llvm/CodeGen/SchedulerRegistry.h"
28#include "llvm/CodeGen/ScheduleDAG.h"
29#include "llvm/Support/raw_ostream.h"
Daniel Dunbar85e44e22008-10-21 23:49:24 +000030#include "llvm/Support/Compiler.h"
31#include "llvm/System/Path.h"
32#include "llvm/System/Program.h"
33#include "llvm/Target/TargetData.h"
34#include "llvm/Target/TargetMachine.h"
35#include "llvm/Target/TargetMachineRegistry.h"
Daniel Dunbaraa7a0662008-10-23 05:50:47 +000036#include "llvm/Transforms/Scalar.h"
37#include "llvm/Transforms/IPO.h"
Daniel Dunbar85e44e22008-10-21 23:49:24 +000038#include <fstream> // FIXME: Remove
39
40using namespace clang;
41using namespace llvm;
42
43namespace {
44 class VISIBILITY_HIDDEN BackendConsumer : public ASTConsumer {
45 BackendAction Action;
Daniel Dunbaraa7a0662008-10-23 05:50:47 +000046 CompileOptions CompileOpts;
Daniel Dunbar85e44e22008-10-21 23:49:24 +000047 const std::string &InputFile;
48 std::string OutputFile;
49 llvm::OwningPtr<CodeGenerator> Gen;
50
51 llvm::Module *TheModule;
52 llvm::TargetData *TheTargetData;
53 llvm::raw_ostream *AsmOutStream;
54
Nuno Lopes74d92782008-10-24 22:51:00 +000055 mutable llvm::ModuleProvider *ModuleProvider;
Daniel Dunbar85e44e22008-10-21 23:49:24 +000056 mutable FunctionPassManager *CodeGenPasses;
57 mutable PassManager *PerModulePasses;
58 mutable FunctionPassManager *PerFunctionPasses;
59
60 FunctionPassManager *getCodeGenPasses() const;
61 PassManager *getPerModulePasses() const;
62 FunctionPassManager *getPerFunctionPasses() const;
63
64 void CreatePasses();
65
66 /// AddEmitPasses - Add passes necessary to emit assembly or LLVM
67 /// IR.
68 ///
Daniel Dunbar85e44e22008-10-21 23:49:24 +000069 /// \return True on success. On failure \arg Error will be set to
70 /// a user readable error message.
Daniel Dunbar655d5092008-10-23 05:59:43 +000071 bool AddEmitPasses(std::string &Error);
Daniel Dunbar85e44e22008-10-21 23:49:24 +000072
73 void EmitAssembly();
74
75 public:
76 BackendConsumer(BackendAction action, Diagnostic &Diags,
Daniel Dunbaraa7a0662008-10-23 05:50:47 +000077 const LangOptions &Features, const CompileOptions &compopts,
Daniel Dunbar85e44e22008-10-21 23:49:24 +000078 const std::string& infile, const std::string& outfile,
79 bool GenerateDebugInfo) :
80 Action(action),
Daniel Dunbaraa7a0662008-10-23 05:50:47 +000081 CompileOpts(compopts),
Daniel Dunbar85e44e22008-10-21 23:49:24 +000082 InputFile(infile),
83 OutputFile(outfile),
84 Gen(CreateLLVMCodeGen(Diags, Features, InputFile, GenerateDebugInfo)),
Nuno Lopes74d92782008-10-24 22:51:00 +000085 TheModule(0), TheTargetData(0), AsmOutStream(0), ModuleProvider(0),
Daniel Dunbar85e44e22008-10-21 23:49:24 +000086 CodeGenPasses(0), PerModulePasses(0), PerFunctionPasses(0) {}
87
88 ~BackendConsumer() {
89 // FIXME: Move out of destructor.
90 EmitAssembly();
91
92 delete AsmOutStream;
93 delete TheTargetData;
Nuno Lopes74d92782008-10-24 22:51:00 +000094 delete ModuleProvider;
Daniel Dunbar85e44e22008-10-21 23:49:24 +000095 delete CodeGenPasses;
96 delete PerModulePasses;
97 delete PerFunctionPasses;
98 }
99
100 virtual void InitializeTU(TranslationUnit& TU) {
101 Gen->InitializeTU(TU);
102
103 TheModule = Gen->GetModule();
Nuno Lopesd41e2b12008-10-24 23:27:18 +0000104 ModuleProvider = new ExistingModuleProvider(TheModule);
Daniel Dunbar85e44e22008-10-21 23:49:24 +0000105 TheTargetData =
106 new llvm::TargetData(TU.getContext().Target.getTargetDescription());
107 }
108
109 virtual void HandleTopLevelDecl(Decl *D) {
110 Gen->HandleTopLevelDecl(D);
111 }
112
113 virtual void HandleTranslationUnit(TranslationUnit& TU) {
114 Gen->HandleTranslationUnit(TU);
115 }
116
117 virtual void HandleTagDeclDefinition(TagDecl *D) {
118 Gen->HandleTagDeclDefinition(D);
119 }
120 };
121}
122
123FunctionPassManager *BackendConsumer::getCodeGenPasses() const {
124 if (!CodeGenPasses) {
Nuno Lopes74d92782008-10-24 22:51:00 +0000125 CodeGenPasses = new FunctionPassManager(ModuleProvider);
Daniel Dunbar85e44e22008-10-21 23:49:24 +0000126 CodeGenPasses->add(new TargetData(*TheTargetData));
127 }
128
129 return CodeGenPasses;
130}
131
132PassManager *BackendConsumer::getPerModulePasses() const {
133 if (!PerModulePasses) {
134 PerModulePasses = new PassManager();
135 PerModulePasses->add(new TargetData(*TheTargetData));
136 }
137
138 return PerModulePasses;
139}
140
141FunctionPassManager *BackendConsumer::getPerFunctionPasses() const {
142 if (!PerFunctionPasses) {
Nuno Lopesd41e2b12008-10-24 23:27:18 +0000143 PerFunctionPasses = new FunctionPassManager(ModuleProvider);
Daniel Dunbar85e44e22008-10-21 23:49:24 +0000144 PerFunctionPasses->add(new TargetData(*TheTargetData));
145 }
146
147 return PerFunctionPasses;
148}
149
Daniel Dunbar655d5092008-10-23 05:59:43 +0000150bool BackendConsumer::AddEmitPasses(std::string &Error) {
Daniel Dunbar85e44e22008-10-21 23:49:24 +0000151 if (OutputFile == "-" || (InputFile == "-" && OutputFile.empty())) {
Daniel Dunbar85e44e22008-10-21 23:49:24 +0000152 AsmOutStream = new raw_stdout_ostream();
153 sys::Program::ChangeStdoutToBinary();
154 } else {
155 if (OutputFile.empty()) {
156 llvm::sys::Path Path(InputFile);
157 Path.eraseSuffix();
158 if (Action == Backend_EmitBC) {
159 Path.appendSuffix("bc");
160 } else if (Action == Backend_EmitLL) {
161 Path.appendSuffix("ll");
162 } else {
163 Path.appendSuffix("s");
164 }
165 OutputFile = Path.toString();
166 }
167
Daniel Dunbare5dbb072008-10-22 17:40:45 +0000168 // FIXME: Should be binary.
169 AsmOutStream = new raw_fd_ostream(OutputFile.c_str(), Error);
Daniel Dunbar85e44e22008-10-21 23:49:24 +0000170 if (!Error.empty())
171 return false;
172 }
173
174 if (Action == Backend_EmitBC) {
Daniel Dunbare5dbb072008-10-22 17:40:45 +0000175 getPerModulePasses()->add(createBitcodeWriterPass(*AsmOutStream));
Daniel Dunbar85e44e22008-10-21 23:49:24 +0000176 } else if (Action == Backend_EmitLL) {
Daniel Dunbar092a7442008-10-22 03:28:13 +0000177 getPerModulePasses()->add(createPrintModulePass(AsmOutStream));
Daniel Dunbar85e44e22008-10-21 23:49:24 +0000178 } else {
Daniel Dunbar655d5092008-10-23 05:59:43 +0000179 bool Fast = CompileOpts.OptimizationLevel == 0;
180
Daniel Dunbaraed93f22008-10-22 18:29:51 +0000181 // Create the TargetMachine for generating code.
182 const TargetMachineRegistry::entry *TME =
183 TargetMachineRegistry::getClosestStaticTargetForModule(*TheModule, Error);
184 if (!TME) {
185 Error = std::string("Unable to get target machine: ") + Error;
186 return false;
187 }
188
189 // FIXME: Support features?
190 std::string FeatureStr;
191 TargetMachine *TM = TME->CtorFn(*TheModule, FeatureStr);
192
193 // Set register scheduler & allocation policy.
194 RegisterScheduler::setDefault(createDefaultScheduler);
195 RegisterRegAlloc::setDefault(Fast ? createLocalRegisterAllocator :
196 createLinearScanRegisterAllocator);
197
Daniel Dunbar85e44e22008-10-21 23:49:24 +0000198 // From llvm-gcc:
199 // If there are passes we have to run on the entire module, we do codegen
200 // as a separate "pass" after that happens.
201 // FIXME: This is disabled right now until bugs can be worked out. Reenable
202 // this for fast -O0 compiles!
203 FunctionPassManager *PM = getCodeGenPasses();
204
205 // Normal mode, emit a .s file by running the code generator.
206 // Note, this also adds codegenerator level optimization passes.
207 switch (TM->addPassesToEmitFile(*PM, *AsmOutStream,
208 TargetMachine::AssemblyFile, Fast)) {
209 default:
210 case FileModel::Error:
211 Error = "Unable to interface with target machine!\n";
212 return false;
213 case FileModel::AsmFile:
214 break;
215 }
216
217 if (TM->addPassesToEmitFileFinish(*CodeGenPasses, 0, Fast)) {
218 Error = "Unable to interface with target machine!\n";
219 return false;
220 }
221 }
222
223 return true;
224}
225
226void BackendConsumer::CreatePasses() {
Daniel Dunbaraa7a0662008-10-23 05:50:47 +0000227 // In -O0 if checking is disabled, we don't even have per-function passes.
228 if (CompileOpts.VerifyModule)
229 getPerFunctionPasses()->add(createVerifierPass());
230
231 if (CompileOpts.OptimizationLevel > 0) {
232 FunctionPassManager *PM = getPerFunctionPasses();
233 PM->add(createCFGSimplificationPass());
234 if (CompileOpts.OptimizationLevel == 1)
235 PM->add(createPromoteMemoryToRegisterPass());
236 else
237 PM->add(createScalarReplAggregatesPass());
238 PM->add(createInstructionCombiningPass());
239 }
240
241 // For now we always create per module passes.
242 PassManager *PM = getPerModulePasses();
243 if (CompileOpts.OptimizationLevel > 0) {
244 if (CompileOpts.UnitAtATime)
245 PM->add(createRaiseAllocationsPass()); // call %malloc -> malloc inst
246 PM->add(createCFGSimplificationPass()); // Clean up disgusting code
247 PM->add(createPromoteMemoryToRegisterPass()); // Kill useless allocas
248 if (CompileOpts.UnitAtATime) {
249 PM->add(createGlobalOptimizerPass()); // Optimize out global vars
250 PM->add(createGlobalDCEPass()); // Remove unused fns and globs
251 PM->add(createIPConstantPropagationPass()); // IP Constant Propagation
252 PM->add(createDeadArgEliminationPass()); // Dead argument elimination
253 }
254 PM->add(createInstructionCombiningPass()); // Clean up after IPCP & DAE
255 PM->add(createCFGSimplificationPass()); // Clean up after IPCP & DAE
256 if (CompileOpts.UnitAtATime) {
257 PM->add(createPruneEHPass()); // Remove dead EH info
258 PM->add(createAddReadAttrsPass()); // Set readonly/readnone attrs
259 }
260 if (CompileOpts.InlineFunctions)
261 PM->add(createFunctionInliningPass()); // Inline small functions
262 else
263 PM->add(createAlwaysInlinerPass()); // Respect always_inline
264 if (CompileOpts.OptimizationLevel > 2)
265 PM->add(createArgumentPromotionPass()); // Scalarize uninlined fn args
266 if (CompileOpts.SimplifyLibCalls)
267 PM->add(createSimplifyLibCallsPass()); // Library Call Optimizations
268 PM->add(createInstructionCombiningPass()); // Cleanup for scalarrepl.
269 PM->add(createJumpThreadingPass()); // Thread jumps.
270 PM->add(createCFGSimplificationPass()); // Merge & remove BBs
271 PM->add(createScalarReplAggregatesPass()); // Break up aggregate allocas
272 PM->add(createInstructionCombiningPass()); // Combine silly seq's
273 PM->add(createCondPropagationPass()); // Propagate conditionals
274 PM->add(createTailCallEliminationPass()); // Eliminate tail calls
275 PM->add(createCFGSimplificationPass()); // Merge & remove BBs
276 PM->add(createReassociatePass()); // Reassociate expressions
277 PM->add(createLoopRotatePass()); // Rotate Loop
278 PM->add(createLICMPass()); // Hoist loop invariants
279 PM->add(createLoopUnswitchPass(CompileOpts.OptimizeSize ? true : false));
280 PM->add(createLoopIndexSplitPass()); // Split loop index
281 PM->add(createInstructionCombiningPass());
282 PM->add(createIndVarSimplifyPass()); // Canonicalize indvars
283 PM->add(createLoopDeletionPass()); // Delete dead loops
284 if (CompileOpts.UnrollLoops)
285 PM->add(createLoopUnrollPass()); // Unroll small loops
286 PM->add(createInstructionCombiningPass()); // Clean up after the unroller
287 PM->add(createGVNPass()); // Remove redundancies
288 PM->add(createMemCpyOptPass()); // Remove memcpy / form memset
289 PM->add(createSCCPPass()); // Constant prop with SCCP
290
291 // Run instcombine after redundancy elimination to exploit opportunities
292 // opened up by them.
293 PM->add(createInstructionCombiningPass());
294 PM->add(createCondPropagationPass()); // Propagate conditionals
295 PM->add(createDeadStoreEliminationPass()); // Delete dead stores
296 PM->add(createAggressiveDCEPass()); // Delete dead instructions
297 PM->add(createCFGSimplificationPass()); // Merge & remove BBs
298
299 if (CompileOpts.UnitAtATime) {
300 PM->add(createStripDeadPrototypesPass()); // Get rid of dead prototypes
301 PM->add(createDeadTypeEliminationPass()); // Eliminate dead types
302 }
303
304 if (CompileOpts.OptimizationLevel > 1 && CompileOpts.UnitAtATime)
305 PM->add(createConstantMergePass()); // Merge dup global constants
306 } else {
Daniel Dunbar4caf24d2008-10-28 19:23:05 +0000307 PM->add(createAlwaysInlinerPass());
Daniel Dunbaraa7a0662008-10-23 05:50:47 +0000308 }
Daniel Dunbar85e44e22008-10-21 23:49:24 +0000309}
310
311/// EmitAssembly - Handle interaction with LLVM backend to generate
312/// actual machine code.
313void BackendConsumer::EmitAssembly() {
314 // Silently ignore if we weren't initialized for some reason.
315 if (!TheModule || !TheTargetData)
316 return;
317
Daniel Dunbarbc147792008-10-27 20:40:41 +0000318 // Make sure IR generation is happy with the module. This is
319 // released by the module provider.
Daniel Dunbar85e44e22008-10-21 23:49:24 +0000320 Module *M = Gen->ReleaseModule();
321 if (!M) {
Daniel Dunbarbc147792008-10-27 20:40:41 +0000322 // The module has been released by IR gen on failures, do not
323 // double free.
324 ModuleProvider->releaseModule();
Daniel Dunbar85e44e22008-10-21 23:49:24 +0000325 TheModule = 0;
326 return;
327 }
328
329 assert(TheModule == M && "Unexpected module change during IR generation");
330
331 CreatePasses();
332
333 std::string Error;
Daniel Dunbar655d5092008-10-23 05:59:43 +0000334 if (!AddEmitPasses(Error)) {
Daniel Dunbar85e44e22008-10-21 23:49:24 +0000335 // FIXME: Don't fail this way.
336 llvm::cerr << "ERROR: " << Error << "\n";
337 ::exit(1);
338 }
339
340 // Run passes. For now we do all passes at once, but eventually we
341 // would like to have the option of streaming code generation.
342
343 if (PerFunctionPasses) {
344 PerFunctionPasses->doInitialization();
345 for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
346 if (!I->isDeclaration())
347 PerFunctionPasses->run(*I);
348 PerFunctionPasses->doFinalization();
349 }
350
351 if (PerModulePasses)
352 PerModulePasses->run(*M);
353
354 if (CodeGenPasses) {
355 CodeGenPasses->doInitialization();
356 for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
357 if (!I->isDeclaration())
358 CodeGenPasses->run(*I);
359 CodeGenPasses->doFinalization();
360 }
361}
362
363ASTConsumer *clang::CreateBackendConsumer(BackendAction Action,
364 Diagnostic &Diags,
365 const LangOptions &Features,
Daniel Dunbaraa7a0662008-10-23 05:50:47 +0000366 const CompileOptions &CompileOpts,
Daniel Dunbar85e44e22008-10-21 23:49:24 +0000367 const std::string& InFile,
368 const std::string& OutFile,
369 bool GenerateDebugInfo) {
Daniel Dunbaraa7a0662008-10-23 05:50:47 +0000370 return new BackendConsumer(Action, Diags, Features, CompileOpts,
371 InFile, OutFile, GenerateDebugInfo);
Daniel Dunbar85e44e22008-10-21 23:49:24 +0000372}