blob: 9ef08774561579aa51a5b3f5794f6545c36c3732 [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:
220 return new PrintingCodeCompleteConsumer(S, CodeCompletionWantsMacros,
221 llvm::outs());
222
223 case CCP_CIndex:
224 return new CIndexCodeCompleteConsumer(S, CodeCompletionWantsMacros,
225 llvm::outs());
226 };
227
228 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 Dunbard1cdcf32009-11-11 08:13:47 +0000257static llvm::cl::opt<std::string>
258TokenCache("token-cache", llvm::cl::value_desc("path"),
259 llvm::cl::desc("Use specified token cache file"));
260
Daniel Dunbar0db4b762009-11-11 08:13:40 +0000261static llvm::cl::opt<bool>
262VerifyDiagnostics("verify",
263 llvm::cl::desc("Verify emitted diagnostics and warnings"));
264
Douglas Gregor3573c0c2009-02-14 20:49:29 +0000265//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +0000266// Language Options
267//===----------------------------------------------------------------------===//
268
Reid Spencer5f016e22007-07-11 17:01:13 +0000269static llvm::cl::opt<LangKind>
270BaseLang("x", llvm::cl::desc("Base language to compile"),
271 llvm::cl::init(langkind_unspecified),
272 llvm::cl::values(clEnumValN(langkind_c, "c", "C"),
Nate Begeman4e3629e2009-06-25 22:43:10 +0000273 clEnumValN(langkind_ocl, "cl", "OpenCL C"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000274 clEnumValN(langkind_cxx, "c++", "C++"),
275 clEnumValN(langkind_objc, "objective-c", "Objective C"),
276 clEnumValN(langkind_objcxx,"objective-c++","Objective C++"),
Daniel Dunbard2ea3862009-01-29 23:50:47 +0000277 clEnumValN(langkind_c_cpp, "cpp-output",
Reid Spencer5f016e22007-07-11 17:01:13 +0000278 "Preprocessed C"),
Chris Lattnera778d7d2008-10-22 17:29:21 +0000279 clEnumValN(langkind_asm_cpp, "assembler-with-cpp",
280 "Preprocessed asm"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000281 clEnumValN(langkind_cxx_cpp, "c++-cpp-output",
Chris Lattnerc76d8072009-02-06 06:19:20 +0000282 "Preprocessed C++"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000283 clEnumValN(langkind_objc_cpp, "objective-c-cpp-output",
284 "Preprocessed Objective C"),
Chris Lattnerc76d8072009-02-06 06:19:20 +0000285 clEnumValN(langkind_objcxx_cpp, "objective-c++-cpp-output",
Reid Spencer5f016e22007-07-11 17:01:13 +0000286 "Preprocessed Objective C++"),
Daniel Dunbar0b5b0da2009-04-01 05:09:09 +0000287 clEnumValN(langkind_c, "c-header",
288 "C header"),
289 clEnumValN(langkind_objc, "objective-c-header",
290 "Objective-C header"),
291 clEnumValN(langkind_cxx, "c++-header",
292 "C++ header"),
293 clEnumValN(langkind_objcxx, "objective-c++-header",
294 "Objective-C++ header"),
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +0000295 clEnumValN(langkind_ast, "ast",
296 "Clang AST"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000297 clEnumValEnd));
298
Daniel Dunbar7c15e712009-10-30 18:12:31 +0000299static llvm::cl::opt<std::string>
300TargetTriple("triple",
301 llvm::cl::desc("Specify target triple (e.g. i686-apple-darwin9)"));
302
Daniel Dunbar56749082009-11-11 07:26:12 +0000303static llvm::cl::opt<std::string>
304TargetABI("target-abi",
305 llvm::cl::desc("Target a particular ABI type"));
Reid Spencer5f016e22007-07-11 17:01:13 +0000306
307//===----------------------------------------------------------------------===//
Chris Lattnere116ccf2009-04-21 05:40:52 +0000308// SourceManager initialization.
Reid Spencer5f016e22007-07-11 17:01:13 +0000309//===----------------------------------------------------------------------===//
310
Douglas Gregore1d918e2009-04-10 23:10:45 +0000311static bool InitializeSourceManager(Preprocessor &PP,
312 const std::string &InFile) {
313 // Figure out where to get and map in the main file.
314 SourceManager &SourceMgr = PP.getSourceManager();
315 FileManager &FileMgr = PP.getFileManager();
Daniel Dunbar57cbfc02009-04-27 21:19:07 +0000316
317 if (EmptyInputOnly) {
318 const char *EmptyStr = "";
Mike Stump1eb44332009-09-09 15:08:12 +0000319 llvm::MemoryBuffer *SB =
Daniel Dunbar57cbfc02009-04-27 21:19:07 +0000320 llvm::MemoryBuffer::getMemBuffer(EmptyStr, EmptyStr, "<empty input>");
321 SourceMgr.createMainFileIDForMemBuffer(SB);
322 } else if (InFile != "-") {
Douglas Gregore1d918e2009-04-10 23:10:45 +0000323 const FileEntry *File = FileMgr.getFile(InFile);
324 if (File) SourceMgr.createMainFileID(File, SourceLocation());
325 if (SourceMgr.getMainFileID().isInvalid()) {
Daniel Dunbar0f9fed72009-11-10 23:55:23 +0000326 PP.getDiagnostics().Report(diag::err_fe_error_reading) << InFile.c_str();
Douglas Gregore1d918e2009-04-10 23:10:45 +0000327 return true;
328 }
329 } else {
330 llvm::MemoryBuffer *SB = llvm::MemoryBuffer::getSTDIN();
Douglas Gregore1d918e2009-04-10 23:10:45 +0000331 SourceMgr.createMainFileIDForMemBuffer(SB);
332 if (SourceMgr.getMainFileID().isInvalid()) {
Daniel Dunbar0f9fed72009-11-10 23:55:23 +0000333 PP.getDiagnostics().Report(diag::err_fe_error_reading_stdin);
Douglas Gregore1d918e2009-04-10 23:10:45 +0000334 return true;
335 }
336 }
337
338 return false;
339}
340
Chris Lattneraa391972008-04-19 23:09:31 +0000341
Chris Lattnere116ccf2009-04-21 05:40:52 +0000342//===----------------------------------------------------------------------===//
343// Preprocessor Initialization
344//===----------------------------------------------------------------------===//
Sam Bishop1102d6b2008-04-14 14:41:57 +0000345
Chris Lattnere6113de2009-11-03 19:50:27 +0000346static llvm::cl::opt<bool>
Mike Stump1eb44332009-09-09 15:08:12 +0000347RelocatablePCH("relocatable-pch",
Douglas Gregore650c8c2009-07-07 00:12:59 +0000348 llvm::cl::desc("Whether to build a relocatable precompiled "
349 "header"));
Reid Spencer5f016e22007-07-11 17:01:13 +0000350
Reid Spencer5f016e22007-07-11 17:01:13 +0000351// Finally, implement the code that groks the options above.
Chris Lattner5f9eae52008-03-01 08:07:28 +0000352
Rafael Espindola1bb15a92009-10-05 13:12:17 +0000353// Add the clang headers, which are relative to the clang binary.
Daniel Dunbar750156a2009-11-07 04:19:57 +0000354std::string GetBuiltinIncludePath(const char *Argv0) {
355 llvm::sys::Path P =
356 llvm::sys::Path::GetMainExecutable(Argv0,
357 (void*)(intptr_t) GetBuiltinIncludePath);
Rafael Espindola1bb15a92009-10-05 13:12:17 +0000358
Daniel Dunbar750156a2009-11-07 04:19:57 +0000359 if (!P.isEmpty()) {
360 P.eraseComponent(); // Remove /clang from foo/bin/clang
361 P.eraseComponent(); // Remove /bin from foo/bin
Rafael Espindola1bb15a92009-10-05 13:12:17 +0000362
Daniel Dunbar750156a2009-11-07 04:19:57 +0000363 // Get foo/lib/clang/<version>/include
364 P.appendComponent("lib");
365 P.appendComponent("clang");
366 P.appendComponent(CLANG_VERSION_STRING);
367 P.appendComponent("include");
368 }
Rafael Espindola1bb15a92009-10-05 13:12:17 +0000369
Daniel Dunbar750156a2009-11-07 04:19:57 +0000370 return P.str();
Rafael Espindola1bb15a92009-10-05 13:12:17 +0000371}
372
Ted Kremeneka42cf2e2008-04-17 21:38:34 +0000373//===----------------------------------------------------------------------===//
Daniel Dunbar90b18272009-11-04 23:56:25 +0000374// Preprocessor construction
Ted Kremeneka42cf2e2008-04-17 21:38:34 +0000375//===----------------------------------------------------------------------===//
376
Daniel Dunbar90b18272009-11-04 23:56:25 +0000377static Preprocessor *
Daniel Dunbar5fc7d342009-11-09 23:12:31 +0000378CreatePreprocessor(Diagnostic &Diags, const LangOptions &LangInfo,
Daniel Dunbarca11f612009-11-11 21:44:00 +0000379 const PreprocessorOptions &PPOpts,
Daniel Dunbar961c76e2009-11-11 21:44:42 +0000380 const HeaderSearchOptions &HSOpts,
Daniel Dunbarca11f612009-11-11 21:44:00 +0000381 const DependencyOutputOptions &DepOpts,
382 TargetInfo &Target, SourceManager &SourceMgr,
Daniel Dunbar5814e652009-11-11 21:44:21 +0000383 FileManager &FileMgr) {
Daniel Dunbar90b18272009-11-04 23:56:25 +0000384 PTHManager *PTHMgr = 0;
Daniel Dunbare0a95812009-11-10 22:09:38 +0000385 if (!TokenCache.empty() && !PPOpts.getImplicitPTHInclude().empty()) {
Daniel Dunbar90b18272009-11-04 23:56:25 +0000386 fprintf(stderr, "error: cannot use both -token-cache and -include-pth "
387 "options\n");
388 exit(1);
Ted Kremeneka42cf2e2008-04-17 21:38:34 +0000389 }
Daniel Dunbar90b18272009-11-04 23:56:25 +0000390
391 // Use PTH?
Daniel Dunbare0a95812009-11-10 22:09:38 +0000392 if (!TokenCache.empty() || !PPOpts.getImplicitPTHInclude().empty()) {
393 const std::string& x = TokenCache.empty() ?
394 PPOpts.getImplicitPTHInclude() : TokenCache;
Daniel Dunbar90b18272009-11-04 23:56:25 +0000395 PTHMgr = PTHManager::Create(x, &Diags,
396 TokenCache.empty() ? Diagnostic::Error
397 : Diagnostic::Warning);
398 }
399
400 if (Diags.hasErrorOccurred())
401 exit(1);
402
403 // Create the Preprocessor.
Daniel Dunbar5814e652009-11-11 21:44:21 +0000404 HeaderSearch *HeaderInfo = new HeaderSearch(FileMgr);
Daniel Dunbar90b18272009-11-04 23:56:25 +0000405 Preprocessor *PP = new Preprocessor(Diags, LangInfo, Target,
Daniel Dunbar5814e652009-11-11 21:44:21 +0000406 SourceMgr, *HeaderInfo, PTHMgr,
407 /*OwnsHeaderSearch=*/true);
Daniel Dunbar90b18272009-11-04 23:56:25 +0000408
409 // Note that this is different then passing PTHMgr to Preprocessor's ctor.
410 // That argument is used as the IdentifierInfoLookup argument to
411 // IdentifierTable's ctor.
412 if (PTHMgr) {
413 PTHMgr->setPreprocessor(PP);
414 PP->setPTHManager(PTHMgr);
415 }
416
Daniel Dunbar961c76e2009-11-11 21:44:42 +0000417 InitializePreprocessor(*PP, PPOpts, HSOpts);
Daniel Dunbar90b18272009-11-04 23:56:25 +0000418
Daniel Dunbarca11f612009-11-11 21:44:00 +0000419 // Handle generating dependencies, if requested.
420 if (!DepOpts.OutputFile.empty())
421 AttachDependencyFileGen(*PP, DepOpts);
422
Daniel Dunbar90b18272009-11-04 23:56:25 +0000423 return PP;
Ted Kremeneka42cf2e2008-04-17 21:38:34 +0000424}
Reid Spencer5f016e22007-07-11 17:01:13 +0000425
Reid Spencer5f016e22007-07-11 17:01:13 +0000426//===----------------------------------------------------------------------===//
427// Basic Parser driver
428//===----------------------------------------------------------------------===//
429
Chris Lattner51574ea2008-04-19 23:25:44 +0000430static void ParseFile(Preprocessor &PP, MinimalAction *PA) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000431 Parser P(PP, *PA);
Ted Kremenek95041a22007-12-19 22:51:13 +0000432 PP.EnterMainSourceFile();
Mike Stump1eb44332009-09-09 15:08:12 +0000433
Reid Spencer5f016e22007-07-11 17:01:13 +0000434 // Parsing the specified input file.
435 P.ParseTranslationUnit();
436 delete PA;
437}
438
439//===----------------------------------------------------------------------===//
Douglas Gregor26df2f02009-04-02 19:05:20 +0000440// Fix-It Options
441//===----------------------------------------------------------------------===//
442static llvm::cl::list<ParsedSourceLocation>
443FixItAtLocations("fixit-at", llvm::cl::value_desc("source-location"),
444 llvm::cl::desc("Perform Fix-It modifications at the given source location"));
445
446//===----------------------------------------------------------------------===//
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000447// ObjC Rewriter Options
448//===----------------------------------------------------------------------===//
449static llvm::cl::opt<bool>
450SilenceRewriteMacroWarning("Wno-rewrite-macros", llvm::cl::init(false),
451 llvm::cl::desc("Silence ObjC rewriting warnings"));
452
453//===----------------------------------------------------------------------===//
Eli Friedman0eeb86e2009-05-19 01:17:04 +0000454// Warning Options
455//===----------------------------------------------------------------------===//
456
457// This gets all -W options, including -Werror, -W[no-]system-headers, etc. The
458// driver has stripped off -Wa,foo etc. The driver has also translated -W to
459// -Wextra, so we don't need to worry about it.
460static llvm::cl::list<std::string>
461OptWarnings("W", llvm::cl::Prefix, llvm::cl::ValueOptional);
462
463static llvm::cl::opt<bool> OptPedantic("pedantic");
464static llvm::cl::opt<bool> OptPedanticErrors("pedantic-errors");
465static llvm::cl::opt<bool> OptNoWarnings("w");
466
467//===----------------------------------------------------------------------===//
Chris Lattner75a97cb2009-04-17 21:05:01 +0000468// -dump-build-information Stuff
469//===----------------------------------------------------------------------===//
470
471static llvm::cl::opt<std::string>
472DumpBuildInformation("dump-build-information",
473 llvm::cl::value_desc("filename"),
474 llvm::cl::desc("output a dump of some build information to a file"));
475
Daniel Dunbar227b2382009-11-09 22:45:57 +0000476static void SetUpBuildDumpLog(const DiagnosticOptions &DiagOpts,
Daniel Dunbare29709f2009-11-09 20:55:08 +0000477 unsigned argc, char **argv,
Chris Lattner75a97cb2009-04-17 21:05:01 +0000478 llvm::OwningPtr<DiagnosticClient> &DiagClient) {
Chris Lattner75a97cb2009-04-17 21:05:01 +0000479 std::string ErrorInfo;
Daniel Dunbaraea36412009-11-11 09:38:24 +0000480 llvm::raw_ostream *OS = new llvm::raw_fd_ostream(DumpBuildInformation.c_str(),
481 ErrorInfo);
Chris Lattner75a97cb2009-04-17 21:05:01 +0000482 if (!ErrorInfo.empty()) {
483 llvm::errs() << "error opening -dump-build-information file '"
484 << DumpBuildInformation << "', option ignored!\n";
Daniel Dunbaraea36412009-11-11 09:38:24 +0000485 delete OS;
Chris Lattner75a97cb2009-04-17 21:05:01 +0000486 return;
487 }
488
Daniel Dunbaraea36412009-11-11 09:38:24 +0000489 (*OS) << "clang-cc command line arguments: ";
Chris Lattner75a97cb2009-04-17 21:05:01 +0000490 for (unsigned i = 0; i != argc; ++i)
Daniel Dunbaraea36412009-11-11 09:38:24 +0000491 (*OS) << argv[i] << ' ';
492 (*OS) << '\n';
Mike Stump1eb44332009-09-09 15:08:12 +0000493
Daniel Dunbardbf75fe2009-11-11 08:13:24 +0000494 // Chain in a diagnostic client which will log the diagnostics.
Daniel Dunbaraea36412009-11-11 09:38:24 +0000495 DiagnosticClient *Logger =
496 new TextDiagnosticPrinter(*OS, DiagOpts, /*OwnsOutputStream=*/true);
Daniel Dunbardbf75fe2009-11-11 08:13:24 +0000497 DiagClient.reset(new ChainedDiagnosticClient(DiagClient.take(), Logger));
Chris Lattner75a97cb2009-04-17 21:05:01 +0000498}
499
Chris Lattner75a97cb2009-04-17 21:05:01 +0000500//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +0000501// Main driver
502//===----------------------------------------------------------------------===//
503
Daniel Dunbare29709f2009-11-09 20:55:08 +0000504static llvm::raw_ostream *ComputeOutFile(const CompilerInvocation &CompOpts,
505 const std::string &InFile,
Chris Lattner92bcc272009-08-23 02:59:41 +0000506 const char *Extension,
Eli Friedman66d6f042009-05-18 22:20:00 +0000507 bool Binary,
508 llvm::sys::Path& OutPath) {
Chris Lattner92bcc272009-08-23 02:59:41 +0000509 llvm::raw_ostream *Ret;
Eli Friedman66d6f042009-05-18 22:20:00 +0000510 std::string OutFile;
Daniel Dunbare29709f2009-11-09 20:55:08 +0000511 if (!CompOpts.getOutputFile().empty())
512 OutFile = CompOpts.getOutputFile();
Chris Lattner92bcc272009-08-23 02:59:41 +0000513 else if (InFile == "-") {
514 OutFile = "-";
Eli Friedman66d6f042009-05-18 22:20:00 +0000515 } else if (Extension) {
516 llvm::sys::Path Path(InFile);
517 Path.eraseSuffix();
518 Path.appendSuffix(Extension);
Chris Lattnerd57a7ef2009-08-23 22:45:33 +0000519 OutFile = Path.str();
Eli Friedman66d6f042009-05-18 22:20:00 +0000520 } else {
Chris Lattner92bcc272009-08-23 02:59:41 +0000521 OutFile = "-";
Chris Lattner8a5c8092009-02-18 01:20:05 +0000522 }
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +0000523
Chris Lattner92bcc272009-08-23 02:59:41 +0000524 std::string Error;
525 Ret = new llvm::raw_fd_ostream(OutFile.c_str(), Error,
Dan Gohmanb044c472009-08-25 15:36:09 +0000526 (Binary ? llvm::raw_fd_ostream::F_Binary : 0));
Chris Lattner92bcc272009-08-23 02:59:41 +0000527 if (!Error.empty()) {
528 // FIXME: Don't fail this way.
529 llvm::errs() << "ERROR: " << Error << "\n";
530 ::exit(1);
Ted Kremenekdb094a22007-12-05 18:27:04 +0000531 }
Mike Stump1eb44332009-09-09 15:08:12 +0000532
Chris Lattner92bcc272009-08-23 02:59:41 +0000533 if (OutFile != "-")
534 OutPath = OutFile;
Eli Friedman66d6f042009-05-18 22:20:00 +0000535
536 return Ret;
Ted Kremenekdb094a22007-12-05 18:27:04 +0000537}
538
Daniel Dunbardc8bbac2009-11-11 09:38:42 +0000539/// AddFixItLocations - Add any individual user specified "fix-it" locations,
Daniel Dunbarbd9f04b2009-11-11 09:38:35 +0000540/// and return true on success (if any were added).
Daniel Dunbardc8bbac2009-11-11 09:38:42 +0000541static bool AddFixItLocations(FixItRewriter *FixItRewrite,
Daniel Dunbarbd9f04b2009-11-11 09:38:35 +0000542 FileManager &FileMgr) {
Daniel Dunbardc8bbac2009-11-11 09:38:42 +0000543 bool AddedFixItLocation = false;
Daniel Dunbarbd9f04b2009-11-11 09:38:35 +0000544
545 for (unsigned i = 0, e = FixItAtLocations.size(); i != e; ++i) {
546 if (const FileEntry *File = FileMgr.getFile(FixItAtLocations[i].FileName)) {
547 RequestedSourceLocation Requested;
548 Requested.File = File;
549 Requested.Line = FixItAtLocations[i].Line;
550 Requested.Column = FixItAtLocations[i].Column;
551 FixItRewrite->addFixItLocation(Requested);
Daniel Dunbardc8bbac2009-11-11 09:38:42 +0000552 AddedFixItLocation = true;
Daniel Dunbarbd9f04b2009-11-11 09:38:35 +0000553 } else {
554 llvm::errs() << "FIX-IT could not find file \""
555 << FixItAtLocations[i].FileName << "\"\n";
556 }
557 }
558
Daniel Dunbardc8bbac2009-11-11 09:38:42 +0000559 return AddedFixItLocation;
Daniel Dunbarbd9f04b2009-11-11 09:38:35 +0000560}
561
Daniel Dunbare29709f2009-11-09 20:55:08 +0000562static ASTConsumer *CreateConsumerAction(const CompilerInvocation &CompOpts,
563 Preprocessor &PP,
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000564 const std::string &InFile,
565 ProgActions PA,
566 llvm::OwningPtr<llvm::raw_ostream> &OS,
567 llvm::sys::Path &OutPath,
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000568 llvm::LLVMContext& Context) {
Ted Kremenek85888962008-10-21 00:54:44 +0000569 switch (PA) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000570 default:
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000571 return 0;
Eli Friedman66d6f042009-05-18 22:20:00 +0000572
573 case ASTPrint:
Daniel Dunbare29709f2009-11-09 20:55:08 +0000574 OS.reset(ComputeOutFile(CompOpts, InFile, 0, false, OutPath));
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000575 return CreateASTPrinter(OS.get());
Mike Stump1eb44332009-09-09 15:08:12 +0000576
Douglas Gregoree75c052009-05-21 20:55:50 +0000577 case ASTPrintXML:
Daniel Dunbare29709f2009-11-09 20:55:08 +0000578 OS.reset(ComputeOutFile(CompOpts, InFile, "xml", false, OutPath));
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000579 return CreateASTPrinterXML(OS.get());
Douglas Gregoree75c052009-05-21 20:55:50 +0000580
Eli Friedman66d6f042009-05-18 22:20:00 +0000581 case ASTDump:
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000582 return CreateASTDumper();
Eli Friedman66d6f042009-05-18 22:20:00 +0000583
Eli Friedman66d6f042009-05-18 22:20:00 +0000584 case ASTView:
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000585 return CreateASTViewer();
Eli Friedman66d6f042009-05-18 22:20:00 +0000586
Anders Carlsson78762eb2009-09-24 18:54:49 +0000587 case DumpRecordLayouts:
588 return CreateRecordLayoutDumper();
589
Eli Friedman66d6f042009-05-18 22:20:00 +0000590 case InheritanceView:
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000591 return CreateInheritanceViewer(InheritanceViewCls);
Eli Friedman66d6f042009-05-18 22:20:00 +0000592
593 case EmitAssembly:
594 case EmitLLVM:
Mike Stump1eb44332009-09-09 15:08:12 +0000595 case EmitBC:
Eli Friedman66d6f042009-05-18 22:20:00 +0000596 case EmitLLVMOnly: {
597 BackendAction Act;
598 if (ProgAction == EmitAssembly) {
599 Act = Backend_EmitAssembly;
Daniel Dunbare29709f2009-11-09 20:55:08 +0000600 OS.reset(ComputeOutFile(CompOpts, InFile, "s", true, OutPath));
Eli Friedman66d6f042009-05-18 22:20:00 +0000601 } else if (ProgAction == EmitLLVM) {
602 Act = Backend_EmitLL;
Daniel Dunbare29709f2009-11-09 20:55:08 +0000603 OS.reset(ComputeOutFile(CompOpts, InFile, "ll", true, OutPath));
Eli Friedman66d6f042009-05-18 22:20:00 +0000604 } else if (ProgAction == EmitLLVMOnly) {
605 Act = Backend_EmitNothing;
606 } else {
607 Act = Backend_EmitBC;
Daniel Dunbare29709f2009-11-09 20:55:08 +0000608 OS.reset(ComputeOutFile(CompOpts, InFile, "bc", true, OutPath));
Ted Kremenekdb094a22007-12-05 18:27:04 +0000609 }
Ted Kremenekfdfc1982007-12-19 22:24:34 +0000610
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000611 return CreateBackendConsumer(Act, PP.getDiagnostics(), PP.getLangOptions(),
Daniel Dunbar36f4ec32009-11-10 16:19:45 +0000612 CompOpts.getCompileOpts(), InFile, OS.get(),
613 Context);
Eli Friedman66d6f042009-05-18 22:20:00 +0000614 }
615
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000616 case RewriteObjC:
Daniel Dunbare29709f2009-11-09 20:55:08 +0000617 OS.reset(ComputeOutFile(CompOpts, InFile, "cpp", true, OutPath));
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000618 return CreateObjCRewriter(InFile, OS.get(), PP.getDiagnostics(),
619 PP.getLangOptions(), SilenceRewriteMacroWarning);
620
621 case RewriteBlocks:
622 return CreateBlockRewriter(InFile, PP.getDiagnostics(),
623 PP.getLangOptions());
Daniel Dunbar5ee0aa72009-11-11 00:54:56 +0000624
Daniel Dunbar387ecbd2009-11-11 10:22:48 +0000625 case FixIt: // We add the rewriter later.
Daniel Dunbar5ee0aa72009-11-11 00:54:56 +0000626 case ParseSyntaxOnly:
627 return new ASTConsumer();
628
629 case PrintDeclContext:
630 return CreateDeclContextPrinter();
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000631 }
632}
633
634/// ProcessInputFile - Process a single input file with the specified state.
635///
Daniel Dunbare29709f2009-11-09 20:55:08 +0000636static void ProcessInputFile(const CompilerInvocation &CompOpts,
637 Preprocessor &PP, const std::string &InFile,
Daniel Dunbar0e0bae82009-11-11 21:43:12 +0000638 ProgActions PA, llvm::LLVMContext& Context) {
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000639 llvm::OwningPtr<llvm::raw_ostream> OS;
640 llvm::OwningPtr<ASTConsumer> Consumer;
641 bool ClearSourceMgr = false;
642 FixItRewriter *FixItRewrite = 0;
643 bool CompleteTranslationUnit = true;
644 llvm::sys::Path OutPath;
645
646 switch (PA) {
647 default:
Daniel Dunbare29709f2009-11-09 20:55:08 +0000648 Consumer.reset(CreateConsumerAction(CompOpts, PP, InFile, PA, OS, OutPath,
Daniel Dunbar26a0cac2009-11-09 22:46:17 +0000649 Context));
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000650 if (!Consumer.get()) {
Daniel Dunbar0f9fed72009-11-10 23:55:23 +0000651 PP.getDiagnostics().Report(diag::err_fe_invalid_ast_action);
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000652 return;
653 }
Daniel Dunbardc8bbac2009-11-11 09:38:42 +0000654 break;
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000655
656 case EmitHTML:
Daniel Dunbare29709f2009-11-09 20:55:08 +0000657 OS.reset(ComputeOutFile(CompOpts, InFile, 0, true, OutPath));
Daniel Dunbar90b18272009-11-04 23:56:25 +0000658 Consumer.reset(CreateHTMLPrinter(OS.get(), PP));
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000659 break;
660
Daniel Dunbar5746f1f2009-11-12 00:24:10 +0000661 case RunAnalysis:
Daniel Dunbare29709f2009-11-09 20:55:08 +0000662 Consumer.reset(CreateAnalysisConsumer(PP, CompOpts.getOutputFile(),
Daniel Dunbar5746f1f2009-11-12 00:24:10 +0000663 CompOpts.getAnalyzerOpts()));
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000664 break;
665
Daniel Dunbarf7973292009-11-11 08:13:32 +0000666 case GeneratePCH: {
667 const std::string &Sysroot = CompOpts.getHeaderSearchOpts().Sysroot;
668 if (RelocatablePCH.getValue() && Sysroot.empty()) {
Douglas Gregore650c8c2009-07-07 00:12:59 +0000669 PP.Diag(SourceLocation(), diag::err_relocatable_without_without_isysroot);
670 RelocatablePCH.setValue(false);
671 }
Mike Stump1eb44332009-09-09 15:08:12 +0000672
Daniel Dunbare29709f2009-11-09 20:55:08 +0000673 OS.reset(ComputeOutFile(CompOpts, InFile, 0, true, OutPath));
Douglas Gregore650c8c2009-07-07 00:12:59 +0000674 if (RelocatablePCH.getValue())
Daniel Dunbarf7973292009-11-11 08:13:32 +0000675 Consumer.reset(CreatePCHGenerator(PP, OS.get(), Sysroot.c_str()));
Douglas Gregore650c8c2009-07-07 00:12:59 +0000676 else
677 Consumer.reset(CreatePCHGenerator(PP, OS.get()));
Eli Friedman66d6f042009-05-18 22:20:00 +0000678 CompleteTranslationUnit = false;
679 break;
Daniel Dunbarf7973292009-11-11 08:13:32 +0000680 }
Chris Lattnerc106c102008-10-12 05:03:36 +0000681 case DumpRawTokens: {
Chris Lattner47099742009-02-18 01:51:21 +0000682 llvm::TimeRegion Timer(ClangFrontendTimer);
Chris Lattnerc106c102008-10-12 05:03:36 +0000683 SourceManager &SM = PP.getSourceManager();
Chris Lattnerc106c102008-10-12 05:03:36 +0000684 // Start lexing the specified input file.
Chris Lattner025c3a62009-01-17 07:35:14 +0000685 Lexer RawLex(SM.getMainFileID(), SM, PP.getLangOptions());
Chris Lattnerc106c102008-10-12 05:03:36 +0000686 RawLex.SetKeepWhitespaceMode(true);
687
688 Token RawTok;
Chris Lattnerc106c102008-10-12 05:03:36 +0000689 RawLex.LexFromRawLexer(RawTok);
690 while (RawTok.isNot(tok::eof)) {
691 PP.DumpToken(RawTok, true);
692 fprintf(stderr, "\n");
693 RawLex.LexFromRawLexer(RawTok);
694 }
695 ClearSourceMgr = true;
696 break;
697 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000698 case DumpTokens: { // Token dump mode.
Chris Lattner47099742009-02-18 01:51:21 +0000699 llvm::TimeRegion Timer(ClangFrontendTimer);
Chris Lattnerd2177732007-07-20 16:59:19 +0000700 Token Tok;
Chris Lattnerc106c102008-10-12 05:03:36 +0000701 // Start preprocessing the specified input file.
Ted Kremenek95041a22007-12-19 22:51:13 +0000702 PP.EnterMainSourceFile();
Reid Spencer5f016e22007-07-11 17:01:13 +0000703 do {
704 PP.Lex(Tok);
705 PP.DumpToken(Tok, true);
706 fprintf(stderr, "\n");
Chris Lattner057aaf62007-10-09 18:03:42 +0000707 } while (Tok.isNot(tok::eof));
Chris Lattnerbd247762007-07-22 06:05:44 +0000708 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000709 break;
710 }
Chris Lattnerd1d64a02009-04-27 21:45:14 +0000711 case RunPreprocessorOnly:
Reid Spencer5f016e22007-07-11 17:01:13 +0000712 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000713
Douglas Gregorbf1bd6e2009-04-02 23:43:50 +0000714 case GeneratePTH: {
Chris Lattner47099742009-02-18 01:51:21 +0000715 llvm::TimeRegion Timer(ClangFrontendTimer);
Daniel Dunbare29709f2009-11-09 20:55:08 +0000716 if (CompOpts.getOutputFile().empty() || CompOpts.getOutputFile() == "-") {
Eli Friedmanf54fce82009-05-19 01:02:07 +0000717 // FIXME: Don't fail this way.
718 // FIXME: Verify that we can actually seek in the given file.
Chris Lattner92bcc272009-08-23 02:59:41 +0000719 llvm::errs() << "ERROR: PTH requires an seekable file for output!\n";
Eli Friedmanf54fce82009-05-19 01:02:07 +0000720 ::exit(1);
721 }
Daniel Dunbare29709f2009-11-09 20:55:08 +0000722 OS.reset(ComputeOutFile(CompOpts, InFile, 0, true, OutPath));
Eli Friedmanf54fce82009-05-19 01:02:07 +0000723 CacheTokens(PP, static_cast<llvm::raw_fd_ostream*>(OS.get()));
Ted Kremenek85888962008-10-21 00:54:44 +0000724 ClearSourceMgr = true;
725 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000726 }
Douglas Gregor6ab35242009-04-09 21:40:53 +0000727
Chris Lattnercc7dea82009-04-27 22:02:30 +0000728 case PrintPreprocessedInput:
Daniel Dunbare29709f2009-11-09 20:55:08 +0000729 OS.reset(ComputeOutFile(CompOpts, InFile, 0, true, OutPath));
Reid Spencer5f016e22007-07-11 17:01:13 +0000730 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000731
Chris Lattnerd1d64a02009-04-27 21:45:14 +0000732 case ParseNoop:
Reid Spencer5f016e22007-07-11 17:01:13 +0000733 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000734
Chris Lattner47099742009-02-18 01:51:21 +0000735 case ParsePrintCallbacks: {
736 llvm::TimeRegion Timer(ClangFrontendTimer);
Daniel Dunbare29709f2009-11-09 20:55:08 +0000737 OS.reset(ComputeOutFile(CompOpts, InFile, 0, true, OutPath));
Eli Friedmanf54fce82009-05-19 01:02:07 +0000738 ParseFile(PP, CreatePrintParserActionsAction(PP, OS.get()));
Chris Lattnerbd247762007-07-22 06:05:44 +0000739 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000740 break;
Chris Lattner47099742009-02-18 01:51:21 +0000741 }
742
Chris Lattnerb57e3d42008-05-08 06:52:13 +0000743 case RewriteMacros:
Daniel Dunbare29709f2009-11-09 20:55:08 +0000744 OS.reset(ComputeOutFile(CompOpts, InFile, 0, true, OutPath));
Eli Friedmanf54fce82009-05-19 01:02:07 +0000745 RewriteMacrosInInput(PP, OS.get());
Chris Lattnerb57e3d42008-05-08 06:52:13 +0000746 ClearSourceMgr = true;
747 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000748
Eli Friedmanf54fce82009-05-19 01:02:07 +0000749 case RewriteTest:
Daniel Dunbare29709f2009-11-09 20:55:08 +0000750 OS.reset(ComputeOutFile(CompOpts, InFile, 0, true, OutPath));
Eli Friedmanf54fce82009-05-19 01:02:07 +0000751 DoRewriteTest(PP, OS.get());
Chris Lattnerb13c5ee2008-10-12 05:29:20 +0000752 ClearSourceMgr = true;
753 break;
Daniel Dunbar387ecbd2009-11-11 10:22:48 +0000754 }
Douglas Gregor558cb562009-04-02 01:08:08 +0000755
Daniel Dunbar387ecbd2009-11-11 10:22:48 +0000756 // Check if we want a fix-it rewriter.
757 if (PA == FixIt || !FixItAtLocations.empty()) {
Douglas Gregorde4bf6a2009-04-02 17:13:00 +0000758 FixItRewrite = new FixItRewriter(PP.getDiagnostics(),
Chris Lattner2c78b872009-04-14 23:22:57 +0000759 PP.getSourceManager(),
760 PP.getLangOptions());
Daniel Dunbar387ecbd2009-11-11 10:22:48 +0000761 if (!FixItAtLocations.empty() &&
762 !AddFixItLocations(FixItRewrite, PP.getFileManager())) {
Chris Lattner1aee61a2009-04-27 21:25:27 +0000763 // All of the fix-it locations were bad. Don't fix anything.
764 delete FixItRewrite;
765 FixItRewrite = 0;
766 }
767 }
768
Daniel Dunbardc8bbac2009-11-11 09:38:42 +0000769
Chris Lattner1aee61a2009-04-27 21:25:27 +0000770 llvm::OwningPtr<ASTContext> ContextOwner;
Chris Lattnerd1d64a02009-04-27 21:45:14 +0000771 if (Consumer)
Chris Lattner9ecd26a2009-03-28 01:37:17 +0000772 ContextOwner.reset(new ASTContext(PP.getLangOptions(),
773 PP.getSourceManager(),
774 PP.getTargetInfo(),
775 PP.getIdentifierTable(),
776 PP.getSelectorTable(),
Chris Lattner1b63e4f2009-06-14 01:54:56 +0000777 PP.getBuiltinInfo(),
Douglas Gregor2deaea32009-04-22 18:49:13 +0000778 /* FreeMemory = */ !DisableFree,
Chris Lattner1b63e4f2009-06-14 01:54:56 +0000779 /* size_reserve = */0));
Mike Stump1eb44332009-09-09 15:08:12 +0000780
Chris Lattnercc7dea82009-04-27 22:02:30 +0000781 llvm::OwningPtr<PCHReader> Reader;
782 llvm::OwningPtr<ExternalASTSource> Source;
Mike Stump1eb44332009-09-09 15:08:12 +0000783
Daniel Dunbare0a95812009-11-10 22:09:38 +0000784 const std::string &ImplicitPCHInclude =
785 CompOpts.getPreprocessorOpts().getImplicitPCHInclude();
786 if (!ImplicitPCHInclude.empty()) {
Douglas Gregore650c8c2009-07-07 00:12:59 +0000787 // If the user specified -isysroot, it will be used for relocatable PCH
788 // files.
Daniel Dunbarf7973292009-11-11 08:13:32 +0000789 const char *isysrootPCH = CompOpts.getHeaderSearchOpts().Sysroot.c_str();
790 if (isysrootPCH[0] == '\0')
791 isysrootPCH = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000792
Douglas Gregore650c8c2009-07-07 00:12:59 +0000793 Reader.reset(new PCHReader(PP, ContextOwner.get(), isysrootPCH));
Mike Stump1eb44332009-09-09 15:08:12 +0000794
Chris Lattnerd1d64a02009-04-27 21:45:14 +0000795 // The user has asked us to include a precompiled header. Load
796 // the precompiled header into the AST context.
Daniel Dunbare0a95812009-11-10 22:09:38 +0000797 switch (Reader->ReadPCH(ImplicitPCHInclude)) {
Chris Lattnerd1d64a02009-04-27 21:45:14 +0000798 case PCHReader::Success: {
Douglas Gregore721f952009-04-28 18:58:38 +0000799 // Set the predefines buffer as suggested by the PCH
800 // reader. Typically, the predefines buffer will be empty.
801 PP.setPredefines(Reader->getSuggestedPredefines());
802
Chris Lattnerd1d64a02009-04-27 21:45:14 +0000803 // Attach the PCH reader to the AST context as an external AST
804 // source, so that declarations will be deserialized from the
805 // PCH file as needed.
Chris Lattnercc7dea82009-04-27 22:02:30 +0000806 if (ContextOwner) {
807 Source.reset(Reader.take());
Douglas Gregore1d918e2009-04-10 23:10:45 +0000808 ContextOwner->setExternalSource(Source);
Chris Lattnercc7dea82009-04-27 22:02:30 +0000809 }
Chris Lattnerd1d64a02009-04-27 21:45:14 +0000810 break;
Douglas Gregor2cf26342009-04-09 22:27:44 +0000811 }
812
Chris Lattnerd1d64a02009-04-27 21:45:14 +0000813 case PCHReader::Failure:
814 // Unrecoverable failure: don't even try to process the input
815 // file.
816 return;
817
818 case PCHReader::IgnorePCH:
Douglas Gregor1ab86ac2009-04-28 22:01:16 +0000819 // No suitable PCH file could be found. Return an error.
820 return;
Chris Lattnerd1d64a02009-04-27 21:45:14 +0000821 }
822
823 // Finish preprocessor initialization. We do this now (rather
824 // than earlier) because this initialization creates new source
825 // location entries in the source manager, which must come after
826 // the source location entries for the PCH file.
827 if (InitializeSourceManager(PP, InFile))
828 return;
Ted Kremenek46157b52009-01-28 04:29:29 +0000829 }
Daniel Dunbarbea5a842009-10-29 01:53:18 +0000830
Chris Lattnerd1d64a02009-04-27 21:45:14 +0000831 // If we have an ASTConsumer, run the parser with it.
Douglas Gregor81b747b2009-09-17 21:32:03 +0000832 if (Consumer) {
833 CodeCompleteConsumer *(*CreateCodeCompleter)(Sema &, void *) = 0;
834 void *CreateCodeCompleterData = 0;
Daniel Dunbarbea5a842009-10-29 01:53:18 +0000835
Douglas Gregorb657f112009-09-22 21:11:38 +0000836 if (!CodeCompletionAt.FileName.empty()) {
837 // Tell the source manager to chop off the given file at a specific
838 // line and column.
Daniel Dunbarbea5a842009-10-29 01:53:18 +0000839 if (const FileEntry *Entry
Douglas Gregorb657f112009-09-22 21:11:38 +0000840 = PP.getFileManager().getFile(CodeCompletionAt.FileName)) {
841 // Truncate the named file at the given line/column.
842 PP.getSourceManager().truncateFileAt(Entry, CodeCompletionAt.Line,
843 CodeCompletionAt.Column);
Daniel Dunbarbea5a842009-10-29 01:53:18 +0000844
Douglas Gregorb657f112009-09-22 21:11:38 +0000845 // Set up the creation routine for code-completion.
846 CreateCodeCompleter = BuildPrintingCodeCompleter;
847 } else {
Daniel Dunbar0f9fed72009-11-10 23:55:23 +0000848 PP.getDiagnostics().Report(diag::err_fe_invalid_code_complete_file)
Douglas Gregorb657f112009-09-22 21:11:38 +0000849 << CodeCompletionAt.FileName;
850 }
Douglas Gregor81b747b2009-09-17 21:32:03 +0000851 }
852
Mike Stump1eb44332009-09-09 15:08:12 +0000853 ParseAST(PP, Consumer.get(), *ContextOwner.get(), Stats,
Douglas Gregor81b747b2009-09-17 21:32:03 +0000854 CompleteTranslationUnit,
855 CreateCodeCompleter, CreateCodeCompleterData);
856 }
Chris Lattnerd1d64a02009-04-27 21:45:14 +0000857
Daniel Dunbar593c41f2009-11-04 23:41:40 +0000858 // Perform post processing actions and actions which don't use a consumer.
859 switch (PA) {
860 default: break;
861
862 case RunPreprocessorOnly: { // Just lex as fast as we can, no output.
Chris Lattnerd1d64a02009-04-27 21:45:14 +0000863 llvm::TimeRegion Timer(ClangFrontendTimer);
864 Token Tok;
865 // Start parsing the specified input file.
866 PP.EnterMainSourceFile();
867 do {
868 PP.Lex(Tok);
869 } while (Tok.isNot(tok::eof));
870 ClearSourceMgr = true;
Daniel Dunbar593c41f2009-11-04 23:41:40 +0000871 break;
872 }
873
874 case ParseNoop: {
Chris Lattnerd1d64a02009-04-27 21:45:14 +0000875 llvm::TimeRegion Timer(ClangFrontendTimer);
876 ParseFile(PP, new MinimalAction(PP));
877 ClearSourceMgr = true;
Daniel Dunbar593c41f2009-11-04 23:41:40 +0000878 break;
879 }
880
881 case PrintPreprocessedInput: {
Chris Lattnercc7dea82009-04-27 22:02:30 +0000882 llvm::TimeRegion Timer(ClangFrontendTimer);
Daniel Dunbar29cf7462009-11-11 10:07:44 +0000883 DoPrintPreprocessedInput(PP, OS.get(),
884 CompOpts.getPreprocessorOutputOpts());
Chris Lattnercc7dea82009-04-27 22:02:30 +0000885 ClearSourceMgr = true;
Chris Lattnerd1d64a02009-04-27 21:45:14 +0000886 }
Mike Stump1eb44332009-09-09 15:08:12 +0000887
Daniel Dunbar593c41f2009-11-04 23:41:40 +0000888 }
889
Chris Lattner1aee61a2009-04-27 21:25:27 +0000890 if (FixItRewrite)
Daniel Dunbare29709f2009-11-09 20:55:08 +0000891 FixItRewrite->WriteFixedFile(InFile, CompOpts.getOutputFile());
Daniel Dunbar70186ab2009-07-29 02:40:09 +0000892
893 // Disable the consumer prior to the context, the consumer may perform actions
894 // in its destructor which require the context.
895 if (DisableFree)
896 Consumer.take();
897 else
898 Consumer.reset();
Mike Stump1eb44332009-09-09 15:08:12 +0000899
Chris Lattner1aee61a2009-04-27 21:25:27 +0000900 // If in -disable-free mode, don't deallocate ASTContext.
901 if (DisableFree)
902 ContextOwner.take();
903 else
904 ContextOwner.reset(); // Delete ASTContext
Eli Friedman66d6f042009-05-18 22:20:00 +0000905
Daniel Dunbar879c3ea2008-10-27 22:03:52 +0000906 if (VerifyDiagnostics)
Daniel Dunbar276373d2008-10-27 22:10:13 +0000907 if (CheckDiagnostics(PP))
908 exit(1);
Chris Lattnere66b65c2008-02-06 01:42:25 +0000909
Reid Spencer5f016e22007-07-11 17:01:13 +0000910 if (Stats) {
Ted Kremenekfdfc1982007-12-19 22:24:34 +0000911 fprintf(stderr, "\nSTATISTICS FOR '%s':\n", InFile.c_str());
Reid Spencer5f016e22007-07-11 17:01:13 +0000912 PP.PrintStats();
913 PP.getIdentifierTable().PrintStats();
Chris Lattnerdee73592007-12-15 20:48:40 +0000914 PP.getHeaderSearchInfo().PrintStats();
Ted Kremenek1b95a652009-01-09 18:20:21 +0000915 PP.getSourceManager().PrintStats();
Reid Spencer5f016e22007-07-11 17:01:13 +0000916 fprintf(stderr, "\n");
917 }
Chris Lattnerbd247762007-07-22 06:05:44 +0000918
Mike Stump1eb44332009-09-09 15:08:12 +0000919 // For a multi-file compilation, some things are ok with nuking the source
Chris Lattnerbd247762007-07-22 06:05:44 +0000920 // manager tables, other require stable fileid/macroid's across multiple
921 // files.
Chris Lattnerdee73592007-12-15 20:48:40 +0000922 if (ClearSourceMgr)
923 PP.getSourceManager().clearIDTables();
Daniel Dunbard68ba0e2008-11-11 06:35:39 +0000924
Eli Friedman66d6f042009-05-18 22:20:00 +0000925 // Always delete the output stream because we don't want to leak file
926 // handles. Also, we don't want to try to erase an open file.
927 OS.reset();
928
Daniel Dunbar8cb65622009-10-29 21:05:18 +0000929 // If we had errors, try to erase the output file.
930 if (PP.getDiagnostics().getNumErrors() && !OutPath.isEmpty())
Eli Friedman66d6f042009-05-18 22:20:00 +0000931 OutPath.eraseFromDisk();
Reid Spencer5f016e22007-07-11 17:01:13 +0000932}
933
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +0000934/// ProcessInputFile - Process a single AST input file with the specified state.
935///
Daniel Dunbare29709f2009-11-09 20:55:08 +0000936static void ProcessASTInputFile(const CompilerInvocation &CompOpts,
937 const std::string &InFile, ProgActions PA,
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +0000938 Diagnostic &Diags, FileManager &FileMgr,
939 llvm::LLVMContext& Context) {
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +0000940 std::string Error;
Steve Naroff36c44642009-10-19 14:34:22 +0000941 llvm::OwningPtr<ASTUnit> AST(ASTUnit::LoadFromPCHFile(InFile, &Error));
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +0000942 if (!AST) {
Daniel Dunbar0f9fed72009-11-10 23:55:23 +0000943 Diags.Report(diag::err_fe_invalid_ast_file) << Error;
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +0000944 return;
945 }
946
947 Preprocessor &PP = AST->getPreprocessor();
948
949 llvm::OwningPtr<llvm::raw_ostream> OS;
950 llvm::sys::Path OutPath;
Daniel Dunbare29709f2009-11-09 20:55:08 +0000951 llvm::OwningPtr<ASTConsumer> Consumer(CreateConsumerAction(CompOpts, PP,
952 InFile, PA, OS,
Daniel Dunbar26a0cac2009-11-09 22:46:17 +0000953 OutPath, Context));
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +0000954
955 if (!Consumer.get()) {
Daniel Dunbar0f9fed72009-11-10 23:55:23 +0000956 Diags.Report(diag::err_fe_invalid_ast_action);
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +0000957 return;
958 }
959
Daniel Dunbara674bf42009-09-21 03:03:56 +0000960 // Set the main file ID to an empty file.
961 //
962 // FIXME: We probably shouldn't need this, but for now this is the simplest
963 // way to reuse the logic in ParseAST.
964 const char *EmptyStr = "";
965 llvm::MemoryBuffer *SB =
966 llvm::MemoryBuffer::getMemBuffer(EmptyStr, EmptyStr, "<dummy input>");
967 AST->getSourceManager().createMainFileIDForMemBuffer(SB);
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +0000968
Daniel Dunbara674bf42009-09-21 03:03:56 +0000969 // Stream the input AST to the consumer.
Daniel Dunbarefcbe942009-11-05 02:42:12 +0000970 Diags.getClient()->BeginSourceFile(PP.getLangOptions());
Daniel Dunbara674bf42009-09-21 03:03:56 +0000971 ParseAST(PP, Consumer.get(), AST->getASTContext(), Stats);
Daniel Dunbarefcbe942009-11-05 02:42:12 +0000972 Diags.getClient()->EndSourceFile();
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +0000973
974 // Release the consumer and the AST, in that order since the consumer may
975 // perform actions in its destructor which require the context.
976 if (DisableFree) {
977 Consumer.take();
978 AST.take();
979 } else {
980 Consumer.reset();
981 AST.reset();
982 }
983
984 // Always delete the output stream because we don't want to leak file
985 // handles. Also, we don't want to try to erase an open file.
986 OS.reset();
987
Daniel Dunbar8cb65622009-10-29 21:05:18 +0000988 // If we had errors, try to erase the output file.
989 if (PP.getDiagnostics().getNumErrors() && !OutPath.isEmpty())
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +0000990 OutPath.eraseFromDisk();
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +0000991}
992
Daniel Dunbar70121eb2009-08-10 03:40:28 +0000993static void LLVMErrorHandler(void *UserData, const std::string &Message) {
994 Diagnostic &Diags = *static_cast<Diagnostic*>(UserData);
995
Daniel Dunbar0f9fed72009-11-10 23:55:23 +0000996 Diags.Report(diag::err_fe_error_backend) << Message;
Daniel Dunbar70121eb2009-08-10 03:40:28 +0000997
998 // We cannot recover from llvm errors.
999 exit(1);
1000}
1001
Daniel Dunbar227b2382009-11-09 22:45:57 +00001002static LangKind GetLanguage() {
1003 // If -x was given, that's the language.
1004 if (BaseLang != langkind_unspecified)
1005 return BaseLang;
Daniel Dunbare29709f2009-11-09 20:55:08 +00001006
Daniel Dunbar227b2382009-11-09 22:45:57 +00001007 // Otherwise guess it from the input filenames;
1008 LangKind LK = langkind_unspecified;
1009 for (unsigned i = 0, e = InputFilenames.size(); i != e; ++i) {
1010 llvm::StringRef Name(InputFilenames[i]);
1011 LangKind ThisKind = llvm::StringSwitch<LangKind>(Name.rsplit('.').second)
1012 .Case("ast", langkind_ast)
1013 .Case("c", langkind_c)
1014 .Cases("S", "s", langkind_asm_cpp)
1015 .Case("i", langkind_c_cpp)
1016 .Case("ii", langkind_cxx_cpp)
1017 .Case("m", langkind_objc)
1018 .Case("mi", langkind_objc_cpp)
1019 .Cases("mm", "M", langkind_objcxx)
1020 .Case("mii", langkind_objcxx_cpp)
1021 .Case("C", langkind_cxx)
1022 .Cases("C", "cc", "cp", langkind_cxx)
1023 .Cases("cpp", "CPP", "c++", "cxx", langkind_cxx)
1024 .Case("cl", langkind_ocl)
1025 .Default(langkind_c);
1026
1027 if (LK != langkind_unspecified && ThisKind != LK) {
1028 llvm::errs() << "error: cannot have multiple input files of distinct "
1029 << "language kinds without -x\n";
1030 exit(1);
1031 }
1032
1033 LK = ThisKind;
1034 }
1035
1036 return LK;
1037}
1038
Daniel Dunbar0498cfc2009-11-10 19:51:53 +00001039static void FinalizeCompileOptions(CompileOptions &Opts,
1040 const LangOptions &Lang) {
1041 if (Lang.NoBuiltin)
1042 Opts.SimplifyLibCalls = 0;
1043 if (Lang.CPlusPlus)
1044 Opts.NoCommon = 1;
1045
1046 // Handle -ftime-report.
1047 Opts.TimePasses = TimeReport;
1048}
1049
Daniel Dunbar227b2382009-11-09 22:45:57 +00001050static void ConstructCompilerInvocation(CompilerInvocation &Opts,
Daniel Dunbar26a0cac2009-11-09 22:46:17 +00001051 const char *Argv0,
Daniel Dunbar227b2382009-11-09 22:45:57 +00001052 const DiagnosticOptions &DiagOpts,
Daniel Dunbar26a0cac2009-11-09 22:46:17 +00001053 TargetInfo &Target,
1054 LangKind LK) {
Daniel Dunbar227b2382009-11-09 22:45:57 +00001055 Opts.getDiagnosticOpts() = DiagOpts;
1056
1057 Opts.getOutputFile() = OutputFile;
Daniel Dunbar26a0cac2009-11-09 22:46:17 +00001058
Daniel Dunbarfcb0c3b2009-11-10 18:47:35 +00001059 // Initialize backend options, which may also be used to key some language
1060 // options.
Daniel Dunbar29a790b2009-11-11 09:38:56 +00001061 InitializeCompileOptions(Opts.getCompileOpts(), Target);
Daniel Dunbarfcb0c3b2009-11-10 18:47:35 +00001062
Daniel Dunbar26a0cac2009-11-09 22:46:17 +00001063 // Initialize language options.
Daniel Dunbar5746f1f2009-11-12 00:24:10 +00001064 //
Daniel Dunbar26a0cac2009-11-09 22:46:17 +00001065 // FIXME: These aren't used during operations on ASTs. Split onto a separate
1066 // code path to make this obvious.
Daniel Dunbar56749082009-11-11 07:26:12 +00001067 if (LK != langkind_ast)
1068 InitializeLangOptions(Opts.getLangOpts(), LK, Target,
Daniel Dunbar29a790b2009-11-11 09:38:56 +00001069 Opts.getCompileOpts());
Daniel Dunbar26a0cac2009-11-09 22:46:17 +00001070
Daniel Dunbar5746f1f2009-11-12 00:24:10 +00001071 // Initialize the static analyzer options.
1072 InitializeAnalyzerOptions(Opts.getAnalyzerOpts());
1073
Daniel Dunbar0e0bae82009-11-11 21:43:12 +00001074 // Initialize the dependency output options (-M...).
1075 InitializeDependencyOutputOptions(Opts.getDependencyOutputOpts());
1076
Daniel Dunbar26a0cac2009-11-09 22:46:17 +00001077 // Initialize the header search options.
Daniel Dunbarf7973292009-11-11 08:13:32 +00001078 InitializeHeaderSearchOptions(Opts.getHeaderSearchOpts(),
1079 GetBuiltinIncludePath(Argv0),
1080 Verbose,
1081 Opts.getLangOpts());
Daniel Dunbar5fc7d342009-11-09 23:12:31 +00001082
1083 // Initialize the other preprocessor options.
1084 InitializePreprocessorOptions(Opts.getPreprocessorOpts());
Daniel Dunbar36f4ec32009-11-10 16:19:45 +00001085
Daniel Dunbar29cf7462009-11-11 10:07:44 +00001086 // Initialize the preprocessed output options.
1087 InitializePreprocessorOutputOptions(Opts.getPreprocessorOutputOpts());
1088
Daniel Dunbar0498cfc2009-11-10 19:51:53 +00001089 // Finalize some code generation options.
Daniel Dunbarfcb0c3b2009-11-10 18:47:35 +00001090 FinalizeCompileOptions(Opts.getCompileOpts(), Opts.getLangOpts());
Daniel Dunbare29709f2009-11-09 20:55:08 +00001091}
1092
Reid Spencer5f016e22007-07-11 17:01:13 +00001093int main(int argc, char **argv) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001094 llvm::sys::PrintStackTraceOnErrorSignal();
Chris Lattner09e94a32009-03-04 21:41:39 +00001095 llvm::PrettyStackTraceProgram X(argc, argv);
Owen Andersond7200462009-07-16 00:14:12 +00001096 llvm::LLVMContext &Context = llvm::getGlobalContext();
Daniel Dunbard6970812009-09-02 23:20:15 +00001097
Daniel Dunbar4d861512009-09-03 04:54:12 +00001098 // Initialize targets first, so that --version shows registered targets.
Chris Lattner2fe11942009-06-17 17:25:50 +00001099 llvm::InitializeAllTargets();
1100 llvm::InitializeAllAsmPrinters();
Daniel Dunbard6970812009-09-02 23:20:15 +00001101
1102 llvm::cl::ParseCommandLineOptions(argc, argv,
1103 "LLVM 'Clang' Compiler: http://clang.llvm.org\n");
Mike Stump1eb44332009-09-09 15:08:12 +00001104
Chris Lattner47099742009-02-18 01:51:21 +00001105 if (TimeReport)
1106 ClangFrontendTimer = new llvm::Timer("Clang front-end time");
Mike Stump1eb44332009-09-09 15:08:12 +00001107
Daniel Dunbar08e6dc62009-05-28 16:37:33 +00001108 if (Verbose)
Mike Stump3cbf5a02009-09-15 21:49:22 +00001109 llvm::errs() << "clang-cc version " CLANG_VERSION_STRING
1110 << " based upon " << PACKAGE_STRING
Daniel Dunbar2e30e592009-09-04 17:43:10 +00001111 << " hosted on " << llvm::sys::getHostTriple() << "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00001112
Reid Spencer5f016e22007-07-11 17:01:13 +00001113 // If no input was specified, read from stdin.
1114 if (InputFilenames.empty())
1115 InputFilenames.push_back("-");
Douglas Gregor68a0d782009-05-02 00:03:46 +00001116
Daniel Dunbar227b2382009-11-09 22:45:57 +00001117 // Construct the diagnostic options first, which cannot fail, so that we can
1118 // build a diagnostic client to use for any errors during option handling.
1119 DiagnosticOptions DiagOpts;
Daniel Dunbar0db4b762009-11-11 08:13:40 +00001120 InitializeDiagnosticOptions(DiagOpts);
Daniel Dunbareace8742009-11-04 06:24:30 +00001121
Ted Kremenek31e703b2007-12-11 23:28:38 +00001122 // Create the diagnostic client for reporting errors or for
1123 // implementing -verify.
Chris Lattner409d4e72009-04-17 20:40:01 +00001124 llvm::OwningPtr<DiagnosticClient> DiagClient;
1125 if (VerifyDiagnostics) {
1126 // When checking diagnostics, just buffer them up.
1127 DiagClient.reset(new TextDiagnosticBuffer());
1128 if (InputFilenames.size() != 1) {
Daniel Dunbar227b2382009-11-09 22:45:57 +00001129 fprintf(stderr, "-verify only works on single input files.\n");
Chris Lattner409d4e72009-04-17 20:40:01 +00001130 return 1;
1131 }
Ted Kremenekb4398aa2008-08-07 17:49:57 +00001132 } else {
Daniel Dunbar227b2382009-11-09 22:45:57 +00001133 DiagClient.reset(new TextDiagnosticPrinter(llvm::errs(), DiagOpts));
Reid Spencer5f016e22007-07-11 17:01:13 +00001134 }
Mike Stump1eb44332009-09-09 15:08:12 +00001135
Daniel Dunbarad451cc2009-11-05 02:11:37 +00001136 if (!DumpBuildInformation.empty())
Daniel Dunbar227b2382009-11-09 22:45:57 +00001137 SetUpBuildDumpLog(DiagOpts, argc, argv, DiagClient);
Ted Kremenekb4398aa2008-08-07 17:49:57 +00001138
Reid Spencer5f016e22007-07-11 17:01:13 +00001139 // Configure our handling of diagnostics.
Ted Kremenekb4398aa2008-08-07 17:49:57 +00001140 Diagnostic Diags(DiagClient.get());
Eli Friedman0eeb86e2009-05-19 01:17:04 +00001141 if (ProcessWarningOptions(Diags, OptWarnings, OptPedantic, OptPedanticErrors,
1142 OptNoWarnings))
Sebastian Redl63a9e0f2009-03-06 17:41:35 +00001143 return 1;
Ted Kremenek31e703b2007-12-11 23:28:38 +00001144
Daniel Dunbar70121eb2009-08-10 03:40:28 +00001145 // Set an error handler, so that any LLVM backend diagnostics go through our
1146 // error handler.
1147 llvm::llvm_install_error_handler(LLVMErrorHandler,
1148 static_cast<void*>(&Diags));
1149
Daniel Dunbar7c15e712009-10-30 18:12:31 +00001150 // Initialize base triple. If a -triple option has been specified, use
1151 // that triple. Otherwise, default to the host triple.
1152 llvm::Triple Triple(TargetTriple);
1153 if (Triple.getTriple().empty())
1154 Triple = llvm::Triple(llvm::sys::getHostTriple());
1155
Chris Lattner11215192008-03-14 06:12:05 +00001156 // Get information about the target being compiled for.
Daniel Dunbarbea5a842009-10-29 01:53:18 +00001157 llvm::OwningPtr<TargetInfo>
Chris Lattner2f60af72009-09-12 22:45:58 +00001158 Target(TargetInfo::CreateTargetInfo(Triple.getTriple()));
Mike Stump1eb44332009-09-09 15:08:12 +00001159
Chris Lattner11215192008-03-14 06:12:05 +00001160 if (Target == 0) {
Daniel Dunbar0f9fed72009-11-10 23:55:23 +00001161 Diags.Report(diag::err_fe_unknown_triple) << Triple.getTriple().c_str();
Sebastian Redlc5613db2009-03-07 12:09:25 +00001162 return 1;
Chris Lattner11215192008-03-14 06:12:05 +00001163 }
Mike Stump1eb44332009-09-09 15:08:12 +00001164
Daniel Dunbar73b79592009-09-14 00:02:12 +00001165 // Set the target ABI if specified.
1166 if (!TargetABI.empty()) {
1167 if (!Target->setABI(TargetABI)) {
Daniel Dunbar0f9fed72009-11-10 23:55:23 +00001168 Diags.Report(diag::err_fe_unknown_target_abi) << TargetABI;
Daniel Dunbar73b79592009-09-14 00:02:12 +00001169 return 1;
1170 }
1171 }
1172
Daniel Dunbard4270232009-01-20 23:17:32 +00001173 if (!InheritanceViewCls.empty()) // C++ visualization?
Ted Kremenek7cae2f62008-10-23 23:36:29 +00001174 ProgAction = InheritanceView;
Mike Stump1eb44332009-09-09 15:08:12 +00001175
Daniel Dunbar227b2382009-11-09 22:45:57 +00001176 // Infer the input language.
1177 //
1178 // FIXME: We should move .ast inputs to taking a separate path, they are
1179 // really quite different.
1180 LangKind LK = GetLanguage();
1181
1182 // Now that we have initialized the diagnostics engine and the target, finish
1183 // setting up the compiler invocation.
1184 CompilerInvocation CompOpts;
Daniel Dunbar26a0cac2009-11-09 22:46:17 +00001185 ConstructCompilerInvocation(CompOpts, argv[0], DiagOpts, *Target, LK);
Daniel Dunbar227b2382009-11-09 22:45:57 +00001186
Daniel Dunbar4cc1a252009-11-05 01:53:23 +00001187 // Create the source manager.
1188 SourceManager SourceMgr;
Mike Stump1eb44332009-09-09 15:08:12 +00001189
Chris Lattner2c78b872009-04-14 23:22:57 +00001190 // Create a file manager object to provide access to and cache the filesystem.
1191 FileManager FileMgr;
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001192
Reid Spencer5f016e22007-07-11 17:01:13 +00001193 for (unsigned i = 0, e = InputFilenames.size(); i != e; ++i) {
Ted Kremenek31e703b2007-12-11 23:28:38 +00001194 const std::string &InFile = InputFilenames[i];
Mike Stump1eb44332009-09-09 15:08:12 +00001195
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +00001196 // AST inputs are handled specially.
1197 if (LK == langkind_ast) {
Daniel Dunbar26a0cac2009-11-09 22:46:17 +00001198 ProcessASTInputFile(CompOpts, InFile, ProgAction, Diags, FileMgr,
1199 Context);
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +00001200 continue;
1201 }
1202
Daniel Dunbar4cc1a252009-11-05 01:53:23 +00001203 // Reset the ID tables if we are reusing the SourceManager.
1204 if (i)
1205 SourceMgr.clearIDTables();
Mike Stump1eb44332009-09-09 15:08:12 +00001206
Chris Lattnerf63aea32009-03-04 21:40:56 +00001207 // Set up the preprocessor with these options.
Daniel Dunbar5fc7d342009-11-09 23:12:31 +00001208 llvm::OwningPtr<Preprocessor>
1209 PP(CreatePreprocessor(Diags, CompOpts.getLangOpts(),
Daniel Dunbarca11f612009-11-11 21:44:00 +00001210 CompOpts.getPreprocessorOpts(),
Daniel Dunbar961c76e2009-11-11 21:44:42 +00001211 CompOpts.getHeaderSearchOpts(),
Daniel Dunbarca11f612009-11-11 21:44:00 +00001212 CompOpts.getDependencyOutputOpts(),
Daniel Dunbar5814e652009-11-11 21:44:21 +00001213 *Target, SourceMgr, FileMgr));
1214
Daniel Dunbare0a95812009-11-10 22:09:38 +00001215 if (CompOpts.getPreprocessorOpts().getImplicitPCHInclude().empty()) {
Chris Lattner1b63e4f2009-06-14 01:54:56 +00001216 if (InitializeSourceManager(*PP.get(), InFile))
1217 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00001218
Chris Lattner1b63e4f2009-06-14 01:54:56 +00001219 // Initialize builtin info.
1220 PP->getBuiltinInfo().InitializeBuiltins(PP->getIdentifierTable(),
Chris Lattner1b63e4f2009-06-14 01:54:56 +00001221 PP->getLangOptions().NoBuiltin);
1222 }
Douglas Gregor14f79002009-04-10 03:52:48 +00001223
Chris Lattnerf63aea32009-03-04 21:40:56 +00001224 // Process the source file.
Daniel Dunbar26a0cac2009-11-09 22:46:17 +00001225 Diags.getClient()->BeginSourceFile(CompOpts.getLangOpts());
1226 ProcessInputFile(CompOpts, *PP, InFile, ProgAction, Context);
Daniel Dunbar227b2382009-11-09 22:45:57 +00001227 Diags.getClient()->EndSourceFile();
Reid Spencer5f016e22007-07-11 17:01:13 +00001228 }
Chris Lattner11215192008-03-14 06:12:05 +00001229
Daniel Dunbar9253e492009-11-10 00:46:12 +00001230 if (CompOpts.getDiagnosticOpts().ShowCarets)
Mike Stumpfc0fed32009-04-28 01:19:10 +00001231 if (unsigned NumDiagnostics = Diags.getNumDiagnostics())
1232 fprintf(stderr, "%d diagnostic%s generated.\n", NumDiagnostics,
1233 (NumDiagnostics == 1 ? "" : "s"));
Mike Stump1eb44332009-09-09 15:08:12 +00001234
Reid Spencer5f016e22007-07-11 17:01:13 +00001235 if (Stats) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001236 FileMgr.PrintStats();
1237 fprintf(stderr, "\n");
1238 }
Chris Lattner75a97cb2009-04-17 21:05:01 +00001239
1240 delete ClangFrontendTimer;
Mike Stump1eb44332009-09-09 15:08:12 +00001241
Daniel Dunbar276373d2008-10-27 22:10:13 +00001242 // If verifying diagnostics and we reached here, all is well.
1243 if (VerifyDiagnostics)
1244 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001245
Daniel Dunbar524b86f2008-10-28 00:38:08 +00001246 // Managed static deconstruction. Useful for making things like
1247 // -time-passes usable.
1248 llvm::llvm_shutdown();
1249
Daniel Dunbar8cb65622009-10-29 21:05:18 +00001250 return (Diags.getNumErrors() != 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00001251}