blob: a40dcee2b3afdcd424e324cb94a232135607efee [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- clang.cpp - C-Language Front-end ---------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This utility may be invoked in the following manner:
11// clang --help - Output help info.
12// clang [options] - Read from stdin.
13// clang [options] file - Read from "file".
14// clang [options] file1 file2 - Read these files.
15//
16//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +000017
Daniel Dunbar0498cfc2009-11-10 19:51:53 +000018#include "Options.h"
Daniel Dunbar775bee72009-11-11 10:07:22 +000019#include "clang/AST/ASTConsumer.h"
20#include "clang/AST/ASTContext.h"
21#include "clang/AST/Decl.h"
22#include "clang/AST/DeclGroup.h"
23#include "clang/Analysis/PathDiagnostic.h"
24#include "clang/Basic/FileManager.h"
25#include "clang/Basic/SourceManager.h"
26#include "clang/Basic/TargetInfo.h"
27#include "clang/Basic/Version.h"
28#include "clang/CodeGen/ModuleBuilder.h"
Eli Friedman8ceb0d92009-05-18 23:02:01 +000029#include "clang/Frontend/ASTConsumers.h"
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +000030#include "clang/Frontend/ASTUnit.h"
Daniel Dunbar775bee72009-11-11 10:07:22 +000031#include "clang/Frontend/AnalysisConsumer.h"
Daniel Dunbardbf75fe2009-11-11 08:13:24 +000032#include "clang/Frontend/ChainedDiagnosticClient.h"
Daniel Dunbar775bee72009-11-11 10:07:22 +000033#include "clang/Frontend/CommandLineSourceLoc.h"
Daniel Dunbare29709f2009-11-09 20:55:08 +000034#include "clang/Frontend/CompilerInvocation.h"
Daniel Dunbar0e0bae82009-11-11 21:43:12 +000035#include "clang/Frontend/DependencyOutputOptions.h"
Douglas Gregor558cb562009-04-02 01:08:08 +000036#include "clang/Frontend/FixItRewriter.h"
Daniel Dunbar50f4f462009-03-12 10:14:16 +000037#include "clang/Frontend/FrontendDiagnostic.h"
Douglas Gregor2cf26342009-04-09 22:27:44 +000038#include "clang/Frontend/PCHReader.h"
Daniel Dunbar8863b982009-11-07 04:20:15 +000039#include "clang/Frontend/PathDiagnosticClients.h"
40#include "clang/Frontend/PreprocessorOptions.h"
Daniel Dunbar775bee72009-11-11 10:07:22 +000041#include "clang/Frontend/PreprocessorOutputOptions.h"
Daniel Dunbare1bd4e62009-03-02 06:16:29 +000042#include "clang/Frontend/TextDiagnosticBuffer.h"
43#include "clang/Frontend/TextDiagnosticPrinter.h"
Eli Friedmanb09f6e12009-05-19 04:14:29 +000044#include "clang/Frontend/Utils.h"
Daniel Dunbar775bee72009-11-11 10:07:22 +000045#include "clang/Lex/HeaderSearch.h"
46#include "clang/Lex/LexDiagnostic.h"
47#include "clang/Parse/Parser.h"
Douglas Gregor81b747b2009-09-17 21:32:03 +000048#include "clang/Sema/CodeCompleteConsumer.h"
Chris Lattnere91c1342008-02-06 00:23:21 +000049#include "clang/Sema/ParseAST.h"
Chris Lattner88eccaf2009-01-29 06:55:46 +000050#include "clang/Sema/SemaDiagnostic.h"
Owen Anderson42253cc2009-07-01 17:00:06 +000051#include "llvm/LLVMContext.h"
Chris Lattnerba0f25f2008-09-30 20:16:56 +000052#include "llvm/ADT/OwningPtr.h"
Chris Lattner8f3dab82007-12-15 23:20:07 +000053#include "llvm/ADT/SmallPtrSet.h"
Chris Lattnerba0f25f2008-09-30 20:16:56 +000054#include "llvm/ADT/StringExtras.h"
Daniel Dunbar868bd0a2009-05-06 03:16:41 +000055#include "llvm/ADT/StringMap.h"
Daniel Dunbar227b2382009-11-09 22:45:57 +000056#include "llvm/ADT/StringSwitch.h"
Chris Lattnerba0f25f2008-09-30 20:16:56 +000057#include "llvm/Config/config.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000058#include "llvm/Support/CommandLine.h"
Daniel Dunbar70121eb2009-08-10 03:40:28 +000059#include "llvm/Support/ErrorHandling.h"
Daniel Dunbar524b86f2008-10-28 00:38:08 +000060#include "llvm/Support/ManagedStatic.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000061#include "llvm/Support/MemoryBuffer.h"
Zhongxing Xu20922362008-11-26 05:23:17 +000062#include "llvm/Support/PluginLoader.h"
Chris Lattner09e94a32009-03-04 21:41:39 +000063#include "llvm/Support/PrettyStackTrace.h"
Chris Lattner47099742009-02-18 01:51:21 +000064#include "llvm/Support/Timer.h"
Chris Lattner0fa0daa2009-08-24 04:11:30 +000065#include "llvm/Support/raw_ostream.h"
Daniel Dunbare553a722008-10-02 01:21:33 +000066#include "llvm/System/Host.h"
Chris Lattnerdcaa0962008-03-03 03:16:03 +000067#include "llvm/System/Path.h"
Eli Friedman66d6f042009-05-18 22:20:00 +000068#include "llvm/System/Program.h"
Chris Lattnerba0f25f2008-09-30 20:16:56 +000069#include "llvm/System/Signals.h"
Chris Lattner2fe11942009-06-17 17:25:50 +000070#include "llvm/Target/TargetSelect.h"
Douglas Gregor26df2f02009-04-02 19:05:20 +000071#include <cstdlib>
Douglas Gregor44cf08e2009-05-03 03:52:38 +000072#if HAVE_SYS_TYPES_H
Douglas Gregor68a0d782009-05-02 00:03:46 +000073# include <sys/types.h>
74#endif
Douglas Gregor26df2f02009-04-02 19:05:20 +000075
Reid Spencer5f016e22007-07-11 17:01:13 +000076using namespace clang;
77
78//===----------------------------------------------------------------------===//
79// Global options.
80//===----------------------------------------------------------------------===//
81
Chris Lattner47099742009-02-18 01:51:21 +000082/// ClangFrontendTimer - The front-end activities should charge time to it with
83/// TimeRegion. The -ftime-report option controls whether this will do
84/// anything.
85llvm::Timer *ClangFrontendTimer = 0;
86
Reid Spencer5f016e22007-07-11 17:01:13 +000087static llvm::cl::opt<bool>
88Verbose("v", llvm::cl::desc("Enable verbose output"));
89static llvm::cl::opt<bool>
Mike Stump1eb44332009-09-09 15:08:12 +000090Stats("print-stats",
Nate Begemanaabbb122007-12-30 01:38:50 +000091 llvm::cl::desc("Print performance metrics and statistics"));
Daniel Dunbard3db4012008-10-16 16:54:18 +000092static llvm::cl::opt<bool>
93DisableFree("disable-free",
94 llvm::cl::desc("Disable freeing of memory on exit"),
95 llvm::cl::init(false));
Daniel Dunbar57cbfc02009-04-27 21:19:07 +000096static llvm::cl::opt<bool>
Mike Stump1eb44332009-09-09 15:08:12 +000097EmptyInputOnly("empty-input-only",
Daniel Dunbar57cbfc02009-04-27 21:19:07 +000098 llvm::cl::desc("Force running on an empty input file"));
Reid Spencer5f016e22007-07-11 17:01:13 +000099
100enum ProgActions {
Steve Naroffb29b4272008-04-14 22:03:09 +0000101 RewriteObjC, // ObjC->C Rewriter.
Steve Naroff13188952008-09-18 14:10:13 +0000102 RewriteBlocks, // ObjC->C Rewriter for Blocks.
Chris Lattnerb57e3d42008-05-08 06:52:13 +0000103 RewriteMacros, // Expand macros but not #includes.
Chris Lattnerb13c5ee2008-10-12 05:29:20 +0000104 RewriteTest, // Rewriter playground
Douglas Gregor558cb562009-04-02 01:08:08 +0000105 FixIt, // Fix-It Rewriter
Ted Kremenek13e479b2008-03-19 07:53:42 +0000106 HTMLTest, // HTML displayer testing stuff.
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000107 EmitAssembly, // Emit a .s file.
Reid Spencer5f016e22007-07-11 17:01:13 +0000108 EmitLLVM, // Emit a .ll file.
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +0000109 EmitBC, // Emit a .bc file.
Mike Stump1eb44332009-09-09 15:08:12 +0000110 EmitLLVMOnly, // Generate LLVM IR, but do not
Ted Kremenek6a340832008-03-18 21:19:49 +0000111 EmitHTML, // Translate input source into HTML.
Chris Lattner3b427b32007-10-11 00:18:28 +0000112 ASTPrint, // Parse ASTs and print them.
Douglas Gregoree75c052009-05-21 20:55:50 +0000113 ASTPrintXML, // Parse ASTs and print them in XML.
Chris Lattner3b427b32007-10-11 00:18:28 +0000114 ASTDump, // Parse ASTs and dump them.
115 ASTView, // Parse ASTs and view them in Graphviz.
Zhongxing Xu2d75d6f2009-01-13 01:29:24 +0000116 PrintDeclContext, // Print DeclContext and their Decls.
Anders Carlsson78762eb2009-09-24 18:54:49 +0000117 DumpRecordLayouts, // Dump record layout information.
Reid Spencer5f016e22007-07-11 17:01:13 +0000118 ParsePrintCallbacks, // Parse and print each callback.
119 ParseSyntaxOnly, // Parse and perform semantic analysis.
120 ParseNoop, // Parse with noop callbacks.
121 RunPreprocessorOnly, // Just lex, no output.
122 PrintPreprocessedInput, // -E mode.
Chris Lattnerc106c102008-10-12 05:03:36 +0000123 DumpTokens, // Dump out preprocessed tokens.
124 DumpRawTokens, // Dump out raw tokens.
Mike Stump1eb44332009-09-09 15:08:12 +0000125 RunAnalysis, // Run one or more source code analyses.
Douglas Gregorbf1bd6e2009-04-02 23:43:50 +0000126 GeneratePTH, // Generate pre-tokenized header.
Douglas Gregor2cf26342009-04-09 22:27:44 +0000127 GeneratePCH, // Generate pre-compiled header.
Ted Kremenek7cae2f62008-10-23 23:36:29 +0000128 InheritanceView // View C++ inheritance for a specified class.
Reid Spencer5f016e22007-07-11 17:01:13 +0000129};
130
Mike Stump1eb44332009-09-09 15:08:12 +0000131static llvm::cl::opt<ProgActions>
Reid Spencer5f016e22007-07-11 17:01:13 +0000132ProgAction(llvm::cl::desc("Choose output type:"), llvm::cl::ZeroOrMore,
133 llvm::cl::init(ParseSyntaxOnly),
134 llvm::cl::values(
135 clEnumValN(RunPreprocessorOnly, "Eonly",
136 "Just run preprocessor, no output (for timings)"),
137 clEnumValN(PrintPreprocessedInput, "E",
138 "Run preprocessor, emit preprocessed file"),
Chris Lattnerc106c102008-10-12 05:03:36 +0000139 clEnumValN(DumpRawTokens, "dump-raw-tokens",
140 "Lex file in raw mode and dump raw tokens"),
Daniel Dunbard4270232009-01-20 23:17:32 +0000141 clEnumValN(RunAnalysis, "analyze",
142 "Run static analysis engine"),
Chris Lattnerc106c102008-10-12 05:03:36 +0000143 clEnumValN(DumpTokens, "dump-tokens",
Reid Spencer5f016e22007-07-11 17:01:13 +0000144 "Run preprocessor, dump internal rep of tokens"),
145 clEnumValN(ParseNoop, "parse-noop",
146 "Run parser with noop callbacks (for timings)"),
147 clEnumValN(ParseSyntaxOnly, "fsyntax-only",
148 "Run parser and perform semantic analysis"),
149 clEnumValN(ParsePrintCallbacks, "parse-print-callbacks",
150 "Run parser and print each callback invoked"),
Ted Kremenek6a340832008-03-18 21:19:49 +0000151 clEnumValN(EmitHTML, "emit-html",
152 "Output input source as HTML"),
Chris Lattner3b427b32007-10-11 00:18:28 +0000153 clEnumValN(ASTPrint, "ast-print",
154 "Build ASTs and then pretty-print them"),
Douglas Gregoree75c052009-05-21 20:55:50 +0000155 clEnumValN(ASTPrintXML, "ast-print-xml",
156 "Build ASTs and then print them in XML format"),
Chris Lattner3b427b32007-10-11 00:18:28 +0000157 clEnumValN(ASTDump, "ast-dump",
158 "Build ASTs and then debug dump them"),
Chris Lattnerea254db2007-10-11 00:37:43 +0000159 clEnumValN(ASTView, "ast-view",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000160 "Build ASTs and view them with GraphViz"),
Zhongxing Xu2d75d6f2009-01-13 01:29:24 +0000161 clEnumValN(PrintDeclContext, "print-decl-contexts",
Ted Kremenek08478eb2009-04-01 00:23:28 +0000162 "Print DeclContexts and their Decls"),
Anders Carlsson78762eb2009-09-24 18:54:49 +0000163 clEnumValN(DumpRecordLayouts, "dump-record-layouts",
164 "Dump record layout information"),
Douglas Gregorbf1bd6e2009-04-02 23:43:50 +0000165 clEnumValN(GeneratePTH, "emit-pth",
Ted Kremenek08478eb2009-04-01 00:23:28 +0000166 "Generate pre-tokenized header file"),
Douglas Gregor2cf26342009-04-09 22:27:44 +0000167 clEnumValN(GeneratePCH, "emit-pch",
168 "Generate pre-compiled header file"),
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000169 clEnumValN(EmitAssembly, "S",
170 "Emit native assembly code"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000171 clEnumValN(EmitLLVM, "emit-llvm",
Ted Kremenek27b07c52007-09-06 21:26:58 +0000172 "Build ASTs then convert to LLVM, emit .ll file"),
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +0000173 clEnumValN(EmitBC, "emit-llvm-bc",
174 "Build ASTs then convert to LLVM, emit .bc file"),
Daniel Dunbare8e26002009-02-26 22:39:37 +0000175 clEnumValN(EmitLLVMOnly, "emit-llvm-only",
176 "Build ASTs and convert to LLVM, discarding output"),
Chris Lattnerb13c5ee2008-10-12 05:29:20 +0000177 clEnumValN(RewriteTest, "rewrite-test",
178 "Rewriter playground"),
Steve Naroffb29b4272008-04-14 22:03:09 +0000179 clEnumValN(RewriteObjC, "rewrite-objc",
Chris Lattnerb57e3d42008-05-08 06:52:13 +0000180 "Rewrite ObjC into C (code rewriter example)"),
181 clEnumValN(RewriteMacros, "rewrite-macros",
182 "Expand macros without full preprocessing"),
Steve Naroff13188952008-09-18 14:10:13 +0000183 clEnumValN(RewriteBlocks, "rewrite-blocks",
184 "Rewrite Blocks to C"),
Douglas Gregor558cb562009-04-02 01:08:08 +0000185 clEnumValN(FixIt, "fixit",
186 "Apply fix-it advice to the input source"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000187 clEnumValEnd));
188
Ted Kremenekccc76472007-12-19 19:47:59 +0000189
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000190enum CodeCompletionPrinter {
191 CCP_Debug,
192 CCP_CIndex
193};
194
Douglas Gregorb657f112009-09-22 21:11:38 +0000195static llvm::cl::opt<ParsedSourceLocation>
196CodeCompletionAt("code-completion-at",
197 llvm::cl::value_desc("file:line:column"),
198 llvm::cl::desc("Dump code-completion information at a location"));
Douglas Gregor81b747b2009-09-17 21:32:03 +0000199
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000200static llvm::cl::opt<CodeCompletionPrinter>
201CodeCompletionPrinter("code-completion-printer",
202 llvm::cl::desc("Choose output type:"),
203 llvm::cl::init(CCP_Debug),
204 llvm::cl::values(
205 clEnumValN(CCP_Debug, "debug",
206 "Debug code-completion results"),
207 clEnumValN(CCP_CIndex, "cindex",
208 "Code-completion results for the CIndex library"),
209 clEnumValEnd));
210
211static llvm::cl::opt<bool>
212CodeCompletionWantsMacros("code-completion-macros",
213 llvm::cl::desc("Include macros in code-completion results"));
214
Douglas Gregor81b747b2009-09-17 21:32:03 +0000215/// \brief Buld a new code-completion consumer that prints the results of
216/// code completion to standard output.
217static CodeCompleteConsumer *BuildPrintingCodeCompleter(Sema &S, void *) {
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000218 switch (CodeCompletionPrinter.getValue()) {
219 case CCP_Debug:
Daniel Dunbarc8daaa42009-11-12 00:24:28 +0000220 return new PrintingCodeCompleteConsumer(S, CodeCompletionWantsMacros,
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000221 llvm::outs());
Daniel Dunbarc8daaa42009-11-12 00:24:28 +0000222
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000223 case CCP_CIndex:
224 return new CIndexCodeCompleteConsumer(S, CodeCompletionWantsMacros,
225 llvm::outs());
226 };
Daniel Dunbarc8daaa42009-11-12 00:24:28 +0000227
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000228 return 0;
Douglas Gregor81b747b2009-09-17 21:32:03 +0000229}
230
Ted Kremenekc2e72992008-12-02 19:57:31 +0000231//===----------------------------------------------------------------------===//
Ted Kremenek7cae2f62008-10-23 23:36:29 +0000232// C++ Visualization.
233//===----------------------------------------------------------------------===//
234
235static llvm::cl::opt<std::string>
236InheritanceViewCls("cxx-inheritance-view",
237 llvm::cl::value_desc("class name"),
Daniel Dunbard77b2512009-01-14 18:56:36 +0000238 llvm::cl::desc("View C++ inheritance for a specified class"));
Ted Kremenek7cae2f62008-10-23 23:36:29 +0000239
240//===----------------------------------------------------------------------===//
Daniel Dunbar0db4b762009-11-11 08:13:40 +0000241// Frontend Options
Douglas Gregor3573c0c2009-02-14 20:49:29 +0000242//===----------------------------------------------------------------------===//
Chris Lattnerb2509e12009-02-18 01:12:43 +0000243
Daniel Dunbard1cdcf32009-11-11 08:13:47 +0000244static llvm::cl::list<std::string>
245InputFilenames(llvm::cl::Positional, llvm::cl::desc("<input files>"));
246
247static llvm::cl::opt<std::string>
248OutputFile("o",
249 llvm::cl::value_desc("path"),
250 llvm::cl::desc("Specify output file"));
251
Chris Lattnerb2509e12009-02-18 01:12:43 +0000252static llvm::cl::opt<bool>
253TimeReport("ftime-report",
254 llvm::cl::desc("Print the amount of time each "
255 "phase of compilation takes"));
256
Daniel Dunbar0db4b762009-11-11 08:13:40 +0000257static llvm::cl::opt<bool>
258VerifyDiagnostics("verify",
259 llvm::cl::desc("Verify emitted diagnostics and warnings"));
260
Douglas Gregor3573c0c2009-02-14 20:49:29 +0000261//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +0000262// Language Options
263//===----------------------------------------------------------------------===//
264
Reid Spencer5f016e22007-07-11 17:01:13 +0000265static llvm::cl::opt<LangKind>
266BaseLang("x", llvm::cl::desc("Base language to compile"),
267 llvm::cl::init(langkind_unspecified),
268 llvm::cl::values(clEnumValN(langkind_c, "c", "C"),
Nate Begeman4e3629e2009-06-25 22:43:10 +0000269 clEnumValN(langkind_ocl, "cl", "OpenCL C"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000270 clEnumValN(langkind_cxx, "c++", "C++"),
271 clEnumValN(langkind_objc, "objective-c", "Objective C"),
272 clEnumValN(langkind_objcxx,"objective-c++","Objective C++"),
Daniel Dunbard2ea3862009-01-29 23:50:47 +0000273 clEnumValN(langkind_c_cpp, "cpp-output",
Reid Spencer5f016e22007-07-11 17:01:13 +0000274 "Preprocessed C"),
Chris Lattnera778d7d2008-10-22 17:29:21 +0000275 clEnumValN(langkind_asm_cpp, "assembler-with-cpp",
276 "Preprocessed asm"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000277 clEnumValN(langkind_cxx_cpp, "c++-cpp-output",
Chris Lattnerc76d8072009-02-06 06:19:20 +0000278 "Preprocessed C++"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000279 clEnumValN(langkind_objc_cpp, "objective-c-cpp-output",
280 "Preprocessed Objective C"),
Chris Lattnerc76d8072009-02-06 06:19:20 +0000281 clEnumValN(langkind_objcxx_cpp, "objective-c++-cpp-output",
Reid Spencer5f016e22007-07-11 17:01:13 +0000282 "Preprocessed Objective C++"),
Daniel Dunbar0b5b0da2009-04-01 05:09:09 +0000283 clEnumValN(langkind_c, "c-header",
284 "C header"),
285 clEnumValN(langkind_objc, "objective-c-header",
286 "Objective-C header"),
287 clEnumValN(langkind_cxx, "c++-header",
288 "C++ header"),
289 clEnumValN(langkind_objcxx, "objective-c++-header",
290 "Objective-C++ header"),
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +0000291 clEnumValN(langkind_ast, "ast",
292 "Clang AST"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000293 clEnumValEnd));
294
Daniel Dunbar7c15e712009-10-30 18:12:31 +0000295static llvm::cl::opt<std::string>
296TargetTriple("triple",
297 llvm::cl::desc("Specify target triple (e.g. i686-apple-darwin9)"));
298
Daniel Dunbar56749082009-11-11 07:26:12 +0000299static llvm::cl::opt<std::string>
300TargetABI("target-abi",
301 llvm::cl::desc("Target a particular ABI type"));
Reid Spencer5f016e22007-07-11 17:01:13 +0000302
303//===----------------------------------------------------------------------===//
Chris Lattnere116ccf2009-04-21 05:40:52 +0000304// SourceManager initialization.
Reid Spencer5f016e22007-07-11 17:01:13 +0000305//===----------------------------------------------------------------------===//
306
Douglas Gregore1d918e2009-04-10 23:10:45 +0000307static bool InitializeSourceManager(Preprocessor &PP,
308 const std::string &InFile) {
309 // Figure out where to get and map in the main file.
310 SourceManager &SourceMgr = PP.getSourceManager();
311 FileManager &FileMgr = PP.getFileManager();
Daniel Dunbar57cbfc02009-04-27 21:19:07 +0000312
313 if (EmptyInputOnly) {
314 const char *EmptyStr = "";
Mike Stump1eb44332009-09-09 15:08:12 +0000315 llvm::MemoryBuffer *SB =
Daniel Dunbar57cbfc02009-04-27 21:19:07 +0000316 llvm::MemoryBuffer::getMemBuffer(EmptyStr, EmptyStr, "<empty input>");
317 SourceMgr.createMainFileIDForMemBuffer(SB);
318 } else if (InFile != "-") {
Douglas Gregore1d918e2009-04-10 23:10:45 +0000319 const FileEntry *File = FileMgr.getFile(InFile);
320 if (File) SourceMgr.createMainFileID(File, SourceLocation());
321 if (SourceMgr.getMainFileID().isInvalid()) {
Daniel Dunbar0f9fed72009-11-10 23:55:23 +0000322 PP.getDiagnostics().Report(diag::err_fe_error_reading) << InFile.c_str();
Douglas Gregore1d918e2009-04-10 23:10:45 +0000323 return true;
324 }
325 } else {
326 llvm::MemoryBuffer *SB = llvm::MemoryBuffer::getSTDIN();
Douglas Gregore1d918e2009-04-10 23:10:45 +0000327 SourceMgr.createMainFileIDForMemBuffer(SB);
328 if (SourceMgr.getMainFileID().isInvalid()) {
Daniel Dunbar0f9fed72009-11-10 23:55:23 +0000329 PP.getDiagnostics().Report(diag::err_fe_error_reading_stdin);
Douglas Gregore1d918e2009-04-10 23:10:45 +0000330 return true;
331 }
332 }
333
334 return false;
335}
336
Chris Lattneraa391972008-04-19 23:09:31 +0000337
Chris Lattnere116ccf2009-04-21 05:40:52 +0000338//===----------------------------------------------------------------------===//
339// Preprocessor Initialization
340//===----------------------------------------------------------------------===//
Sam Bishop1102d6b2008-04-14 14:41:57 +0000341
Chris Lattnere6113de2009-11-03 19:50:27 +0000342static llvm::cl::opt<bool>
Mike Stump1eb44332009-09-09 15:08:12 +0000343RelocatablePCH("relocatable-pch",
Douglas Gregore650c8c2009-07-07 00:12:59 +0000344 llvm::cl::desc("Whether to build a relocatable precompiled "
345 "header"));
Reid Spencer5f016e22007-07-11 17:01:13 +0000346
Reid Spencer5f016e22007-07-11 17:01:13 +0000347// Finally, implement the code that groks the options above.
Chris Lattner5f9eae52008-03-01 08:07:28 +0000348
Rafael Espindola1bb15a92009-10-05 13:12:17 +0000349// Add the clang headers, which are relative to the clang binary.
Daniel Dunbar750156a2009-11-07 04:19:57 +0000350std::string GetBuiltinIncludePath(const char *Argv0) {
351 llvm::sys::Path P =
352 llvm::sys::Path::GetMainExecutable(Argv0,
353 (void*)(intptr_t) GetBuiltinIncludePath);
Rafael Espindola1bb15a92009-10-05 13:12:17 +0000354
Daniel Dunbar750156a2009-11-07 04:19:57 +0000355 if (!P.isEmpty()) {
356 P.eraseComponent(); // Remove /clang from foo/bin/clang
357 P.eraseComponent(); // Remove /bin from foo/bin
Rafael Espindola1bb15a92009-10-05 13:12:17 +0000358
Daniel Dunbar750156a2009-11-07 04:19:57 +0000359 // Get foo/lib/clang/<version>/include
360 P.appendComponent("lib");
361 P.appendComponent("clang");
362 P.appendComponent(CLANG_VERSION_STRING);
363 P.appendComponent("include");
364 }
Rafael Espindola1bb15a92009-10-05 13:12:17 +0000365
Daniel Dunbar750156a2009-11-07 04:19:57 +0000366 return P.str();
Rafael Espindola1bb15a92009-10-05 13:12:17 +0000367}
368
Ted Kremeneka42cf2e2008-04-17 21:38:34 +0000369//===----------------------------------------------------------------------===//
Daniel Dunbar90b18272009-11-04 23:56:25 +0000370// Preprocessor construction
Ted Kremeneka42cf2e2008-04-17 21:38:34 +0000371//===----------------------------------------------------------------------===//
372
Daniel Dunbar90b18272009-11-04 23:56:25 +0000373static Preprocessor *
Daniel Dunbar5fc7d342009-11-09 23:12:31 +0000374CreatePreprocessor(Diagnostic &Diags, const LangOptions &LangInfo,
Daniel Dunbarca11f612009-11-11 21:44:00 +0000375 const PreprocessorOptions &PPOpts,
Daniel Dunbar961c76e2009-11-11 21:44:42 +0000376 const HeaderSearchOptions &HSOpts,
Daniel Dunbarca11f612009-11-11 21:44:00 +0000377 const DependencyOutputOptions &DepOpts,
378 TargetInfo &Target, SourceManager &SourceMgr,
Daniel Dunbar5814e652009-11-11 21:44:21 +0000379 FileManager &FileMgr) {
Daniel Dunbarb3cb98e2009-11-12 02:53:59 +0000380 // Create a PTH manager if we are using some form of a token cache.
Daniel Dunbar90b18272009-11-04 23:56:25 +0000381 PTHManager *PTHMgr = 0;
Daniel Dunbarb3cb98e2009-11-12 02:53:59 +0000382 if (!PPOpts.getTokenCache().empty())
383 PTHMgr = PTHManager::Create(PPOpts.getTokenCache(), Diags);
Daniel Dunbar90b18272009-11-04 23:56:25 +0000384
Daniel Dunbarb3cb98e2009-11-12 02:53:59 +0000385 // FIXME: Don't fail like this.
Daniel Dunbar90b18272009-11-04 23:56:25 +0000386 if (Diags.hasErrorOccurred())
387 exit(1);
388
389 // Create the Preprocessor.
Daniel Dunbar5814e652009-11-11 21:44:21 +0000390 HeaderSearch *HeaderInfo = new HeaderSearch(FileMgr);
Daniel Dunbar90b18272009-11-04 23:56:25 +0000391 Preprocessor *PP = new Preprocessor(Diags, LangInfo, Target,
Daniel Dunbar5814e652009-11-11 21:44:21 +0000392 SourceMgr, *HeaderInfo, PTHMgr,
393 /*OwnsHeaderSearch=*/true);
Daniel Dunbar90b18272009-11-04 23:56:25 +0000394
395 // Note that this is different then passing PTHMgr to Preprocessor's ctor.
396 // That argument is used as the IdentifierInfoLookup argument to
397 // IdentifierTable's ctor.
398 if (PTHMgr) {
399 PTHMgr->setPreprocessor(PP);
400 PP->setPTHManager(PTHMgr);
401 }
402
Daniel Dunbar961c76e2009-11-11 21:44:42 +0000403 InitializePreprocessor(*PP, PPOpts, HSOpts);
Daniel Dunbar90b18272009-11-04 23:56:25 +0000404
Daniel Dunbarca11f612009-11-11 21:44:00 +0000405 // Handle generating dependencies, if requested.
406 if (!DepOpts.OutputFile.empty())
407 AttachDependencyFileGen(*PP, DepOpts);
408
Daniel Dunbar90b18272009-11-04 23:56:25 +0000409 return PP;
Ted Kremeneka42cf2e2008-04-17 21:38:34 +0000410}
Reid Spencer5f016e22007-07-11 17:01:13 +0000411
Reid Spencer5f016e22007-07-11 17:01:13 +0000412//===----------------------------------------------------------------------===//
413// Basic Parser driver
414//===----------------------------------------------------------------------===//
415
Chris Lattner51574ea2008-04-19 23:25:44 +0000416static void ParseFile(Preprocessor &PP, MinimalAction *PA) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000417 Parser P(PP, *PA);
Ted Kremenek95041a22007-12-19 22:51:13 +0000418 PP.EnterMainSourceFile();
Mike Stump1eb44332009-09-09 15:08:12 +0000419
Reid Spencer5f016e22007-07-11 17:01:13 +0000420 // Parsing the specified input file.
421 P.ParseTranslationUnit();
422 delete PA;
423}
424
425//===----------------------------------------------------------------------===//
Douglas Gregor26df2f02009-04-02 19:05:20 +0000426// Fix-It Options
427//===----------------------------------------------------------------------===//
428static llvm::cl::list<ParsedSourceLocation>
429FixItAtLocations("fixit-at", llvm::cl::value_desc("source-location"),
430 llvm::cl::desc("Perform Fix-It modifications at the given source location"));
431
432//===----------------------------------------------------------------------===//
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000433// ObjC Rewriter Options
434//===----------------------------------------------------------------------===//
435static llvm::cl::opt<bool>
436SilenceRewriteMacroWarning("Wno-rewrite-macros", llvm::cl::init(false),
437 llvm::cl::desc("Silence ObjC rewriting warnings"));
438
439//===----------------------------------------------------------------------===//
Eli Friedman0eeb86e2009-05-19 01:17:04 +0000440// Warning Options
441//===----------------------------------------------------------------------===//
442
443// This gets all -W options, including -Werror, -W[no-]system-headers, etc. The
444// driver has stripped off -Wa,foo etc. The driver has also translated -W to
445// -Wextra, so we don't need to worry about it.
446static llvm::cl::list<std::string>
447OptWarnings("W", llvm::cl::Prefix, llvm::cl::ValueOptional);
448
449static llvm::cl::opt<bool> OptPedantic("pedantic");
450static llvm::cl::opt<bool> OptPedanticErrors("pedantic-errors");
451static llvm::cl::opt<bool> OptNoWarnings("w");
452
453//===----------------------------------------------------------------------===//
Chris Lattner75a97cb2009-04-17 21:05:01 +0000454// -dump-build-information Stuff
455//===----------------------------------------------------------------------===//
456
457static llvm::cl::opt<std::string>
458DumpBuildInformation("dump-build-information",
459 llvm::cl::value_desc("filename"),
460 llvm::cl::desc("output a dump of some build information to a file"));
461
Daniel Dunbar227b2382009-11-09 22:45:57 +0000462static void SetUpBuildDumpLog(const DiagnosticOptions &DiagOpts,
Daniel Dunbare29709f2009-11-09 20:55:08 +0000463 unsigned argc, char **argv,
Chris Lattner75a97cb2009-04-17 21:05:01 +0000464 llvm::OwningPtr<DiagnosticClient> &DiagClient) {
Chris Lattner75a97cb2009-04-17 21:05:01 +0000465 std::string ErrorInfo;
Daniel Dunbaraea36412009-11-11 09:38:24 +0000466 llvm::raw_ostream *OS = new llvm::raw_fd_ostream(DumpBuildInformation.c_str(),
467 ErrorInfo);
Chris Lattner75a97cb2009-04-17 21:05:01 +0000468 if (!ErrorInfo.empty()) {
469 llvm::errs() << "error opening -dump-build-information file '"
470 << DumpBuildInformation << "', option ignored!\n";
Daniel Dunbaraea36412009-11-11 09:38:24 +0000471 delete OS;
Chris Lattner75a97cb2009-04-17 21:05:01 +0000472 return;
473 }
474
Daniel Dunbaraea36412009-11-11 09:38:24 +0000475 (*OS) << "clang-cc command line arguments: ";
Chris Lattner75a97cb2009-04-17 21:05:01 +0000476 for (unsigned i = 0; i != argc; ++i)
Daniel Dunbaraea36412009-11-11 09:38:24 +0000477 (*OS) << argv[i] << ' ';
478 (*OS) << '\n';
Mike Stump1eb44332009-09-09 15:08:12 +0000479
Daniel Dunbardbf75fe2009-11-11 08:13:24 +0000480 // Chain in a diagnostic client which will log the diagnostics.
Daniel Dunbaraea36412009-11-11 09:38:24 +0000481 DiagnosticClient *Logger =
482 new TextDiagnosticPrinter(*OS, DiagOpts, /*OwnsOutputStream=*/true);
Daniel Dunbardbf75fe2009-11-11 08:13:24 +0000483 DiagClient.reset(new ChainedDiagnosticClient(DiagClient.take(), Logger));
Chris Lattner75a97cb2009-04-17 21:05:01 +0000484}
485
Chris Lattner75a97cb2009-04-17 21:05:01 +0000486//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +0000487// Main driver
488//===----------------------------------------------------------------------===//
489
Daniel Dunbare29709f2009-11-09 20:55:08 +0000490static llvm::raw_ostream *ComputeOutFile(const CompilerInvocation &CompOpts,
491 const std::string &InFile,
Chris Lattner92bcc272009-08-23 02:59:41 +0000492 const char *Extension,
Eli Friedman66d6f042009-05-18 22:20:00 +0000493 bool Binary,
494 llvm::sys::Path& OutPath) {
Chris Lattner92bcc272009-08-23 02:59:41 +0000495 llvm::raw_ostream *Ret;
Eli Friedman66d6f042009-05-18 22:20:00 +0000496 std::string OutFile;
Daniel Dunbare29709f2009-11-09 20:55:08 +0000497 if (!CompOpts.getOutputFile().empty())
498 OutFile = CompOpts.getOutputFile();
Chris Lattner92bcc272009-08-23 02:59:41 +0000499 else if (InFile == "-") {
500 OutFile = "-";
Eli Friedman66d6f042009-05-18 22:20:00 +0000501 } else if (Extension) {
502 llvm::sys::Path Path(InFile);
503 Path.eraseSuffix();
504 Path.appendSuffix(Extension);
Chris Lattnerd57a7ef2009-08-23 22:45:33 +0000505 OutFile = Path.str();
Eli Friedman66d6f042009-05-18 22:20:00 +0000506 } else {
Chris Lattner92bcc272009-08-23 02:59:41 +0000507 OutFile = "-";
Chris Lattner8a5c8092009-02-18 01:20:05 +0000508 }
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +0000509
Chris Lattner92bcc272009-08-23 02:59:41 +0000510 std::string Error;
511 Ret = new llvm::raw_fd_ostream(OutFile.c_str(), Error,
Dan Gohmanb044c472009-08-25 15:36:09 +0000512 (Binary ? llvm::raw_fd_ostream::F_Binary : 0));
Chris Lattner92bcc272009-08-23 02:59:41 +0000513 if (!Error.empty()) {
514 // FIXME: Don't fail this way.
515 llvm::errs() << "ERROR: " << Error << "\n";
516 ::exit(1);
Ted Kremenekdb094a22007-12-05 18:27:04 +0000517 }
Mike Stump1eb44332009-09-09 15:08:12 +0000518
Chris Lattner92bcc272009-08-23 02:59:41 +0000519 if (OutFile != "-")
520 OutPath = OutFile;
Eli Friedman66d6f042009-05-18 22:20:00 +0000521
522 return Ret;
Ted Kremenekdb094a22007-12-05 18:27:04 +0000523}
524
Daniel Dunbardc8bbac2009-11-11 09:38:42 +0000525/// AddFixItLocations - Add any individual user specified "fix-it" locations,
Daniel Dunbarbd9f04b2009-11-11 09:38:35 +0000526/// and return true on success (if any were added).
Daniel Dunbardc8bbac2009-11-11 09:38:42 +0000527static bool AddFixItLocations(FixItRewriter *FixItRewrite,
Daniel Dunbarbd9f04b2009-11-11 09:38:35 +0000528 FileManager &FileMgr) {
Daniel Dunbardc8bbac2009-11-11 09:38:42 +0000529 bool AddedFixItLocation = false;
Daniel Dunbarbd9f04b2009-11-11 09:38:35 +0000530
531 for (unsigned i = 0, e = FixItAtLocations.size(); i != e; ++i) {
532 if (const FileEntry *File = FileMgr.getFile(FixItAtLocations[i].FileName)) {
533 RequestedSourceLocation Requested;
534 Requested.File = File;
535 Requested.Line = FixItAtLocations[i].Line;
536 Requested.Column = FixItAtLocations[i].Column;
537 FixItRewrite->addFixItLocation(Requested);
Daniel Dunbardc8bbac2009-11-11 09:38:42 +0000538 AddedFixItLocation = true;
Daniel Dunbarbd9f04b2009-11-11 09:38:35 +0000539 } else {
540 llvm::errs() << "FIX-IT could not find file \""
541 << FixItAtLocations[i].FileName << "\"\n";
542 }
543 }
544
Daniel Dunbardc8bbac2009-11-11 09:38:42 +0000545 return AddedFixItLocation;
Daniel Dunbarbd9f04b2009-11-11 09:38:35 +0000546}
547
Daniel Dunbare29709f2009-11-09 20:55:08 +0000548static ASTConsumer *CreateConsumerAction(const CompilerInvocation &CompOpts,
549 Preprocessor &PP,
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000550 const std::string &InFile,
551 ProgActions PA,
552 llvm::OwningPtr<llvm::raw_ostream> &OS,
553 llvm::sys::Path &OutPath,
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000554 llvm::LLVMContext& Context) {
Ted Kremenek85888962008-10-21 00:54:44 +0000555 switch (PA) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000556 default:
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000557 return 0;
Eli Friedman66d6f042009-05-18 22:20:00 +0000558
559 case ASTPrint:
Daniel Dunbare29709f2009-11-09 20:55:08 +0000560 OS.reset(ComputeOutFile(CompOpts, InFile, 0, false, OutPath));
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000561 return CreateASTPrinter(OS.get());
Mike Stump1eb44332009-09-09 15:08:12 +0000562
Douglas Gregoree75c052009-05-21 20:55:50 +0000563 case ASTPrintXML:
Daniel Dunbare29709f2009-11-09 20:55:08 +0000564 OS.reset(ComputeOutFile(CompOpts, InFile, "xml", false, OutPath));
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000565 return CreateASTPrinterXML(OS.get());
Douglas Gregoree75c052009-05-21 20:55:50 +0000566
Eli Friedman66d6f042009-05-18 22:20:00 +0000567 case ASTDump:
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000568 return CreateASTDumper();
Eli Friedman66d6f042009-05-18 22:20:00 +0000569
Eli Friedman66d6f042009-05-18 22:20:00 +0000570 case ASTView:
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000571 return CreateASTViewer();
Eli Friedman66d6f042009-05-18 22:20:00 +0000572
Anders Carlsson78762eb2009-09-24 18:54:49 +0000573 case DumpRecordLayouts:
574 return CreateRecordLayoutDumper();
575
Eli Friedman66d6f042009-05-18 22:20:00 +0000576 case InheritanceView:
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000577 return CreateInheritanceViewer(InheritanceViewCls);
Eli Friedman66d6f042009-05-18 22:20:00 +0000578
579 case EmitAssembly:
580 case EmitLLVM:
Mike Stump1eb44332009-09-09 15:08:12 +0000581 case EmitBC:
Eli Friedman66d6f042009-05-18 22:20:00 +0000582 case EmitLLVMOnly: {
583 BackendAction Act;
584 if (ProgAction == EmitAssembly) {
585 Act = Backend_EmitAssembly;
Daniel Dunbare29709f2009-11-09 20:55:08 +0000586 OS.reset(ComputeOutFile(CompOpts, InFile, "s", true, OutPath));
Eli Friedman66d6f042009-05-18 22:20:00 +0000587 } else if (ProgAction == EmitLLVM) {
588 Act = Backend_EmitLL;
Daniel Dunbare29709f2009-11-09 20:55:08 +0000589 OS.reset(ComputeOutFile(CompOpts, InFile, "ll", true, OutPath));
Eli Friedman66d6f042009-05-18 22:20:00 +0000590 } else if (ProgAction == EmitLLVMOnly) {
591 Act = Backend_EmitNothing;
592 } else {
593 Act = Backend_EmitBC;
Daniel Dunbare29709f2009-11-09 20:55:08 +0000594 OS.reset(ComputeOutFile(CompOpts, InFile, "bc", true, OutPath));
Ted Kremenekdb094a22007-12-05 18:27:04 +0000595 }
Ted Kremenekfdfc1982007-12-19 22:24:34 +0000596
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000597 return CreateBackendConsumer(Act, PP.getDiagnostics(), PP.getLangOptions(),
Daniel Dunbar36f4ec32009-11-10 16:19:45 +0000598 CompOpts.getCompileOpts(), InFile, OS.get(),
599 Context);
Eli Friedman66d6f042009-05-18 22:20:00 +0000600 }
601
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000602 case RewriteObjC:
Daniel Dunbare29709f2009-11-09 20:55:08 +0000603 OS.reset(ComputeOutFile(CompOpts, InFile, "cpp", true, OutPath));
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000604 return CreateObjCRewriter(InFile, OS.get(), PP.getDiagnostics(),
605 PP.getLangOptions(), SilenceRewriteMacroWarning);
606
607 case RewriteBlocks:
608 return CreateBlockRewriter(InFile, PP.getDiagnostics(),
609 PP.getLangOptions());
Daniel Dunbar5ee0aa72009-11-11 00:54:56 +0000610
Daniel Dunbar387ecbd2009-11-11 10:22:48 +0000611 case FixIt: // We add the rewriter later.
Daniel Dunbar5ee0aa72009-11-11 00:54:56 +0000612 case ParseSyntaxOnly:
613 return new ASTConsumer();
614
615 case PrintDeclContext:
616 return CreateDeclContextPrinter();
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000617 }
618}
619
Daniel Dunbar975790e2009-11-12 02:53:20 +0000620/// ReadPCHFile - Load a PCH file from disk, and initialize the preprocessor for
621/// reading from the PCH file.
622///
623/// \return The AST source, or null on failure.
624static ExternalASTSource *ReadPCHFile(llvm::StringRef Path,
625 const CompilerInvocation &CompOpts,
626 Preprocessor &PP,
627 ASTContext &Context) {
628 // If the user specified -isysroot, it will be used for relocatable PCH files.
629 const char *isysrootPCH = CompOpts.getHeaderSearchOpts().Sysroot.c_str();
630 if (isysrootPCH[0] == '\0')
631 isysrootPCH = 0;
632
633 llvm::OwningPtr<PCHReader> Reader;
634 Reader.reset(new PCHReader(PP, &Context, isysrootPCH));
635
636 switch (Reader->ReadPCH(Path)) {
637 case PCHReader::Success:
638 // Set the predefines buffer as suggested by the PCH reader. Typically, the
639 // predefines buffer will be empty.
640 PP.setPredefines(Reader->getSuggestedPredefines());
641 return Reader.take();
642
643 case PCHReader::Failure:
644 // Unrecoverable failure: don't even try to process the input file.
645 break;
646
647 case PCHReader::IgnorePCH:
648 // No suitable PCH file could be found. Return an error.
649 break;
650 }
651
652 return 0;
653}
654
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000655/// ProcessInputFile - Process a single input file with the specified state.
656///
Daniel Dunbare29709f2009-11-09 20:55:08 +0000657static void ProcessInputFile(const CompilerInvocation &CompOpts,
658 Preprocessor &PP, const std::string &InFile,
Daniel Dunbar0e0bae82009-11-11 21:43:12 +0000659 ProgActions PA, llvm::LLVMContext& Context) {
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000660 llvm::OwningPtr<llvm::raw_ostream> OS;
661 llvm::OwningPtr<ASTConsumer> Consumer;
662 bool ClearSourceMgr = false;
663 FixItRewriter *FixItRewrite = 0;
664 bool CompleteTranslationUnit = true;
665 llvm::sys::Path OutPath;
666
667 switch (PA) {
668 default:
Daniel Dunbare29709f2009-11-09 20:55:08 +0000669 Consumer.reset(CreateConsumerAction(CompOpts, PP, InFile, PA, OS, OutPath,
Daniel Dunbar26a0cac2009-11-09 22:46:17 +0000670 Context));
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000671 if (!Consumer.get()) {
Daniel Dunbar0f9fed72009-11-10 23:55:23 +0000672 PP.getDiagnostics().Report(diag::err_fe_invalid_ast_action);
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000673 return;
674 }
Daniel Dunbardc8bbac2009-11-11 09:38:42 +0000675 break;
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000676
677 case EmitHTML:
Daniel Dunbare29709f2009-11-09 20:55:08 +0000678 OS.reset(ComputeOutFile(CompOpts, InFile, 0, true, OutPath));
Daniel Dunbar90b18272009-11-04 23:56:25 +0000679 Consumer.reset(CreateHTMLPrinter(OS.get(), PP));
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000680 break;
681
Daniel Dunbar5746f1f2009-11-12 00:24:10 +0000682 case RunAnalysis:
Daniel Dunbare29709f2009-11-09 20:55:08 +0000683 Consumer.reset(CreateAnalysisConsumer(PP, CompOpts.getOutputFile(),
Daniel Dunbar5746f1f2009-11-12 00:24:10 +0000684 CompOpts.getAnalyzerOpts()));
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000685 break;
686
Daniel Dunbarf7973292009-11-11 08:13:32 +0000687 case GeneratePCH: {
688 const std::string &Sysroot = CompOpts.getHeaderSearchOpts().Sysroot;
689 if (RelocatablePCH.getValue() && Sysroot.empty()) {
Douglas Gregore650c8c2009-07-07 00:12:59 +0000690 PP.Diag(SourceLocation(), diag::err_relocatable_without_without_isysroot);
691 RelocatablePCH.setValue(false);
692 }
Mike Stump1eb44332009-09-09 15:08:12 +0000693
Daniel Dunbare29709f2009-11-09 20:55:08 +0000694 OS.reset(ComputeOutFile(CompOpts, InFile, 0, true, OutPath));
Douglas Gregore650c8c2009-07-07 00:12:59 +0000695 if (RelocatablePCH.getValue())
Daniel Dunbarf7973292009-11-11 08:13:32 +0000696 Consumer.reset(CreatePCHGenerator(PP, OS.get(), Sysroot.c_str()));
Douglas Gregore650c8c2009-07-07 00:12:59 +0000697 else
698 Consumer.reset(CreatePCHGenerator(PP, OS.get()));
Eli Friedman66d6f042009-05-18 22:20:00 +0000699 CompleteTranslationUnit = false;
700 break;
Daniel Dunbarf7973292009-11-11 08:13:32 +0000701 }
Chris Lattnerc106c102008-10-12 05:03:36 +0000702
Daniel Dunbar8e1bcb02009-11-12 01:36:27 +0000703 // Do any necessary set up for non-consumer actions.
704 case DumpRawTokens:
705 case DumpTokens:
Chris Lattnerd1d64a02009-04-27 21:45:14 +0000706 case RunPreprocessorOnly:
Daniel Dunbar8e1bcb02009-11-12 01:36:27 +0000707 case ParseNoop:
708 break; // No setup.
Mike Stump1eb44332009-09-09 15:08:12 +0000709
Daniel Dunbar8e1bcb02009-11-12 01:36:27 +0000710 case GeneratePTH:
Daniel Dunbare29709f2009-11-09 20:55:08 +0000711 if (CompOpts.getOutputFile().empty() || CompOpts.getOutputFile() == "-") {
Eli Friedmanf54fce82009-05-19 01:02:07 +0000712 // FIXME: Don't fail this way.
713 // FIXME: Verify that we can actually seek in the given file.
Chris Lattner92bcc272009-08-23 02:59:41 +0000714 llvm::errs() << "ERROR: PTH requires an seekable file for output!\n";
Eli Friedmanf54fce82009-05-19 01:02:07 +0000715 ::exit(1);
716 }
Daniel Dunbare29709f2009-11-09 20:55:08 +0000717 OS.reset(ComputeOutFile(CompOpts, InFile, 0, true, OutPath));
Ted Kremenek85888962008-10-21 00:54:44 +0000718 break;
Douglas Gregor6ab35242009-04-09 21:40:53 +0000719
Chris Lattnercc7dea82009-04-27 22:02:30 +0000720 case PrintPreprocessedInput:
Daniel Dunbar8e1bcb02009-11-12 01:36:27 +0000721 case ParsePrintCallbacks:
Chris Lattnerb57e3d42008-05-08 06:52:13 +0000722 case RewriteMacros:
Eli Friedmanf54fce82009-05-19 01:02:07 +0000723 case RewriteTest:
Daniel Dunbare29709f2009-11-09 20:55:08 +0000724 OS.reset(ComputeOutFile(CompOpts, InFile, 0, true, OutPath));
Chris Lattnerb13c5ee2008-10-12 05:29:20 +0000725 break;
Daniel Dunbar387ecbd2009-11-11 10:22:48 +0000726 }
Douglas Gregor558cb562009-04-02 01:08:08 +0000727
Daniel Dunbar387ecbd2009-11-11 10:22:48 +0000728 // Check if we want a fix-it rewriter.
729 if (PA == FixIt || !FixItAtLocations.empty()) {
Douglas Gregorde4bf6a2009-04-02 17:13:00 +0000730 FixItRewrite = new FixItRewriter(PP.getDiagnostics(),
Chris Lattner2c78b872009-04-14 23:22:57 +0000731 PP.getSourceManager(),
732 PP.getLangOptions());
Daniel Dunbar387ecbd2009-11-11 10:22:48 +0000733 if (!FixItAtLocations.empty() &&
734 !AddFixItLocations(FixItRewrite, PP.getFileManager())) {
Chris Lattner1aee61a2009-04-27 21:25:27 +0000735 // All of the fix-it locations were bad. Don't fix anything.
736 delete FixItRewrite;
737 FixItRewrite = 0;
738 }
739 }
740
741 llvm::OwningPtr<ASTContext> ContextOwner;
Daniel Dunbar66068642009-11-12 02:53:13 +0000742 llvm::OwningPtr<ExternalASTSource> Source;
743 const std::string &ImplicitPCHInclude =
744 CompOpts.getPreprocessorOpts().getImplicitPCHInclude();
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000745 if (Consumer) {
Chris Lattner9ecd26a2009-03-28 01:37:17 +0000746 ContextOwner.reset(new ASTContext(PP.getLangOptions(),
747 PP.getSourceManager(),
748 PP.getTargetInfo(),
749 PP.getIdentifierTable(),
750 PP.getSelectorTable(),
Chris Lattner1b63e4f2009-06-14 01:54:56 +0000751 PP.getBuiltinInfo(),
Douglas Gregor2deaea32009-04-22 18:49:13 +0000752 /* FreeMemory = */ !DisableFree,
Chris Lattner1b63e4f2009-06-14 01:54:56 +0000753 /* size_reserve = */0));
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000754
755 if (!ImplicitPCHInclude.empty()) {
756 Source.reset(ReadPCHFile(ImplicitPCHInclude, CompOpts, PP,
757 *ContextOwner));
758 if (!Source)
759 return;
760
761 // Attach the PCH reader to the AST context as an external AST source, so
762 // that declarations will be deserialized from the PCH file as needed.
763 ContextOwner->setExternalSource(Source);
764 } else {
765 // Initialize builtin info when not using PCH.
766 PP.getBuiltinInfo().InitializeBuiltins(PP.getIdentifierTable(),
767 PP.getLangOptions().NoBuiltin);
768 }
769
770 // Initialize the main file entry. This needs to be delayed until after PCH
771 // has loaded.
772 if (InitializeSourceManager(PP, InFile))
Chris Lattnerd1d64a02009-04-27 21:45:14 +0000773 return;
774
Douglas Gregor81b747b2009-09-17 21:32:03 +0000775 CodeCompleteConsumer *(*CreateCodeCompleter)(Sema &, void *) = 0;
776 void *CreateCodeCompleterData = 0;
Daniel Dunbarbea5a842009-10-29 01:53:18 +0000777
Douglas Gregorb657f112009-09-22 21:11:38 +0000778 if (!CodeCompletionAt.FileName.empty()) {
779 // Tell the source manager to chop off the given file at a specific
780 // line and column.
Daniel Dunbarbea5a842009-10-29 01:53:18 +0000781 if (const FileEntry *Entry
Douglas Gregorb657f112009-09-22 21:11:38 +0000782 = PP.getFileManager().getFile(CodeCompletionAt.FileName)) {
783 // Truncate the named file at the given line/column.
784 PP.getSourceManager().truncateFileAt(Entry, CodeCompletionAt.Line,
785 CodeCompletionAt.Column);
Daniel Dunbarbea5a842009-10-29 01:53:18 +0000786
Douglas Gregorb657f112009-09-22 21:11:38 +0000787 // Set up the creation routine for code-completion.
788 CreateCodeCompleter = BuildPrintingCodeCompleter;
789 } else {
Daniel Dunbar0f9fed72009-11-10 23:55:23 +0000790 PP.getDiagnostics().Report(diag::err_fe_invalid_code_complete_file)
Douglas Gregorb657f112009-09-22 21:11:38 +0000791 << CodeCompletionAt.FileName;
792 }
Douglas Gregor81b747b2009-09-17 21:32:03 +0000793 }
794
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000795 // Run the AST consumer action.
Mike Stump1eb44332009-09-09 15:08:12 +0000796 ParseAST(PP, Consumer.get(), *ContextOwner.get(), Stats,
Douglas Gregor81b747b2009-09-17 21:32:03 +0000797 CompleteTranslationUnit,
798 CreateCodeCompleter, CreateCodeCompleterData);
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000799 } else {
800 // Initialize builtin info.
801 PP.getBuiltinInfo().InitializeBuiltins(PP.getIdentifierTable(),
802 PP.getLangOptions().NoBuiltin);
Chris Lattnerd1d64a02009-04-27 21:45:14 +0000803
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000804 // Initialize the main file entry. This needs to be delayed until after PCH
805 // has loaded.
806 if (InitializeSourceManager(PP, InFile))
807 return;
Daniel Dunbar593c41f2009-11-04 23:41:40 +0000808
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000809 // Run the preprocessor actions.
Daniel Dunbarc67a5f92009-11-12 02:53:34 +0000810 llvm::TimeRegion Timer(ClangFrontendTimer);
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000811 switch (PA) {
812 default:
813 assert(0 && "unexpected program action");
Daniel Dunbar8e1bcb02009-11-12 01:36:27 +0000814
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000815 case DumpRawTokens: {
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000816 SourceManager &SM = PP.getSourceManager();
817 // Start lexing the specified input file.
818 Lexer RawLex(SM.getMainFileID(), SM, PP.getLangOptions());
819 RawLex.SetKeepWhitespaceMode(true);
820
821 Token RawTok;
Daniel Dunbar8e1bcb02009-11-12 01:36:27 +0000822 RawLex.LexFromRawLexer(RawTok);
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000823 while (RawTok.isNot(tok::eof)) {
824 PP.DumpToken(RawTok, true);
825 fprintf(stderr, "\n");
826 RawLex.LexFromRawLexer(RawTok);
827 }
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000828 break;
Daniel Dunbar8e1bcb02009-11-12 01:36:27 +0000829 }
Daniel Dunbar8e1bcb02009-11-12 01:36:27 +0000830
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000831 case DumpTokens: {
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000832 Token Tok;
833 // Start preprocessing the specified input file.
834 PP.EnterMainSourceFile();
835 do {
836 PP.Lex(Tok);
837 PP.DumpToken(Tok, true);
838 fprintf(stderr, "\n");
839 } while (Tok.isNot(tok::eof));
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000840 break;
841 }
Daniel Dunbar593c41f2009-11-04 23:41:40 +0000842
Daniel Dunbarc67a5f92009-11-12 02:53:34 +0000843 case GeneratePTH:
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000844 CacheTokens(PP, static_cast<llvm::raw_fd_ostream*>(OS.get()));
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000845 break;
Daniel Dunbar8e1bcb02009-11-12 01:36:27 +0000846
Daniel Dunbarc67a5f92009-11-12 02:53:34 +0000847 case ParseNoop:
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000848 ParseFile(PP, new MinimalAction(PP));
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000849 break;
Daniel Dunbar593c41f2009-11-04 23:41:40 +0000850
Daniel Dunbarc67a5f92009-11-12 02:53:34 +0000851 case ParsePrintCallbacks:
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000852 ParseFile(PP, CreatePrintParserActionsAction(PP, OS.get()));
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000853 break;
Daniel Dunbar8e1bcb02009-11-12 01:36:27 +0000854
Daniel Dunbarc67a5f92009-11-12 02:53:34 +0000855 case PrintPreprocessedInput:
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000856 DoPrintPreprocessedInput(PP, OS.get(),
857 CompOpts.getPreprocessorOutputOpts());
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000858 break;
Daniel Dunbar8e1bcb02009-11-12 01:36:27 +0000859
Daniel Dunbarc67a5f92009-11-12 02:53:34 +0000860 case RewriteMacros:
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000861 RewriteMacrosInInput(PP, OS.get());
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000862 break;
Daniel Dunbar8e1bcb02009-11-12 01:36:27 +0000863
Daniel Dunbarc67a5f92009-11-12 02:53:34 +0000864 case RewriteTest:
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000865 DoRewriteTest(PP, OS.get());
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000866 break;
Daniel Dunbar8e1bcb02009-11-12 01:36:27 +0000867
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000868 case RunPreprocessorOnly: { // Just lex as fast as we can, no output.
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000869 Token Tok;
870 // Start parsing the specified input file.
871 PP.EnterMainSourceFile();
872 do {
873 PP.Lex(Tok);
874 } while (Tok.isNot(tok::eof));
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000875 break;
876 }
Daniel Dunbard1e7a962009-11-12 02:53:27 +0000877 }
Daniel Dunbarc67a5f92009-11-12 02:53:34 +0000878
879 ClearSourceMgr = true;
Daniel Dunbar593c41f2009-11-04 23:41:40 +0000880 }
881
Chris Lattner1aee61a2009-04-27 21:25:27 +0000882 if (FixItRewrite)
Daniel Dunbare29709f2009-11-09 20:55:08 +0000883 FixItRewrite->WriteFixedFile(InFile, CompOpts.getOutputFile());
Daniel Dunbar70186ab2009-07-29 02:40:09 +0000884
Daniel Dunbarc8daaa42009-11-12 00:24:28 +0000885 // Release the consumer and the AST, in that order since the consumer may
886 // perform actions in its destructor which require the context.
887 if (DisableFree) {
Daniel Dunbar70186ab2009-07-29 02:40:09 +0000888 Consumer.take();
Chris Lattner1aee61a2009-04-27 21:25:27 +0000889 ContextOwner.take();
Daniel Dunbarc8daaa42009-11-12 00:24:28 +0000890 } else {
891 Consumer.reset();
892 ContextOwner.reset();
893 }
Eli Friedman66d6f042009-05-18 22:20:00 +0000894
Daniel Dunbar879c3ea2008-10-27 22:03:52 +0000895 if (VerifyDiagnostics)
Daniel Dunbar276373d2008-10-27 22:10:13 +0000896 if (CheckDiagnostics(PP))
897 exit(1);
Chris Lattnere66b65c2008-02-06 01:42:25 +0000898
Reid Spencer5f016e22007-07-11 17:01:13 +0000899 if (Stats) {
Ted Kremenekfdfc1982007-12-19 22:24:34 +0000900 fprintf(stderr, "\nSTATISTICS FOR '%s':\n", InFile.c_str());
Reid Spencer5f016e22007-07-11 17:01:13 +0000901 PP.PrintStats();
902 PP.getIdentifierTable().PrintStats();
Chris Lattnerdee73592007-12-15 20:48:40 +0000903 PP.getHeaderSearchInfo().PrintStats();
Ted Kremenek1b95a652009-01-09 18:20:21 +0000904 PP.getSourceManager().PrintStats();
Reid Spencer5f016e22007-07-11 17:01:13 +0000905 fprintf(stderr, "\n");
906 }
Chris Lattnerbd247762007-07-22 06:05:44 +0000907
Mike Stump1eb44332009-09-09 15:08:12 +0000908 // For a multi-file compilation, some things are ok with nuking the source
Chris Lattnerbd247762007-07-22 06:05:44 +0000909 // manager tables, other require stable fileid/macroid's across multiple
910 // files.
Chris Lattnerdee73592007-12-15 20:48:40 +0000911 if (ClearSourceMgr)
912 PP.getSourceManager().clearIDTables();
Daniel Dunbard68ba0e2008-11-11 06:35:39 +0000913
Eli Friedman66d6f042009-05-18 22:20:00 +0000914 // Always delete the output stream because we don't want to leak file
915 // handles. Also, we don't want to try to erase an open file.
916 OS.reset();
917
Daniel Dunbar8cb65622009-10-29 21:05:18 +0000918 // If we had errors, try to erase the output file.
919 if (PP.getDiagnostics().getNumErrors() && !OutPath.isEmpty())
Eli Friedman66d6f042009-05-18 22:20:00 +0000920 OutPath.eraseFromDisk();
Reid Spencer5f016e22007-07-11 17:01:13 +0000921}
922
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +0000923/// ProcessInputFile - Process a single AST input file with the specified state.
924///
Daniel Dunbare29709f2009-11-09 20:55:08 +0000925static void ProcessASTInputFile(const CompilerInvocation &CompOpts,
926 const std::string &InFile, ProgActions PA,
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +0000927 Diagnostic &Diags, FileManager &FileMgr,
928 llvm::LLVMContext& Context) {
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +0000929 std::string Error;
Steve Naroff36c44642009-10-19 14:34:22 +0000930 llvm::OwningPtr<ASTUnit> AST(ASTUnit::LoadFromPCHFile(InFile, &Error));
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +0000931 if (!AST) {
Daniel Dunbar0f9fed72009-11-10 23:55:23 +0000932 Diags.Report(diag::err_fe_invalid_ast_file) << Error;
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +0000933 return;
934 }
935
936 Preprocessor &PP = AST->getPreprocessor();
937
938 llvm::OwningPtr<llvm::raw_ostream> OS;
939 llvm::sys::Path OutPath;
Daniel Dunbarc8daaa42009-11-12 00:24:28 +0000940 llvm::OwningPtr<ASTConsumer> Consumer(CreateConsumerAction(CompOpts, PP,
Daniel Dunbare29709f2009-11-09 20:55:08 +0000941 InFile, PA, OS,
Daniel Dunbar26a0cac2009-11-09 22:46:17 +0000942 OutPath, Context));
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +0000943 if (!Consumer.get()) {
Daniel Dunbar0f9fed72009-11-10 23:55:23 +0000944 Diags.Report(diag::err_fe_invalid_ast_action);
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +0000945 return;
946 }
947
Daniel Dunbara674bf42009-09-21 03:03:56 +0000948 // Set the main file ID to an empty file.
949 //
950 // FIXME: We probably shouldn't need this, but for now this is the simplest
951 // way to reuse the logic in ParseAST.
952 const char *EmptyStr = "";
953 llvm::MemoryBuffer *SB =
954 llvm::MemoryBuffer::getMemBuffer(EmptyStr, EmptyStr, "<dummy input>");
955 AST->getSourceManager().createMainFileIDForMemBuffer(SB);
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +0000956
Daniel Dunbara674bf42009-09-21 03:03:56 +0000957 // Stream the input AST to the consumer.
Daniel Dunbarefcbe942009-11-05 02:42:12 +0000958 Diags.getClient()->BeginSourceFile(PP.getLangOptions());
Daniel Dunbara674bf42009-09-21 03:03:56 +0000959 ParseAST(PP, Consumer.get(), AST->getASTContext(), Stats);
Daniel Dunbarefcbe942009-11-05 02:42:12 +0000960 Diags.getClient()->EndSourceFile();
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +0000961
962 // Release the consumer and the AST, in that order since the consumer may
963 // perform actions in its destructor which require the context.
964 if (DisableFree) {
965 Consumer.take();
966 AST.take();
967 } else {
968 Consumer.reset();
969 AST.reset();
970 }
971
972 // Always delete the output stream because we don't want to leak file
973 // handles. Also, we don't want to try to erase an open file.
974 OS.reset();
975
Daniel Dunbar8cb65622009-10-29 21:05:18 +0000976 // If we had errors, try to erase the output file.
977 if (PP.getDiagnostics().getNumErrors() && !OutPath.isEmpty())
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +0000978 OutPath.eraseFromDisk();
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +0000979}
980
Daniel Dunbar70121eb2009-08-10 03:40:28 +0000981static void LLVMErrorHandler(void *UserData, const std::string &Message) {
982 Diagnostic &Diags = *static_cast<Diagnostic*>(UserData);
983
Daniel Dunbar0f9fed72009-11-10 23:55:23 +0000984 Diags.Report(diag::err_fe_error_backend) << Message;
Daniel Dunbar70121eb2009-08-10 03:40:28 +0000985
986 // We cannot recover from llvm errors.
987 exit(1);
988}
989
Daniel Dunbar227b2382009-11-09 22:45:57 +0000990static LangKind GetLanguage() {
991 // If -x was given, that's the language.
992 if (BaseLang != langkind_unspecified)
993 return BaseLang;
Daniel Dunbare29709f2009-11-09 20:55:08 +0000994
Daniel Dunbar227b2382009-11-09 22:45:57 +0000995 // Otherwise guess it from the input filenames;
996 LangKind LK = langkind_unspecified;
997 for (unsigned i = 0, e = InputFilenames.size(); i != e; ++i) {
998 llvm::StringRef Name(InputFilenames[i]);
999 LangKind ThisKind = llvm::StringSwitch<LangKind>(Name.rsplit('.').second)
1000 .Case("ast", langkind_ast)
1001 .Case("c", langkind_c)
1002 .Cases("S", "s", langkind_asm_cpp)
1003 .Case("i", langkind_c_cpp)
1004 .Case("ii", langkind_cxx_cpp)
1005 .Case("m", langkind_objc)
1006 .Case("mi", langkind_objc_cpp)
1007 .Cases("mm", "M", langkind_objcxx)
1008 .Case("mii", langkind_objcxx_cpp)
1009 .Case("C", langkind_cxx)
1010 .Cases("C", "cc", "cp", langkind_cxx)
1011 .Cases("cpp", "CPP", "c++", "cxx", langkind_cxx)
1012 .Case("cl", langkind_ocl)
1013 .Default(langkind_c);
1014
1015 if (LK != langkind_unspecified && ThisKind != LK) {
1016 llvm::errs() << "error: cannot have multiple input files of distinct "
1017 << "language kinds without -x\n";
1018 exit(1);
1019 }
1020
1021 LK = ThisKind;
1022 }
1023
1024 return LK;
1025}
1026
Daniel Dunbar0498cfc2009-11-10 19:51:53 +00001027static void FinalizeCompileOptions(CompileOptions &Opts,
1028 const LangOptions &Lang) {
1029 if (Lang.NoBuiltin)
1030 Opts.SimplifyLibCalls = 0;
1031 if (Lang.CPlusPlus)
1032 Opts.NoCommon = 1;
1033
1034 // Handle -ftime-report.
1035 Opts.TimePasses = TimeReport;
1036}
1037
Daniel Dunbar227b2382009-11-09 22:45:57 +00001038static void ConstructCompilerInvocation(CompilerInvocation &Opts,
Daniel Dunbar26a0cac2009-11-09 22:46:17 +00001039 const char *Argv0,
Daniel Dunbar227b2382009-11-09 22:45:57 +00001040 const DiagnosticOptions &DiagOpts,
Daniel Dunbar26a0cac2009-11-09 22:46:17 +00001041 TargetInfo &Target,
1042 LangKind LK) {
Daniel Dunbar227b2382009-11-09 22:45:57 +00001043 Opts.getDiagnosticOpts() = DiagOpts;
1044
1045 Opts.getOutputFile() = OutputFile;
Daniel Dunbar26a0cac2009-11-09 22:46:17 +00001046
Daniel Dunbarfcb0c3b2009-11-10 18:47:35 +00001047 // Initialize backend options, which may also be used to key some language
1048 // options.
Daniel Dunbar29a790b2009-11-11 09:38:56 +00001049 InitializeCompileOptions(Opts.getCompileOpts(), Target);
Daniel Dunbarfcb0c3b2009-11-10 18:47:35 +00001050
Daniel Dunbar26a0cac2009-11-09 22:46:17 +00001051 // Initialize language options.
Daniel Dunbar5746f1f2009-11-12 00:24:10 +00001052 //
Daniel Dunbar26a0cac2009-11-09 22:46:17 +00001053 // FIXME: These aren't used during operations on ASTs. Split onto a separate
1054 // code path to make this obvious.
Daniel Dunbar56749082009-11-11 07:26:12 +00001055 if (LK != langkind_ast)
1056 InitializeLangOptions(Opts.getLangOpts(), LK, Target,
Daniel Dunbar29a790b2009-11-11 09:38:56 +00001057 Opts.getCompileOpts());
Daniel Dunbar26a0cac2009-11-09 22:46:17 +00001058
Daniel Dunbar5746f1f2009-11-12 00:24:10 +00001059 // Initialize the static analyzer options.
1060 InitializeAnalyzerOptions(Opts.getAnalyzerOpts());
1061
Daniel Dunbar0e0bae82009-11-11 21:43:12 +00001062 // Initialize the dependency output options (-M...).
1063 InitializeDependencyOutputOptions(Opts.getDependencyOutputOpts());
1064
Daniel Dunbar26a0cac2009-11-09 22:46:17 +00001065 // Initialize the header search options.
Daniel Dunbarf7973292009-11-11 08:13:32 +00001066 InitializeHeaderSearchOptions(Opts.getHeaderSearchOpts(),
1067 GetBuiltinIncludePath(Argv0),
1068 Verbose,
1069 Opts.getLangOpts());
Daniel Dunbar5fc7d342009-11-09 23:12:31 +00001070
1071 // Initialize the other preprocessor options.
1072 InitializePreprocessorOptions(Opts.getPreprocessorOpts());
Daniel Dunbar36f4ec32009-11-10 16:19:45 +00001073
Daniel Dunbar29cf7462009-11-11 10:07:44 +00001074 // Initialize the preprocessed output options.
1075 InitializePreprocessorOutputOptions(Opts.getPreprocessorOutputOpts());
1076
Daniel Dunbar0498cfc2009-11-10 19:51:53 +00001077 // Finalize some code generation options.
Daniel Dunbarfcb0c3b2009-11-10 18:47:35 +00001078 FinalizeCompileOptions(Opts.getCompileOpts(), Opts.getLangOpts());
Daniel Dunbare29709f2009-11-09 20:55:08 +00001079}
1080
Reid Spencer5f016e22007-07-11 17:01:13 +00001081int main(int argc, char **argv) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001082 llvm::sys::PrintStackTraceOnErrorSignal();
Chris Lattner09e94a32009-03-04 21:41:39 +00001083 llvm::PrettyStackTraceProgram X(argc, argv);
Owen Andersond7200462009-07-16 00:14:12 +00001084 llvm::LLVMContext &Context = llvm::getGlobalContext();
Daniel Dunbard6970812009-09-02 23:20:15 +00001085
Daniel Dunbar4d861512009-09-03 04:54:12 +00001086 // Initialize targets first, so that --version shows registered targets.
Chris Lattner2fe11942009-06-17 17:25:50 +00001087 llvm::InitializeAllTargets();
1088 llvm::InitializeAllAsmPrinters();
Daniel Dunbard6970812009-09-02 23:20:15 +00001089
1090 llvm::cl::ParseCommandLineOptions(argc, argv,
1091 "LLVM 'Clang' Compiler: http://clang.llvm.org\n");
Mike Stump1eb44332009-09-09 15:08:12 +00001092
Chris Lattner47099742009-02-18 01:51:21 +00001093 if (TimeReport)
1094 ClangFrontendTimer = new llvm::Timer("Clang front-end time");
Mike Stump1eb44332009-09-09 15:08:12 +00001095
Daniel Dunbar08e6dc62009-05-28 16:37:33 +00001096 if (Verbose)
Mike Stump3cbf5a02009-09-15 21:49:22 +00001097 llvm::errs() << "clang-cc version " CLANG_VERSION_STRING
1098 << " based upon " << PACKAGE_STRING
Daniel Dunbar2e30e592009-09-04 17:43:10 +00001099 << " hosted on " << llvm::sys::getHostTriple() << "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00001100
Reid Spencer5f016e22007-07-11 17:01:13 +00001101 // If no input was specified, read from stdin.
1102 if (InputFilenames.empty())
1103 InputFilenames.push_back("-");
Douglas Gregor68a0d782009-05-02 00:03:46 +00001104
Daniel Dunbar227b2382009-11-09 22:45:57 +00001105 // Construct the diagnostic options first, which cannot fail, so that we can
1106 // build a diagnostic client to use for any errors during option handling.
1107 DiagnosticOptions DiagOpts;
Daniel Dunbar0db4b762009-11-11 08:13:40 +00001108 InitializeDiagnosticOptions(DiagOpts);
Daniel Dunbareace8742009-11-04 06:24:30 +00001109
Ted Kremenek31e703b2007-12-11 23:28:38 +00001110 // Create the diagnostic client for reporting errors or for
1111 // implementing -verify.
Chris Lattner409d4e72009-04-17 20:40:01 +00001112 llvm::OwningPtr<DiagnosticClient> DiagClient;
1113 if (VerifyDiagnostics) {
1114 // When checking diagnostics, just buffer them up.
1115 DiagClient.reset(new TextDiagnosticBuffer());
1116 if (InputFilenames.size() != 1) {
Daniel Dunbar227b2382009-11-09 22:45:57 +00001117 fprintf(stderr, "-verify only works on single input files.\n");
Chris Lattner409d4e72009-04-17 20:40:01 +00001118 return 1;
1119 }
Ted Kremenekb4398aa2008-08-07 17:49:57 +00001120 } else {
Daniel Dunbar227b2382009-11-09 22:45:57 +00001121 DiagClient.reset(new TextDiagnosticPrinter(llvm::errs(), DiagOpts));
Reid Spencer5f016e22007-07-11 17:01:13 +00001122 }
Mike Stump1eb44332009-09-09 15:08:12 +00001123
Daniel Dunbarad451cc2009-11-05 02:11:37 +00001124 if (!DumpBuildInformation.empty())
Daniel Dunbar227b2382009-11-09 22:45:57 +00001125 SetUpBuildDumpLog(DiagOpts, argc, argv, DiagClient);
Ted Kremenekb4398aa2008-08-07 17:49:57 +00001126
Reid Spencer5f016e22007-07-11 17:01:13 +00001127 // Configure our handling of diagnostics.
Ted Kremenekb4398aa2008-08-07 17:49:57 +00001128 Diagnostic Diags(DiagClient.get());
Eli Friedman0eeb86e2009-05-19 01:17:04 +00001129 if (ProcessWarningOptions(Diags, OptWarnings, OptPedantic, OptPedanticErrors,
1130 OptNoWarnings))
Sebastian Redl63a9e0f2009-03-06 17:41:35 +00001131 return 1;
Ted Kremenek31e703b2007-12-11 23:28:38 +00001132
Daniel Dunbar70121eb2009-08-10 03:40:28 +00001133 // Set an error handler, so that any LLVM backend diagnostics go through our
1134 // error handler.
1135 llvm::llvm_install_error_handler(LLVMErrorHandler,
1136 static_cast<void*>(&Diags));
1137
Daniel Dunbar7c15e712009-10-30 18:12:31 +00001138 // Initialize base triple. If a -triple option has been specified, use
1139 // that triple. Otherwise, default to the host triple.
1140 llvm::Triple Triple(TargetTriple);
1141 if (Triple.getTriple().empty())
1142 Triple = llvm::Triple(llvm::sys::getHostTriple());
1143
Chris Lattner11215192008-03-14 06:12:05 +00001144 // Get information about the target being compiled for.
Daniel Dunbarbea5a842009-10-29 01:53:18 +00001145 llvm::OwningPtr<TargetInfo>
Chris Lattner2f60af72009-09-12 22:45:58 +00001146 Target(TargetInfo::CreateTargetInfo(Triple.getTriple()));
Mike Stump1eb44332009-09-09 15:08:12 +00001147
Chris Lattner11215192008-03-14 06:12:05 +00001148 if (Target == 0) {
Daniel Dunbar0f9fed72009-11-10 23:55:23 +00001149 Diags.Report(diag::err_fe_unknown_triple) << Triple.getTriple().c_str();
Sebastian Redlc5613db2009-03-07 12:09:25 +00001150 return 1;
Chris Lattner11215192008-03-14 06:12:05 +00001151 }
Mike Stump1eb44332009-09-09 15:08:12 +00001152
Daniel Dunbar73b79592009-09-14 00:02:12 +00001153 // Set the target ABI if specified.
1154 if (!TargetABI.empty()) {
1155 if (!Target->setABI(TargetABI)) {
Daniel Dunbar0f9fed72009-11-10 23:55:23 +00001156 Diags.Report(diag::err_fe_unknown_target_abi) << TargetABI;
Daniel Dunbar73b79592009-09-14 00:02:12 +00001157 return 1;
1158 }
1159 }
1160
Daniel Dunbard4270232009-01-20 23:17:32 +00001161 if (!InheritanceViewCls.empty()) // C++ visualization?
Ted Kremenek7cae2f62008-10-23 23:36:29 +00001162 ProgAction = InheritanceView;
Mike Stump1eb44332009-09-09 15:08:12 +00001163
Daniel Dunbar227b2382009-11-09 22:45:57 +00001164 // Infer the input language.
1165 //
1166 // FIXME: We should move .ast inputs to taking a separate path, they are
1167 // really quite different.
1168 LangKind LK = GetLanguage();
1169
1170 // Now that we have initialized the diagnostics engine and the target, finish
1171 // setting up the compiler invocation.
1172 CompilerInvocation CompOpts;
Daniel Dunbar26a0cac2009-11-09 22:46:17 +00001173 ConstructCompilerInvocation(CompOpts, argv[0], DiagOpts, *Target, LK);
Daniel Dunbar227b2382009-11-09 22:45:57 +00001174
Daniel Dunbar4cc1a252009-11-05 01:53:23 +00001175 // Create the source manager.
1176 SourceManager SourceMgr;
Mike Stump1eb44332009-09-09 15:08:12 +00001177
Chris Lattner2c78b872009-04-14 23:22:57 +00001178 // Create a file manager object to provide access to and cache the filesystem.
1179 FileManager FileMgr;
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001180
Reid Spencer5f016e22007-07-11 17:01:13 +00001181 for (unsigned i = 0, e = InputFilenames.size(); i != e; ++i) {
Ted Kremenek31e703b2007-12-11 23:28:38 +00001182 const std::string &InFile = InputFilenames[i];
Mike Stump1eb44332009-09-09 15:08:12 +00001183
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +00001184 // AST inputs are handled specially.
1185 if (LK == langkind_ast) {
Daniel Dunbar26a0cac2009-11-09 22:46:17 +00001186 ProcessASTInputFile(CompOpts, InFile, ProgAction, Diags, FileMgr,
1187 Context);
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +00001188 continue;
1189 }
1190
Daniel Dunbar4cc1a252009-11-05 01:53:23 +00001191 // Reset the ID tables if we are reusing the SourceManager.
1192 if (i)
1193 SourceMgr.clearIDTables();
Mike Stump1eb44332009-09-09 15:08:12 +00001194
Chris Lattnerf63aea32009-03-04 21:40:56 +00001195 // Set up the preprocessor with these options.
Daniel Dunbar5fc7d342009-11-09 23:12:31 +00001196 llvm::OwningPtr<Preprocessor>
1197 PP(CreatePreprocessor(Diags, CompOpts.getLangOpts(),
Daniel Dunbarca11f612009-11-11 21:44:00 +00001198 CompOpts.getPreprocessorOpts(),
Daniel Dunbar961c76e2009-11-11 21:44:42 +00001199 CompOpts.getHeaderSearchOpts(),
Daniel Dunbarca11f612009-11-11 21:44:00 +00001200 CompOpts.getDependencyOutputOpts(),
Daniel Dunbar5814e652009-11-11 21:44:21 +00001201 *Target, SourceMgr, FileMgr));
1202
Chris Lattnerf63aea32009-03-04 21:40:56 +00001203 // Process the source file.
Daniel Dunbar26a0cac2009-11-09 22:46:17 +00001204 Diags.getClient()->BeginSourceFile(CompOpts.getLangOpts());
1205 ProcessInputFile(CompOpts, *PP, InFile, ProgAction, Context);
Daniel Dunbar227b2382009-11-09 22:45:57 +00001206 Diags.getClient()->EndSourceFile();
Reid Spencer5f016e22007-07-11 17:01:13 +00001207 }
Chris Lattner11215192008-03-14 06:12:05 +00001208
Daniel Dunbar9253e492009-11-10 00:46:12 +00001209 if (CompOpts.getDiagnosticOpts().ShowCarets)
Mike Stumpfc0fed32009-04-28 01:19:10 +00001210 if (unsigned NumDiagnostics = Diags.getNumDiagnostics())
1211 fprintf(stderr, "%d diagnostic%s generated.\n", NumDiagnostics,
1212 (NumDiagnostics == 1 ? "" : "s"));
Mike Stump1eb44332009-09-09 15:08:12 +00001213
Reid Spencer5f016e22007-07-11 17:01:13 +00001214 if (Stats) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001215 FileMgr.PrintStats();
1216 fprintf(stderr, "\n");
1217 }
Chris Lattner75a97cb2009-04-17 21:05:01 +00001218
1219 delete ClangFrontendTimer;
Mike Stump1eb44332009-09-09 15:08:12 +00001220
Daniel Dunbar276373d2008-10-27 22:10:13 +00001221 // If verifying diagnostics and we reached here, all is well.
1222 if (VerifyDiagnostics)
1223 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001224
Daniel Dunbar524b86f2008-10-28 00:38:08 +00001225 // Managed static deconstruction. Useful for making things like
1226 // -time-passes usable.
1227 llvm::llvm_shutdown();
1228
Daniel Dunbar8cb65622009-10-29 21:05:18 +00001229 return (Diags.getNumErrors() != 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00001230}