blob: 6eaffe9d9aecd0161f50e16a1d4187c05cc1d853 [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"
Daniel Dunbar85e44e22008-10-21 23:49:24 +000028#include "llvm/Support/raw_ostream.h"
Daniel Dunbar85e44e22008-10-21 23:49:24 +000029#include "llvm/Support/Compiler.h"
30#include "llvm/System/Path.h"
31#include "llvm/System/Program.h"
Daniel Dunbar9101a632009-02-17 19:47:34 +000032#include "llvm/Target/SubtargetFeature.h"
Daniel Dunbar85e44e22008-10-21 23:49:24 +000033#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
39using namespace clang;
40using namespace llvm;
41
42namespace {
43 class VISIBILITY_HIDDEN BackendConsumer : public ASTConsumer {
44 BackendAction Action;
Daniel Dunbaraa7a0662008-10-23 05:50:47 +000045 CompileOptions CompileOpts;
Daniel Dunbar85e44e22008-10-21 23:49:24 +000046 const std::string &InputFile;
47 std::string OutputFile;
Daniel Dunbar1a27a192008-10-29 08:50:02 +000048 bool GenerateDebugInfo;
49
Daniel Dunbar85e44e22008-10-21 23:49:24 +000050 llvm::OwningPtr<CodeGenerator> Gen;
51
52 llvm::Module *TheModule;
53 llvm::TargetData *TheTargetData;
54 llvm::raw_ostream *AsmOutStream;
55
Nuno Lopes74d92782008-10-24 22:51:00 +000056 mutable llvm::ModuleProvider *ModuleProvider;
Daniel Dunbar85e44e22008-10-21 23:49:24 +000057 mutable FunctionPassManager *CodeGenPasses;
58 mutable PassManager *PerModulePasses;
59 mutable FunctionPassManager *PerFunctionPasses;
60
61 FunctionPassManager *getCodeGenPasses() const;
62 PassManager *getPerModulePasses() const;
63 FunctionPassManager *getPerFunctionPasses() const;
64
65 void CreatePasses();
66
67 /// AddEmitPasses - Add passes necessary to emit assembly or LLVM
68 /// IR.
69 ///
Daniel Dunbar85e44e22008-10-21 23:49:24 +000070 /// \return True on success. On failure \arg Error will be set to
71 /// a user readable error message.
Daniel Dunbar655d5092008-10-23 05:59:43 +000072 bool AddEmitPasses(std::string &Error);
Daniel Dunbar85e44e22008-10-21 23:49:24 +000073
74 void EmitAssembly();
75
76 public:
77 BackendConsumer(BackendAction action, Diagnostic &Diags,
Daniel Dunbar9101a632009-02-17 19:47:34 +000078 const LangOptions &langopts, const CompileOptions &compopts,
Daniel Dunbar85e44e22008-10-21 23:49:24 +000079 const std::string& infile, const std::string& outfile,
Daniel Dunbar1a27a192008-10-29 08:50:02 +000080 bool debug) :
Daniel Dunbar85e44e22008-10-21 23:49:24 +000081 Action(action),
Daniel Dunbaraa7a0662008-10-23 05:50:47 +000082 CompileOpts(compopts),
Daniel Dunbar85e44e22008-10-21 23:49:24 +000083 InputFile(infile),
84 OutputFile(outfile),
Daniel Dunbar1a27a192008-10-29 08:50:02 +000085 GenerateDebugInfo(debug),
Daniel Dunbar9101a632009-02-17 19:47:34 +000086 Gen(CreateLLVMCodeGen(Diags, langopts, InputFile, GenerateDebugInfo)),
Nuno Lopes74d92782008-10-24 22:51:00 +000087 TheModule(0), TheTargetData(0), AsmOutStream(0), ModuleProvider(0),
Daniel Dunbar85e44e22008-10-21 23:49:24 +000088 CodeGenPasses(0), PerModulePasses(0), PerFunctionPasses(0) {}
89
90 ~BackendConsumer() {
Daniel Dunbar85e44e22008-10-21 23:49:24 +000091 delete AsmOutStream;
92 delete TheTargetData;
Nuno Lopes74d92782008-10-24 22:51:00 +000093 delete ModuleProvider;
Daniel Dunbar85e44e22008-10-21 23:49:24 +000094 delete CodeGenPasses;
95 delete PerModulePasses;
96 delete PerFunctionPasses;
97 }
98
99 virtual void InitializeTU(TranslationUnit& TU) {
100 Gen->InitializeTU(TU);
101
102 TheModule = Gen->GetModule();
Nuno Lopesd41e2b12008-10-24 23:27:18 +0000103 ModuleProvider = new ExistingModuleProvider(TheModule);
Daniel Dunbar85e44e22008-10-21 23:49:24 +0000104 TheTargetData =
105 new llvm::TargetData(TU.getContext().Target.getTargetDescription());
106 }
107
108 virtual void HandleTopLevelDecl(Decl *D) {
109 Gen->HandleTopLevelDecl(D);
110 }
111
112 virtual void HandleTranslationUnit(TranslationUnit& TU) {
113 Gen->HandleTranslationUnit(TU);
Daniel Dunbar622d6d02008-11-11 06:35:39 +0000114
115 EmitAssembly();
116 // Force a flush here in case we never get released.
117 if (AsmOutStream)
118 AsmOutStream->flush();
Daniel Dunbar85e44e22008-10-21 23:49:24 +0000119 }
120
121 virtual void HandleTagDeclDefinition(TagDecl *D) {
122 Gen->HandleTagDeclDefinition(D);
123 }
124 };
125}
126
127FunctionPassManager *BackendConsumer::getCodeGenPasses() const {
128 if (!CodeGenPasses) {
Nuno Lopes74d92782008-10-24 22:51:00 +0000129 CodeGenPasses = new FunctionPassManager(ModuleProvider);
Daniel Dunbar85e44e22008-10-21 23:49:24 +0000130 CodeGenPasses->add(new TargetData(*TheTargetData));
131 }
132
133 return CodeGenPasses;
134}
135
136PassManager *BackendConsumer::getPerModulePasses() const {
137 if (!PerModulePasses) {
138 PerModulePasses = new PassManager();
139 PerModulePasses->add(new TargetData(*TheTargetData));
140 }
141
142 return PerModulePasses;
143}
144
145FunctionPassManager *BackendConsumer::getPerFunctionPasses() const {
146 if (!PerFunctionPasses) {
Nuno Lopesd41e2b12008-10-24 23:27:18 +0000147 PerFunctionPasses = new FunctionPassManager(ModuleProvider);
Daniel Dunbar85e44e22008-10-21 23:49:24 +0000148 PerFunctionPasses->add(new TargetData(*TheTargetData));
149 }
150
151 return PerFunctionPasses;
152}
153
Daniel Dunbar655d5092008-10-23 05:59:43 +0000154bool BackendConsumer::AddEmitPasses(std::string &Error) {
Daniel Dunbar85e44e22008-10-21 23:49:24 +0000155 if (OutputFile == "-" || (InputFile == "-" && OutputFile.empty())) {
Daniel Dunbar85e44e22008-10-21 23:49:24 +0000156 AsmOutStream = new raw_stdout_ostream();
157 sys::Program::ChangeStdoutToBinary();
158 } else {
159 if (OutputFile.empty()) {
160 llvm::sys::Path Path(InputFile);
161 Path.eraseSuffix();
162 if (Action == Backend_EmitBC) {
163 Path.appendSuffix("bc");
164 } else if (Action == Backend_EmitLL) {
165 Path.appendSuffix("ll");
166 } else {
167 Path.appendSuffix("s");
168 }
169 OutputFile = Path.toString();
170 }
171
Daniel Dunbar8fc9ba62008-11-13 05:09:21 +0000172 AsmOutStream = new raw_fd_ostream(OutputFile.c_str(), true, Error);
Daniel Dunbar85e44e22008-10-21 23:49:24 +0000173 if (!Error.empty())
174 return false;
175 }
176
177 if (Action == Backend_EmitBC) {
Daniel Dunbare5dbb072008-10-22 17:40:45 +0000178 getPerModulePasses()->add(createBitcodeWriterPass(*AsmOutStream));
Daniel Dunbar85e44e22008-10-21 23:49:24 +0000179 } else if (Action == Backend_EmitLL) {
Daniel Dunbar092a7442008-10-22 03:28:13 +0000180 getPerModulePasses()->add(createPrintModulePass(AsmOutStream));
Daniel Dunbar85e44e22008-10-21 23:49:24 +0000181 } else {
Daniel Dunbar655d5092008-10-23 05:59:43 +0000182 bool Fast = CompileOpts.OptimizationLevel == 0;
183
Daniel Dunbaraed93f22008-10-22 18:29:51 +0000184 // Create the TargetMachine for generating code.
185 const TargetMachineRegistry::entry *TME =
186 TargetMachineRegistry::getClosestStaticTargetForModule(*TheModule, Error);
187 if (!TME) {
188 Error = std::string("Unable to get target machine: ") + Error;
189 return false;
190 }
Daniel Dunbar9101a632009-02-17 19:47:34 +0000191
192 std::string FeaturesStr;
193 if (CompileOpts.CPU.size() || CompileOpts.Features.size()) {
194 SubtargetFeatures Features;
195 Features.setCPU(CompileOpts.CPU);
196 for (std::vector<std::string>::iterator
197 it = CompileOpts.Features.begin(),
198 ie = CompileOpts.Features.end(); it != ie; ++it)
199 Features.AddFeature(*it);
200 FeaturesStr = Features.getString();
201 }
202 TargetMachine *TM = TME->CtorFn(*TheModule, FeaturesStr);
Daniel Dunbaraed93f22008-10-22 18:29:51 +0000203
204 // Set register scheduler & allocation policy.
205 RegisterScheduler::setDefault(createDefaultScheduler);
206 RegisterRegAlloc::setDefault(Fast ? createLocalRegisterAllocator :
207 createLinearScanRegisterAllocator);
208
Daniel Dunbar85e44e22008-10-21 23:49:24 +0000209 // From llvm-gcc:
210 // If there are passes we have to run on the entire module, we do codegen
211 // as a separate "pass" after that happens.
212 // FIXME: This is disabled right now until bugs can be worked out. Reenable
213 // this for fast -O0 compiles!
214 FunctionPassManager *PM = getCodeGenPasses();
215
216 // Normal mode, emit a .s file by running the code generator.
217 // Note, this also adds codegenerator level optimization passes.
218 switch (TM->addPassesToEmitFile(*PM, *AsmOutStream,
219 TargetMachine::AssemblyFile, Fast)) {
220 default:
221 case FileModel::Error:
222 Error = "Unable to interface with target machine!\n";
223 return false;
224 case FileModel::AsmFile:
225 break;
226 }
227
228 if (TM->addPassesToEmitFileFinish(*CodeGenPasses, 0, Fast)) {
229 Error = "Unable to interface with target machine!\n";
230 return false;
231 }
232 }
233
234 return true;
235}
236
237void BackendConsumer::CreatePasses() {
Daniel Dunbaraa7a0662008-10-23 05:50:47 +0000238 // In -O0 if checking is disabled, we don't even have per-function passes.
239 if (CompileOpts.VerifyModule)
240 getPerFunctionPasses()->add(createVerifierPass());
241
242 if (CompileOpts.OptimizationLevel > 0) {
243 FunctionPassManager *PM = getPerFunctionPasses();
244 PM->add(createCFGSimplificationPass());
245 if (CompileOpts.OptimizationLevel == 1)
246 PM->add(createPromoteMemoryToRegisterPass());
247 else
248 PM->add(createScalarReplAggregatesPass());
249 PM->add(createInstructionCombiningPass());
250 }
251
252 // For now we always create per module passes.
253 PassManager *PM = getPerModulePasses();
254 if (CompileOpts.OptimizationLevel > 0) {
255 if (CompileOpts.UnitAtATime)
256 PM->add(createRaiseAllocationsPass()); // call %malloc -> malloc inst
257 PM->add(createCFGSimplificationPass()); // Clean up disgusting code
258 PM->add(createPromoteMemoryToRegisterPass()); // Kill useless allocas
259 if (CompileOpts.UnitAtATime) {
260 PM->add(createGlobalOptimizerPass()); // Optimize out global vars
261 PM->add(createGlobalDCEPass()); // Remove unused fns and globs
262 PM->add(createIPConstantPropagationPass()); // IP Constant Propagation
263 PM->add(createDeadArgEliminationPass()); // Dead argument elimination
264 }
265 PM->add(createInstructionCombiningPass()); // Clean up after IPCP & DAE
266 PM->add(createCFGSimplificationPass()); // Clean up after IPCP & DAE
267 if (CompileOpts.UnitAtATime) {
268 PM->add(createPruneEHPass()); // Remove dead EH info
Bill Wendlingaccd9b72008-12-31 19:51:31 +0000269 PM->add(createFunctionAttrsPass()); // Set readonly/readnone attrs
Daniel Dunbaraa7a0662008-10-23 05:50:47 +0000270 }
271 if (CompileOpts.InlineFunctions)
272 PM->add(createFunctionInliningPass()); // Inline small functions
273 else
274 PM->add(createAlwaysInlinerPass()); // Respect always_inline
275 if (CompileOpts.OptimizationLevel > 2)
276 PM->add(createArgumentPromotionPass()); // Scalarize uninlined fn args
277 if (CompileOpts.SimplifyLibCalls)
278 PM->add(createSimplifyLibCallsPass()); // Library Call Optimizations
279 PM->add(createInstructionCombiningPass()); // Cleanup for scalarrepl.
280 PM->add(createJumpThreadingPass()); // Thread jumps.
281 PM->add(createCFGSimplificationPass()); // Merge & remove BBs
282 PM->add(createScalarReplAggregatesPass()); // Break up aggregate allocas
283 PM->add(createInstructionCombiningPass()); // Combine silly seq's
284 PM->add(createCondPropagationPass()); // Propagate conditionals
285 PM->add(createTailCallEliminationPass()); // Eliminate tail calls
286 PM->add(createCFGSimplificationPass()); // Merge & remove BBs
287 PM->add(createReassociatePass()); // Reassociate expressions
288 PM->add(createLoopRotatePass()); // Rotate Loop
289 PM->add(createLICMPass()); // Hoist loop invariants
290 PM->add(createLoopUnswitchPass(CompileOpts.OptimizeSize ? true : false));
Devang Patel62237e72008-11-26 05:01:52 +0000291// PM->add(createLoopIndexSplitPass()); // Split loop index
Daniel Dunbaraa7a0662008-10-23 05:50:47 +0000292 PM->add(createInstructionCombiningPass());
293 PM->add(createIndVarSimplifyPass()); // Canonicalize indvars
294 PM->add(createLoopDeletionPass()); // Delete dead loops
295 if (CompileOpts.UnrollLoops)
296 PM->add(createLoopUnrollPass()); // Unroll small loops
297 PM->add(createInstructionCombiningPass()); // Clean up after the unroller
298 PM->add(createGVNPass()); // Remove redundancies
299 PM->add(createMemCpyOptPass()); // Remove memcpy / form memset
300 PM->add(createSCCPPass()); // Constant prop with SCCP
301
302 // Run instcombine after redundancy elimination to exploit opportunities
303 // opened up by them.
304 PM->add(createInstructionCombiningPass());
305 PM->add(createCondPropagationPass()); // Propagate conditionals
306 PM->add(createDeadStoreEliminationPass()); // Delete dead stores
307 PM->add(createAggressiveDCEPass()); // Delete dead instructions
308 PM->add(createCFGSimplificationPass()); // Merge & remove BBs
309
310 if (CompileOpts.UnitAtATime) {
311 PM->add(createStripDeadPrototypesPass()); // Get rid of dead prototypes
312 PM->add(createDeadTypeEliminationPass()); // Eliminate dead types
313 }
314
315 if (CompileOpts.OptimizationLevel > 1 && CompileOpts.UnitAtATime)
316 PM->add(createConstantMergePass()); // Merge dup global constants
317 } else {
Daniel Dunbar160cb622008-11-13 05:29:02 +0000318 PM->add(createAlwaysInlinerPass());
Daniel Dunbaraa7a0662008-10-23 05:50:47 +0000319 }
Daniel Dunbar85e44e22008-10-21 23:49:24 +0000320}
321
322/// EmitAssembly - Handle interaction with LLVM backend to generate
323/// actual machine code.
324void BackendConsumer::EmitAssembly() {
325 // Silently ignore if we weren't initialized for some reason.
326 if (!TheModule || !TheTargetData)
327 return;
328
Daniel Dunbarbc147792008-10-27 20:40:41 +0000329 // Make sure IR generation is happy with the module. This is
330 // released by the module provider.
Daniel Dunbar85e44e22008-10-21 23:49:24 +0000331 Module *M = Gen->ReleaseModule();
332 if (!M) {
Daniel Dunbarbc147792008-10-27 20:40:41 +0000333 // The module has been released by IR gen on failures, do not
334 // double free.
335 ModuleProvider->releaseModule();
Daniel Dunbar85e44e22008-10-21 23:49:24 +0000336 TheModule = 0;
337 return;
338 }
339
340 assert(TheModule == M && "Unexpected module change during IR generation");
341
342 CreatePasses();
343
344 std::string Error;
Daniel Dunbar655d5092008-10-23 05:59:43 +0000345 if (!AddEmitPasses(Error)) {
Daniel Dunbar85e44e22008-10-21 23:49:24 +0000346 // FIXME: Don't fail this way.
347 llvm::cerr << "ERROR: " << Error << "\n";
348 ::exit(1);
349 }
350
351 // Run passes. For now we do all passes at once, but eventually we
352 // would like to have the option of streaming code generation.
353
354 if (PerFunctionPasses) {
355 PerFunctionPasses->doInitialization();
356 for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
357 if (!I->isDeclaration())
358 PerFunctionPasses->run(*I);
359 PerFunctionPasses->doFinalization();
360 }
361
362 if (PerModulePasses)
363 PerModulePasses->run(*M);
364
365 if (CodeGenPasses) {
366 CodeGenPasses->doInitialization();
367 for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
368 if (!I->isDeclaration())
369 CodeGenPasses->run(*I);
370 CodeGenPasses->doFinalization();
371 }
372}
373
374ASTConsumer *clang::CreateBackendConsumer(BackendAction Action,
375 Diagnostic &Diags,
Daniel Dunbar9101a632009-02-17 19:47:34 +0000376 const LangOptions &LangOpts,
Daniel Dunbaraa7a0662008-10-23 05:50:47 +0000377 const CompileOptions &CompileOpts,
Daniel Dunbar85e44e22008-10-21 23:49:24 +0000378 const std::string& InFile,
379 const std::string& OutFile,
380 bool GenerateDebugInfo) {
Chris Lattner57ff05c2009-02-12 01:50:58 +0000381 // FIXME: If optimizing, disable all debug info generation. The LLVM
382 // optimizer and backend is not ready to handle it when optimizations
383 // are enabled.
384 if (CompileOpts.OptimizationLevel > 0)
385 GenerateDebugInfo = false;
Daniel Dunbar9101a632009-02-17 19:47:34 +0000386
387 return new BackendConsumer(Action, Diags, LangOpts, CompileOpts,
Daniel Dunbaraa7a0662008-10-23 05:50:47 +0000388 InFile, OutFile, GenerateDebugInfo);
Daniel Dunbar85e44e22008-10-21 23:49:24 +0000389}