blob: bc4afc5ecb4213a39e8cd6cb89d0ff4adc21264e [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"
Eli Friedman0ec78fa2009-05-19 21:10:40 +000019#include "clang/Frontend/AnalysisConsumer.h"
Eli Friedman8ceb0d92009-05-18 23:02:01 +000020#include "clang/Frontend/ASTConsumers.h"
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +000021#include "clang/Frontend/ASTUnit.h"
Daniel Dunbardbf75fe2009-11-11 08:13:24 +000022#include "clang/Frontend/ChainedDiagnosticClient.h"
Daniel Dunbare29709f2009-11-09 20:55:08 +000023#include "clang/Frontend/CompilerInvocation.h"
Daniel Dunbareace8742009-11-04 06:24:30 +000024#include "clang/Frontend/DiagnosticOptions.h"
Douglas Gregor558cb562009-04-02 01:08:08 +000025#include "clang/Frontend/FixItRewriter.h"
Daniel Dunbar50f4f462009-03-12 10:14:16 +000026#include "clang/Frontend/FrontendDiagnostic.h"
Douglas Gregor2cf26342009-04-09 22:27:44 +000027#include "clang/Frontend/PCHReader.h"
Daniel Dunbar8863b982009-11-07 04:20:15 +000028#include "clang/Frontend/PathDiagnosticClients.h"
29#include "clang/Frontend/PreprocessorOptions.h"
Daniel Dunbare1bd4e62009-03-02 06:16:29 +000030#include "clang/Frontend/TextDiagnosticBuffer.h"
31#include "clang/Frontend/TextDiagnosticPrinter.h"
Argyrios Kyrtzidis34d25d82009-06-23 22:01:39 +000032#include "clang/Frontend/CommandLineSourceLoc.h"
Eli Friedmanb09f6e12009-05-19 04:14:29 +000033#include "clang/Frontend/Utils.h"
Ted Kremenek88f5cde2008-03-27 06:17:42 +000034#include "clang/Analysis/PathDiagnostic.h"
Chris Lattner8ee3c032008-02-06 02:01:47 +000035#include "clang/CodeGen/ModuleBuilder.h"
Douglas Gregor81b747b2009-09-17 21:32:03 +000036#include "clang/Sema/CodeCompleteConsumer.h"
Chris Lattnere91c1342008-02-06 00:23:21 +000037#include "clang/Sema/ParseAST.h"
Chris Lattner88eccaf2009-01-29 06:55:46 +000038#include "clang/Sema/SemaDiagnostic.h"
Chris Lattner556beb72007-09-15 22:56:56 +000039#include "clang/AST/ASTConsumer.h"
Chris Lattner1266eca2009-03-28 04:31:31 +000040#include "clang/AST/ASTContext.h"
41#include "clang/AST/Decl.h"
Chris Lattner682bf922009-03-29 16:50:03 +000042#include "clang/AST/DeclGroup.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000043#include "clang/Parse/Parser.h"
44#include "clang/Lex/HeaderSearch.h"
Chris Lattnerdb766842009-02-06 04:16:41 +000045#include "clang/Lex/LexDiagnostic.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000046#include "clang/Basic/FileManager.h"
47#include "clang/Basic/SourceManager.h"
48#include "clang/Basic/TargetInfo.h"
Daniel Dunbaraa338bc2009-05-06 04:07:06 +000049#include "clang/Basic/Version.h"
Owen Anderson42253cc2009-07-01 17:00:06 +000050#include "llvm/LLVMContext.h"
Chris Lattnerba0f25f2008-09-30 20:16:56 +000051#include "llvm/ADT/OwningPtr.h"
Chris Lattner8f3dab82007-12-15 23:20:07 +000052#include "llvm/ADT/SmallPtrSet.h"
Chris Lattnerba0f25f2008-09-30 20:16:56 +000053#include "llvm/ADT/StringExtras.h"
Daniel Dunbar868bd0a2009-05-06 03:16:41 +000054#include "llvm/ADT/StringMap.h"
Daniel Dunbar227b2382009-11-09 22:45:57 +000055#include "llvm/ADT/StringSwitch.h"
Chris Lattnerba0f25f2008-09-30 20:16:56 +000056#include "llvm/Config/config.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000057#include "llvm/Support/CommandLine.h"
Daniel Dunbar70121eb2009-08-10 03:40:28 +000058#include "llvm/Support/ErrorHandling.h"
Daniel Dunbar524b86f2008-10-28 00:38:08 +000059#include "llvm/Support/ManagedStatic.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000060#include "llvm/Support/MemoryBuffer.h"
Zhongxing Xu20922362008-11-26 05:23:17 +000061#include "llvm/Support/PluginLoader.h"
Chris Lattner09e94a32009-03-04 21:41:39 +000062#include "llvm/Support/PrettyStackTrace.h"
Chris Lattner47099742009-02-18 01:51:21 +000063#include "llvm/Support/Timer.h"
Chris Lattner0fa0daa2009-08-24 04:11:30 +000064#include "llvm/Support/raw_ostream.h"
Daniel Dunbare553a722008-10-02 01:21:33 +000065#include "llvm/System/Host.h"
Chris Lattnerdcaa0962008-03-03 03:16:03 +000066#include "llvm/System/Path.h"
Eli Friedman66d6f042009-05-18 22:20:00 +000067#include "llvm/System/Program.h"
Chris Lattnerba0f25f2008-09-30 20:16:56 +000068#include "llvm/System/Signals.h"
Chris Lattner2fe11942009-06-17 17:25:50 +000069#include "llvm/Target/TargetSelect.h"
Douglas Gregor26df2f02009-04-02 19:05:20 +000070#include <cstdlib>
Douglas Gregor44cf08e2009-05-03 03:52:38 +000071#if HAVE_SYS_TYPES_H
Douglas Gregor68a0d782009-05-02 00:03:46 +000072# include <sys/types.h>
73#endif
Douglas Gregor26df2f02009-04-02 19:05:20 +000074
Reid Spencer5f016e22007-07-11 17:01:13 +000075using namespace clang;
76
77//===----------------------------------------------------------------------===//
Douglas Gregor26df2f02009-04-02 19:05:20 +000078// Source Location Parser
79//===----------------------------------------------------------------------===//
80
Argyrios Kyrtzidis34d25d82009-06-23 22:01:39 +000081static bool ResolveParsedLocation(ParsedSourceLocation &ParsedLoc,
82 FileManager &FileMgr,
83 RequestedSourceLocation &Result) {
84 const FileEntry *File = FileMgr.getFile(ParsedLoc.FileName);
Douglas Gregor26df2f02009-04-02 19:05:20 +000085 if (!File)
86 return true;
87
88 Result.File = File;
Argyrios Kyrtzidis34d25d82009-06-23 22:01:39 +000089 Result.Line = ParsedLoc.Line;
90 Result.Column = ParsedLoc.Column;
Douglas Gregor26df2f02009-04-02 19:05:20 +000091 return false;
92}
93
Douglas Gregor26df2f02009-04-02 19:05:20 +000094//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +000095// Global options.
96//===----------------------------------------------------------------------===//
97
Chris Lattner47099742009-02-18 01:51:21 +000098/// ClangFrontendTimer - The front-end activities should charge time to it with
99/// TimeRegion. The -ftime-report option controls whether this will do
100/// anything.
101llvm::Timer *ClangFrontendTimer = 0;
102
Reid Spencer5f016e22007-07-11 17:01:13 +0000103static llvm::cl::opt<bool>
104Verbose("v", llvm::cl::desc("Enable verbose output"));
105static llvm::cl::opt<bool>
Mike Stump1eb44332009-09-09 15:08:12 +0000106Stats("print-stats",
Nate Begemanaabbb122007-12-30 01:38:50 +0000107 llvm::cl::desc("Print performance metrics and statistics"));
Daniel Dunbard3db4012008-10-16 16:54:18 +0000108static llvm::cl::opt<bool>
109DisableFree("disable-free",
110 llvm::cl::desc("Disable freeing of memory on exit"),
111 llvm::cl::init(false));
Daniel Dunbar57cbfc02009-04-27 21:19:07 +0000112static llvm::cl::opt<bool>
Mike Stump1eb44332009-09-09 15:08:12 +0000113EmptyInputOnly("empty-input-only",
Daniel Dunbar57cbfc02009-04-27 21:19:07 +0000114 llvm::cl::desc("Force running on an empty input file"));
Reid Spencer5f016e22007-07-11 17:01:13 +0000115
116enum ProgActions {
Steve Naroffb29b4272008-04-14 22:03:09 +0000117 RewriteObjC, // ObjC->C Rewriter.
Steve Naroff13188952008-09-18 14:10:13 +0000118 RewriteBlocks, // ObjC->C Rewriter for Blocks.
Chris Lattnerb57e3d42008-05-08 06:52:13 +0000119 RewriteMacros, // Expand macros but not #includes.
Chris Lattnerb13c5ee2008-10-12 05:29:20 +0000120 RewriteTest, // Rewriter playground
Douglas Gregor558cb562009-04-02 01:08:08 +0000121 FixIt, // Fix-It Rewriter
Ted Kremenek13e479b2008-03-19 07:53:42 +0000122 HTMLTest, // HTML displayer testing stuff.
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000123 EmitAssembly, // Emit a .s file.
Reid Spencer5f016e22007-07-11 17:01:13 +0000124 EmitLLVM, // Emit a .ll file.
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +0000125 EmitBC, // Emit a .bc file.
Mike Stump1eb44332009-09-09 15:08:12 +0000126 EmitLLVMOnly, // Generate LLVM IR, but do not
Ted Kremenek6a340832008-03-18 21:19:49 +0000127 EmitHTML, // Translate input source into HTML.
Chris Lattner3b427b32007-10-11 00:18:28 +0000128 ASTPrint, // Parse ASTs and print them.
Douglas Gregoree75c052009-05-21 20:55:50 +0000129 ASTPrintXML, // Parse ASTs and print them in XML.
Chris Lattner3b427b32007-10-11 00:18:28 +0000130 ASTDump, // Parse ASTs and dump them.
131 ASTView, // Parse ASTs and view them in Graphviz.
Zhongxing Xu2d75d6f2009-01-13 01:29:24 +0000132 PrintDeclContext, // Print DeclContext and their Decls.
Anders Carlsson78762eb2009-09-24 18:54:49 +0000133 DumpRecordLayouts, // Dump record layout information.
Reid Spencer5f016e22007-07-11 17:01:13 +0000134 ParsePrintCallbacks, // Parse and print each callback.
135 ParseSyntaxOnly, // Parse and perform semantic analysis.
136 ParseNoop, // Parse with noop callbacks.
137 RunPreprocessorOnly, // Just lex, no output.
138 PrintPreprocessedInput, // -E mode.
Chris Lattnerc106c102008-10-12 05:03:36 +0000139 DumpTokens, // Dump out preprocessed tokens.
140 DumpRawTokens, // Dump out raw tokens.
Mike Stump1eb44332009-09-09 15:08:12 +0000141 RunAnalysis, // Run one or more source code analyses.
Douglas Gregorbf1bd6e2009-04-02 23:43:50 +0000142 GeneratePTH, // Generate pre-tokenized header.
Douglas Gregor2cf26342009-04-09 22:27:44 +0000143 GeneratePCH, // Generate pre-compiled header.
Ted Kremenek7cae2f62008-10-23 23:36:29 +0000144 InheritanceView // View C++ inheritance for a specified class.
Reid Spencer5f016e22007-07-11 17:01:13 +0000145};
146
Mike Stump1eb44332009-09-09 15:08:12 +0000147static llvm::cl::opt<ProgActions>
Reid Spencer5f016e22007-07-11 17:01:13 +0000148ProgAction(llvm::cl::desc("Choose output type:"), llvm::cl::ZeroOrMore,
149 llvm::cl::init(ParseSyntaxOnly),
150 llvm::cl::values(
151 clEnumValN(RunPreprocessorOnly, "Eonly",
152 "Just run preprocessor, no output (for timings)"),
153 clEnumValN(PrintPreprocessedInput, "E",
154 "Run preprocessor, emit preprocessed file"),
Chris Lattnerc106c102008-10-12 05:03:36 +0000155 clEnumValN(DumpRawTokens, "dump-raw-tokens",
156 "Lex file in raw mode and dump raw tokens"),
Daniel Dunbard4270232009-01-20 23:17:32 +0000157 clEnumValN(RunAnalysis, "analyze",
158 "Run static analysis engine"),
Chris Lattnerc106c102008-10-12 05:03:36 +0000159 clEnumValN(DumpTokens, "dump-tokens",
Reid Spencer5f016e22007-07-11 17:01:13 +0000160 "Run preprocessor, dump internal rep of tokens"),
161 clEnumValN(ParseNoop, "parse-noop",
162 "Run parser with noop callbacks (for timings)"),
163 clEnumValN(ParseSyntaxOnly, "fsyntax-only",
164 "Run parser and perform semantic analysis"),
165 clEnumValN(ParsePrintCallbacks, "parse-print-callbacks",
166 "Run parser and print each callback invoked"),
Ted Kremenek6a340832008-03-18 21:19:49 +0000167 clEnumValN(EmitHTML, "emit-html",
168 "Output input source as HTML"),
Chris Lattner3b427b32007-10-11 00:18:28 +0000169 clEnumValN(ASTPrint, "ast-print",
170 "Build ASTs and then pretty-print them"),
Douglas Gregoree75c052009-05-21 20:55:50 +0000171 clEnumValN(ASTPrintXML, "ast-print-xml",
172 "Build ASTs and then print them in XML format"),
Chris Lattner3b427b32007-10-11 00:18:28 +0000173 clEnumValN(ASTDump, "ast-dump",
174 "Build ASTs and then debug dump them"),
Chris Lattnerea254db2007-10-11 00:37:43 +0000175 clEnumValN(ASTView, "ast-view",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000176 "Build ASTs and view them with GraphViz"),
Zhongxing Xu2d75d6f2009-01-13 01:29:24 +0000177 clEnumValN(PrintDeclContext, "print-decl-contexts",
Ted Kremenek08478eb2009-04-01 00:23:28 +0000178 "Print DeclContexts and their Decls"),
Anders Carlsson78762eb2009-09-24 18:54:49 +0000179 clEnumValN(DumpRecordLayouts, "dump-record-layouts",
180 "Dump record layout information"),
Douglas Gregorbf1bd6e2009-04-02 23:43:50 +0000181 clEnumValN(GeneratePTH, "emit-pth",
Ted Kremenek08478eb2009-04-01 00:23:28 +0000182 "Generate pre-tokenized header file"),
Douglas Gregor2cf26342009-04-09 22:27:44 +0000183 clEnumValN(GeneratePCH, "emit-pch",
184 "Generate pre-compiled header file"),
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000185 clEnumValN(EmitAssembly, "S",
186 "Emit native assembly code"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000187 clEnumValN(EmitLLVM, "emit-llvm",
Ted Kremenek27b07c52007-09-06 21:26:58 +0000188 "Build ASTs then convert to LLVM, emit .ll file"),
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +0000189 clEnumValN(EmitBC, "emit-llvm-bc",
190 "Build ASTs then convert to LLVM, emit .bc file"),
Daniel Dunbare8e26002009-02-26 22:39:37 +0000191 clEnumValN(EmitLLVMOnly, "emit-llvm-only",
192 "Build ASTs and convert to LLVM, discarding output"),
Chris Lattnerb13c5ee2008-10-12 05:29:20 +0000193 clEnumValN(RewriteTest, "rewrite-test",
194 "Rewriter playground"),
Steve Naroffb29b4272008-04-14 22:03:09 +0000195 clEnumValN(RewriteObjC, "rewrite-objc",
Chris Lattnerb57e3d42008-05-08 06:52:13 +0000196 "Rewrite ObjC into C (code rewriter example)"),
197 clEnumValN(RewriteMacros, "rewrite-macros",
198 "Expand macros without full preprocessing"),
Steve Naroff13188952008-09-18 14:10:13 +0000199 clEnumValN(RewriteBlocks, "rewrite-blocks",
200 "Rewrite Blocks to C"),
Douglas Gregor558cb562009-04-02 01:08:08 +0000201 clEnumValN(FixIt, "fixit",
202 "Apply fix-it advice to the input source"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000203 clEnumValEnd));
204
Ted Kremenekccc76472007-12-19 19:47:59 +0000205
206static llvm::cl::opt<std::string>
207OutputFile("o",
Ted Kremenek50b56412007-12-19 19:50:41 +0000208 llvm::cl::value_desc("path"),
Douglas Gregor370187c2009-04-22 21:45:53 +0000209 llvm::cl::desc("Specify output file"));
Ted Kremenek55af98c2008-04-14 18:40:58 +0000210
Ted Kremenekc2e72992008-12-02 19:57:31 +0000211
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000212enum CodeCompletionPrinter {
213 CCP_Debug,
214 CCP_CIndex
215};
216
Douglas Gregorb657f112009-09-22 21:11:38 +0000217static llvm::cl::opt<ParsedSourceLocation>
218CodeCompletionAt("code-completion-at",
219 llvm::cl::value_desc("file:line:column"),
220 llvm::cl::desc("Dump code-completion information at a location"));
Douglas Gregor81b747b2009-09-17 21:32:03 +0000221
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000222static llvm::cl::opt<CodeCompletionPrinter>
223CodeCompletionPrinter("code-completion-printer",
224 llvm::cl::desc("Choose output type:"),
225 llvm::cl::init(CCP_Debug),
226 llvm::cl::values(
227 clEnumValN(CCP_Debug, "debug",
228 "Debug code-completion results"),
229 clEnumValN(CCP_CIndex, "cindex",
230 "Code-completion results for the CIndex library"),
231 clEnumValEnd));
232
233static llvm::cl::opt<bool>
234CodeCompletionWantsMacros("code-completion-macros",
235 llvm::cl::desc("Include macros in code-completion results"));
236
Douglas Gregor81b747b2009-09-17 21:32:03 +0000237/// \brief Buld a new code-completion consumer that prints the results of
238/// code completion to standard output.
239static CodeCompleteConsumer *BuildPrintingCodeCompleter(Sema &S, void *) {
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000240 switch (CodeCompletionPrinter.getValue()) {
241 case CCP_Debug:
242 return new PrintingCodeCompleteConsumer(S, CodeCompletionWantsMacros,
243 llvm::outs());
244
245 case CCP_CIndex:
246 return new CIndexCodeCompleteConsumer(S, CodeCompletionWantsMacros,
247 llvm::outs());
248 };
249
250 return 0;
Douglas Gregor81b747b2009-09-17 21:32:03 +0000251}
252
Ted Kremenekc2e72992008-12-02 19:57:31 +0000253//===----------------------------------------------------------------------===//
254// PTH.
255//===----------------------------------------------------------------------===//
256
257static llvm::cl::opt<std::string>
258TokenCache("token-cache", llvm::cl::value_desc("path"),
259 llvm::cl::desc("Use specified token cache file"));
260
Sanjiv Guptae8b9f5b2008-05-08 08:54:20 +0000261//===----------------------------------------------------------------------===//
Ted Kremenek55af98c2008-04-14 18:40:58 +0000262// Diagnostic Options
263//===----------------------------------------------------------------------===//
264
Ted Kremenek41193e42007-09-26 19:42:19 +0000265static llvm::cl::opt<bool>
266VerifyDiagnostics("verify",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000267 llvm::cl::desc("Verify emitted diagnostics and warnings"));
Ted Kremenek41193e42007-09-26 19:42:19 +0000268
Nico Weberfd54ebc2008-08-05 23:33:20 +0000269static llvm::cl::opt<bool>
270NoShowColumn("fno-show-column",
271 llvm::cl::desc("Do not include column number on diagnostics"));
272
273static llvm::cl::opt<bool>
Chris Lattner65f5e642009-01-30 19:01:41 +0000274NoShowLocation("fno-show-source-location",
275 llvm::cl::desc("Do not include source location information with"
276 " diagnostics"));
277
278static llvm::cl::opt<bool>
Nico Weberfd54ebc2008-08-05 23:33:20 +0000279NoCaretDiagnostics("fno-caret-diagnostics",
280 llvm::cl::desc("Do not include source line and caret with"
281 " diagnostics"));
282
Chris Lattner1fbee5d2009-03-13 01:08:23 +0000283static llvm::cl::opt<bool>
Chris Lattneraa5bf2e2009-04-19 07:44:08 +0000284NoDiagnosticsFixIt("fno-diagnostics-fixit-info",
285 llvm::cl::desc("Do not include fixit information in"
286 " diagnostics"));
287
288static llvm::cl::opt<bool>
Chris Lattner182e0922009-04-21 05:34:31 +0000289PrintSourceRangeInfo("fdiagnostics-print-source-range-info",
290 llvm::cl::desc("Print source range spans in numeric form"));
291
Chris Lattnerd51d74a2009-04-16 05:44:38 +0000292static llvm::cl::opt<bool>
293PrintDiagnosticOption("fdiagnostics-show-option",
294 llvm::cl::desc("Print diagnostic name with mappable diagnostics"));
Nico Weberfd54ebc2008-08-05 23:33:20 +0000295
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000296static llvm::cl::opt<unsigned>
297MessageLength("fmessage-length",
Mike Stump1eb44332009-09-09 15:08:12 +0000298 llvm::cl::desc("Format message diagnostics so that they fit "
299 "within N columns or fewer, when possible."),
300 llvm::cl::value_desc("N"));
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000301
Torok Edwin603fca72009-06-04 07:18:23 +0000302static llvm::cl::opt<bool>
Daniel Dunbar838be482009-11-04 06:24:57 +0000303PrintColorDiagnostic("fcolor-diagnostics",
304 llvm::cl::desc("Use colors in diagnostics"));
305
Reid Spencer5f016e22007-07-11 17:01:13 +0000306//===----------------------------------------------------------------------===//
Ted Kremenek7cae2f62008-10-23 23:36:29 +0000307// C++ Visualization.
308//===----------------------------------------------------------------------===//
309
310static llvm::cl::opt<std::string>
311InheritanceViewCls("cxx-inheritance-view",
312 llvm::cl::value_desc("class name"),
Daniel Dunbard77b2512009-01-14 18:56:36 +0000313 llvm::cl::desc("View C++ inheritance for a specified class"));
Ted Kremenek7cae2f62008-10-23 23:36:29 +0000314
315//===----------------------------------------------------------------------===//
Douglas Gregor3573c0c2009-02-14 20:49:29 +0000316// Builtin Options
317//===----------------------------------------------------------------------===//
Chris Lattnerb2509e12009-02-18 01:12:43 +0000318
319static llvm::cl::opt<bool>
320TimeReport("ftime-report",
321 llvm::cl::desc("Print the amount of time each "
322 "phase of compilation takes"));
323
Douglas Gregor3573c0c2009-02-14 20:49:29 +0000324//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +0000325// Language Options
326//===----------------------------------------------------------------------===//
327
Reid Spencer5f016e22007-07-11 17:01:13 +0000328static llvm::cl::opt<LangKind>
329BaseLang("x", llvm::cl::desc("Base language to compile"),
330 llvm::cl::init(langkind_unspecified),
331 llvm::cl::values(clEnumValN(langkind_c, "c", "C"),
Nate Begeman4e3629e2009-06-25 22:43:10 +0000332 clEnumValN(langkind_ocl, "cl", "OpenCL C"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000333 clEnumValN(langkind_cxx, "c++", "C++"),
334 clEnumValN(langkind_objc, "objective-c", "Objective C"),
335 clEnumValN(langkind_objcxx,"objective-c++","Objective C++"),
Daniel Dunbard2ea3862009-01-29 23:50:47 +0000336 clEnumValN(langkind_c_cpp, "cpp-output",
Reid Spencer5f016e22007-07-11 17:01:13 +0000337 "Preprocessed C"),
Chris Lattnera778d7d2008-10-22 17:29:21 +0000338 clEnumValN(langkind_asm_cpp, "assembler-with-cpp",
339 "Preprocessed asm"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000340 clEnumValN(langkind_cxx_cpp, "c++-cpp-output",
Chris Lattnerc76d8072009-02-06 06:19:20 +0000341 "Preprocessed C++"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000342 clEnumValN(langkind_objc_cpp, "objective-c-cpp-output",
343 "Preprocessed Objective C"),
Chris Lattnerc76d8072009-02-06 06:19:20 +0000344 clEnumValN(langkind_objcxx_cpp, "objective-c++-cpp-output",
Reid Spencer5f016e22007-07-11 17:01:13 +0000345 "Preprocessed Objective C++"),
Daniel Dunbar0b5b0da2009-04-01 05:09:09 +0000346 clEnumValN(langkind_c, "c-header",
347 "C header"),
348 clEnumValN(langkind_objc, "objective-c-header",
349 "Objective-C header"),
350 clEnumValN(langkind_cxx, "c++-header",
351 "C++ header"),
352 clEnumValN(langkind_objcxx, "objective-c++-header",
353 "Objective-C++ header"),
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +0000354 clEnumValN(langkind_ast, "ast",
355 "Clang AST"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000356 clEnumValEnd));
357
Daniel Dunbar7c15e712009-10-30 18:12:31 +0000358static llvm::cl::opt<std::string>
359TargetTriple("triple",
360 llvm::cl::desc("Specify target triple (e.g. i686-apple-darwin9)"));
361
Daniel Dunbar56749082009-11-11 07:26:12 +0000362static llvm::cl::opt<std::string>
363TargetABI("target-abi",
364 llvm::cl::desc("Target a particular ABI type"));
Reid Spencer5f016e22007-07-11 17:01:13 +0000365
366//===----------------------------------------------------------------------===//
Chris Lattnere116ccf2009-04-21 05:40:52 +0000367// SourceManager initialization.
Reid Spencer5f016e22007-07-11 17:01:13 +0000368//===----------------------------------------------------------------------===//
369
Douglas Gregore1d918e2009-04-10 23:10:45 +0000370static bool InitializeSourceManager(Preprocessor &PP,
371 const std::string &InFile) {
372 // Figure out where to get and map in the main file.
373 SourceManager &SourceMgr = PP.getSourceManager();
374 FileManager &FileMgr = PP.getFileManager();
Daniel Dunbar57cbfc02009-04-27 21:19:07 +0000375
376 if (EmptyInputOnly) {
377 const char *EmptyStr = "";
Mike Stump1eb44332009-09-09 15:08:12 +0000378 llvm::MemoryBuffer *SB =
Daniel Dunbar57cbfc02009-04-27 21:19:07 +0000379 llvm::MemoryBuffer::getMemBuffer(EmptyStr, EmptyStr, "<empty input>");
380 SourceMgr.createMainFileIDForMemBuffer(SB);
381 } else if (InFile != "-") {
Douglas Gregore1d918e2009-04-10 23:10:45 +0000382 const FileEntry *File = FileMgr.getFile(InFile);
383 if (File) SourceMgr.createMainFileID(File, SourceLocation());
384 if (SourceMgr.getMainFileID().isInvalid()) {
Daniel Dunbar0f9fed72009-11-10 23:55:23 +0000385 PP.getDiagnostics().Report(diag::err_fe_error_reading) << InFile.c_str();
Douglas Gregore1d918e2009-04-10 23:10:45 +0000386 return true;
387 }
388 } else {
389 llvm::MemoryBuffer *SB = llvm::MemoryBuffer::getSTDIN();
Douglas Gregore1d918e2009-04-10 23:10:45 +0000390 SourceMgr.createMainFileIDForMemBuffer(SB);
391 if (SourceMgr.getMainFileID().isInvalid()) {
Daniel Dunbar0f9fed72009-11-10 23:55:23 +0000392 PP.getDiagnostics().Report(diag::err_fe_error_reading_stdin);
Douglas Gregore1d918e2009-04-10 23:10:45 +0000393 return true;
394 }
395 }
396
397 return false;
398}
399
Chris Lattneraa391972008-04-19 23:09:31 +0000400
Chris Lattnere116ccf2009-04-21 05:40:52 +0000401//===----------------------------------------------------------------------===//
402// Preprocessor Initialization
403//===----------------------------------------------------------------------===//
Sam Bishop1102d6b2008-04-14 14:41:57 +0000404
Chris Lattnere6113de2009-11-03 19:50:27 +0000405static llvm::cl::opt<bool>
Mike Stump1eb44332009-09-09 15:08:12 +0000406RelocatablePCH("relocatable-pch",
Douglas Gregore650c8c2009-07-07 00:12:59 +0000407 llvm::cl::desc("Whether to build a relocatable precompiled "
408 "header"));
Reid Spencer5f016e22007-07-11 17:01:13 +0000409
Reid Spencer5f016e22007-07-11 17:01:13 +0000410// Finally, implement the code that groks the options above.
Chris Lattner5f9eae52008-03-01 08:07:28 +0000411
Rafael Espindola1bb15a92009-10-05 13:12:17 +0000412// Add the clang headers, which are relative to the clang binary.
Daniel Dunbar750156a2009-11-07 04:19:57 +0000413std::string GetBuiltinIncludePath(const char *Argv0) {
414 llvm::sys::Path P =
415 llvm::sys::Path::GetMainExecutable(Argv0,
416 (void*)(intptr_t) GetBuiltinIncludePath);
Rafael Espindola1bb15a92009-10-05 13:12:17 +0000417
Daniel Dunbar750156a2009-11-07 04:19:57 +0000418 if (!P.isEmpty()) {
419 P.eraseComponent(); // Remove /clang from foo/bin/clang
420 P.eraseComponent(); // Remove /bin from foo/bin
Rafael Espindola1bb15a92009-10-05 13:12:17 +0000421
Daniel Dunbar750156a2009-11-07 04:19:57 +0000422 // Get foo/lib/clang/<version>/include
423 P.appendComponent("lib");
424 P.appendComponent("clang");
425 P.appendComponent(CLANG_VERSION_STRING);
426 P.appendComponent("include");
427 }
Rafael Espindola1bb15a92009-10-05 13:12:17 +0000428
Daniel Dunbar750156a2009-11-07 04:19:57 +0000429 return P.str();
Rafael Espindola1bb15a92009-10-05 13:12:17 +0000430}
431
Ted Kremeneka42cf2e2008-04-17 21:38:34 +0000432//===----------------------------------------------------------------------===//
Daniel Dunbar90b18272009-11-04 23:56:25 +0000433// Preprocessor construction
Ted Kremeneka42cf2e2008-04-17 21:38:34 +0000434//===----------------------------------------------------------------------===//
435
Daniel Dunbar90b18272009-11-04 23:56:25 +0000436static Preprocessor *
Daniel Dunbar5fc7d342009-11-09 23:12:31 +0000437CreatePreprocessor(Diagnostic &Diags, const LangOptions &LangInfo,
438 const PreprocessorOptions &PPOpts, TargetInfo &Target,
439 SourceManager &SourceMgr, HeaderSearch &HeaderInfo) {
Daniel Dunbar90b18272009-11-04 23:56:25 +0000440 PTHManager *PTHMgr = 0;
Daniel Dunbare0a95812009-11-10 22:09:38 +0000441 if (!TokenCache.empty() && !PPOpts.getImplicitPTHInclude().empty()) {
Daniel Dunbar90b18272009-11-04 23:56:25 +0000442 fprintf(stderr, "error: cannot use both -token-cache and -include-pth "
443 "options\n");
444 exit(1);
Ted Kremeneka42cf2e2008-04-17 21:38:34 +0000445 }
Daniel Dunbar90b18272009-11-04 23:56:25 +0000446
447 // Use PTH?
Daniel Dunbare0a95812009-11-10 22:09:38 +0000448 if (!TokenCache.empty() || !PPOpts.getImplicitPTHInclude().empty()) {
449 const std::string& x = TokenCache.empty() ?
450 PPOpts.getImplicitPTHInclude() : TokenCache;
Daniel Dunbar90b18272009-11-04 23:56:25 +0000451 PTHMgr = PTHManager::Create(x, &Diags,
452 TokenCache.empty() ? Diagnostic::Error
453 : Diagnostic::Warning);
454 }
455
456 if (Diags.hasErrorOccurred())
457 exit(1);
458
459 // Create the Preprocessor.
460 Preprocessor *PP = new Preprocessor(Diags, LangInfo, Target,
461 SourceMgr, HeaderInfo, PTHMgr);
462
463 // Note that this is different then passing PTHMgr to Preprocessor's ctor.
464 // That argument is used as the IdentifierInfoLookup argument to
465 // IdentifierTable's ctor.
466 if (PTHMgr) {
467 PTHMgr->setPreprocessor(PP);
468 PP->setPTHManager(PTHMgr);
469 }
470
Daniel Dunbar5fc7d342009-11-09 23:12:31 +0000471 InitializePreprocessor(*PP, PPOpts);
Daniel Dunbar90b18272009-11-04 23:56:25 +0000472
473 return PP;
Ted Kremeneka42cf2e2008-04-17 21:38:34 +0000474}
Reid Spencer5f016e22007-07-11 17:01:13 +0000475
Reid Spencer5f016e22007-07-11 17:01:13 +0000476//===----------------------------------------------------------------------===//
477// Basic Parser driver
478//===----------------------------------------------------------------------===//
479
Chris Lattner51574ea2008-04-19 23:25:44 +0000480static void ParseFile(Preprocessor &PP, MinimalAction *PA) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000481 Parser P(PP, *PA);
Ted Kremenek95041a22007-12-19 22:51:13 +0000482 PP.EnterMainSourceFile();
Mike Stump1eb44332009-09-09 15:08:12 +0000483
Reid Spencer5f016e22007-07-11 17:01:13 +0000484 // Parsing the specified input file.
485 P.ParseTranslationUnit();
486 delete PA;
487}
488
489//===----------------------------------------------------------------------===//
Douglas Gregor26df2f02009-04-02 19:05:20 +0000490// Fix-It Options
491//===----------------------------------------------------------------------===//
492static llvm::cl::list<ParsedSourceLocation>
493FixItAtLocations("fixit-at", llvm::cl::value_desc("source-location"),
494 llvm::cl::desc("Perform Fix-It modifications at the given source location"));
495
496//===----------------------------------------------------------------------===//
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000497// ObjC Rewriter Options
498//===----------------------------------------------------------------------===//
499static llvm::cl::opt<bool>
500SilenceRewriteMacroWarning("Wno-rewrite-macros", llvm::cl::init(false),
501 llvm::cl::desc("Silence ObjC rewriting warnings"));
502
503//===----------------------------------------------------------------------===//
Eli Friedman0eeb86e2009-05-19 01:17:04 +0000504// Warning Options
505//===----------------------------------------------------------------------===//
506
507// This gets all -W options, including -Werror, -W[no-]system-headers, etc. The
508// driver has stripped off -Wa,foo etc. The driver has also translated -W to
509// -Wextra, so we don't need to worry about it.
510static llvm::cl::list<std::string>
511OptWarnings("W", llvm::cl::Prefix, llvm::cl::ValueOptional);
512
513static llvm::cl::opt<bool> OptPedantic("pedantic");
514static llvm::cl::opt<bool> OptPedanticErrors("pedantic-errors");
515static llvm::cl::opt<bool> OptNoWarnings("w");
516
517//===----------------------------------------------------------------------===//
Eli Friedman12d3b1d2009-05-19 03:06:47 +0000518// Preprocessing (-E mode) Options
519//===----------------------------------------------------------------------===//
520static llvm::cl::opt<bool>
521DisableLineMarkers("P", llvm::cl::desc("Disable linemarker output in -E mode"));
522static llvm::cl::opt<bool>
523EnableCommentOutput("C", llvm::cl::desc("Enable comment output in -E mode"));
524static llvm::cl::opt<bool>
525EnableMacroCommentOutput("CC",
526 llvm::cl::desc("Enable comment output in -E mode, "
527 "even from macro expansions"));
528static llvm::cl::opt<bool>
529DumpMacros("dM", llvm::cl::desc("Print macro definitions in -E mode instead of"
530 " normal output"));
531static llvm::cl::opt<bool>
532DumpDefines("dD", llvm::cl::desc("Print macro definitions in -E mode in "
533 "addition to normal output"));
Eli Friedmanb5c8f8b2009-05-19 03:35:57 +0000534
535//===----------------------------------------------------------------------===//
536// Dependency file options
537//===----------------------------------------------------------------------===//
538static llvm::cl::opt<std::string>
539DependencyFile("dependency-file",
540 llvm::cl::desc("Filename (or -) to write dependency output to"));
541
542static llvm::cl::opt<bool>
543DependenciesIncludeSystemHeaders("sys-header-deps",
544 llvm::cl::desc("Include system headers in dependency output"));
545
546static llvm::cl::list<std::string>
547DependencyTargets("MT",
548 llvm::cl::desc("Specify target for dependency"));
549
Eli Friedmanb5c8f8b2009-05-19 03:35:57 +0000550static llvm::cl::opt<bool>
551PhonyDependencyTarget("MP",
552 llvm::cl::desc("Create phony target for each dependency "
553 "(other than main file)"));
554
Eli Friedman12d3b1d2009-05-19 03:06:47 +0000555//===----------------------------------------------------------------------===//
Eli Friedmane71b85f2009-05-19 10:18:02 +0000556// Analysis options
557//===----------------------------------------------------------------------===//
558
559static llvm::cl::list<Analyses>
560AnalysisList(llvm::cl::desc("Source Code Analysis - Checks and Analyses"),
561llvm::cl::values(
562#define ANALYSIS(NAME, CMDFLAG, DESC, SCOPE)\
563clEnumValN(NAME, CMDFLAG, DESC),
Eli Friedman0ec78fa2009-05-19 21:10:40 +0000564#include "clang/Frontend/Analyses.def"
Eli Friedmane71b85f2009-05-19 10:18:02 +0000565clEnumValEnd));
566
Mike Stump1eb44332009-09-09 15:08:12 +0000567static llvm::cl::opt<AnalysisStores>
Eli Friedmane71b85f2009-05-19 10:18:02 +0000568AnalysisStoreOpt("analyzer-store",
569 llvm::cl::desc("Source Code Analysis - Abstract Memory Store Models"),
570 llvm::cl::init(BasicStoreModel),
571 llvm::cl::values(
572#define ANALYSIS_STORE(NAME, CMDFLAG, DESC, CREATFN)\
573clEnumValN(NAME##Model, CMDFLAG, DESC),
Eli Friedman0ec78fa2009-05-19 21:10:40 +0000574#include "clang/Frontend/Analyses.def"
Eli Friedmane71b85f2009-05-19 10:18:02 +0000575clEnumValEnd));
576
Mike Stump1eb44332009-09-09 15:08:12 +0000577static llvm::cl::opt<AnalysisConstraints>
Eli Friedmane71b85f2009-05-19 10:18:02 +0000578AnalysisConstraintsOpt("analyzer-constraints",
579 llvm::cl::desc("Source Code Analysis - Symbolic Constraint Engines"),
580 llvm::cl::init(RangeConstraintsModel),
581 llvm::cl::values(
582#define ANALYSIS_CONSTRAINTS(NAME, CMDFLAG, DESC, CREATFN)\
583clEnumValN(NAME##Model, CMDFLAG, DESC),
Eli Friedman0ec78fa2009-05-19 21:10:40 +0000584#include "clang/Frontend/Analyses.def"
Eli Friedmane71b85f2009-05-19 10:18:02 +0000585clEnumValEnd));
586
587static llvm::cl::opt<AnalysisDiagClients>
588AnalysisDiagOpt("analyzer-output",
589 llvm::cl::desc("Source Code Analysis - Output Options"),
590 llvm::cl::init(PD_HTML),
591 llvm::cl::values(
592#define ANALYSIS_DIAGNOSTICS(NAME, CMDFLAG, DESC, CREATFN, AUTOCREATE)\
593clEnumValN(PD_##NAME, CMDFLAG, DESC),
Eli Friedman0ec78fa2009-05-19 21:10:40 +0000594#include "clang/Frontend/Analyses.def"
Eli Friedmane71b85f2009-05-19 10:18:02 +0000595clEnumValEnd));
596
597static llvm::cl::opt<bool>
598VisualizeEGDot("analyzer-viz-egraph-graphviz",
599 llvm::cl::desc("Display exploded graph using GraphViz"));
600
601static llvm::cl::opt<bool>
602VisualizeEGUbi("analyzer-viz-egraph-ubigraph",
603 llvm::cl::desc("Display exploded graph using Ubigraph"));
604
605static llvm::cl::opt<bool>
606AnalyzeAll("analyzer-opt-analyze-headers",
607 llvm::cl::desc("Force the static analyzer to analyze "
608 "functions defined in header files"));
609
610static llvm::cl::opt<bool>
611AnalyzerDisplayProgress("analyzer-display-progress",
612 llvm::cl::desc("Emit verbose output about the analyzer's progress."));
613
614static llvm::cl::opt<bool>
615PurgeDead("analyzer-purge-dead",
616 llvm::cl::init(true),
617 llvm::cl::desc("Remove dead symbols, bindings, and constraints before"
618 " processing a statement."));
619
620static llvm::cl::opt<bool>
621EagerlyAssume("analyzer-eagerly-assume",
622 llvm::cl::init(false),
623 llvm::cl::desc("Eagerly assume the truth/falseness of some "
624 "symbolic constraints."));
625
626static llvm::cl::opt<std::string>
627AnalyzeSpecificFunction("analyze-function",
628 llvm::cl::desc("Run analysis on specific function"));
629
630static llvm::cl::opt<bool>
631TrimGraph("trim-egraph",
632 llvm::cl::desc("Only show error-related paths in the analysis graph"));
633
634static AnalyzerOptions ReadAnalyzerOptions() {
635 AnalyzerOptions Opts;
636 Opts.AnalysisList = AnalysisList;
637 Opts.AnalysisStoreOpt = AnalysisStoreOpt;
638 Opts.AnalysisConstraintsOpt = AnalysisConstraintsOpt;
639 Opts.AnalysisDiagOpt = AnalysisDiagOpt;
640 Opts.VisualizeEGDot = VisualizeEGDot;
641 Opts.VisualizeEGUbi = VisualizeEGUbi;
642 Opts.AnalyzeAll = AnalyzeAll;
643 Opts.AnalyzerDisplayProgress = AnalyzerDisplayProgress;
644 Opts.PurgeDead = PurgeDead;
645 Opts.EagerlyAssume = EagerlyAssume;
646 Opts.AnalyzeSpecificFunction = AnalyzeSpecificFunction;
647 Opts.TrimGraph = TrimGraph;
648 return Opts;
649}
650
651//===----------------------------------------------------------------------===//
Chris Lattner75a97cb2009-04-17 21:05:01 +0000652// -dump-build-information Stuff
653//===----------------------------------------------------------------------===//
654
655static llvm::cl::opt<std::string>
656DumpBuildInformation("dump-build-information",
657 llvm::cl::value_desc("filename"),
658 llvm::cl::desc("output a dump of some build information to a file"));
659
660static llvm::raw_ostream *BuildLogFile = 0;
661
Daniel Dunbar227b2382009-11-09 22:45:57 +0000662static void SetUpBuildDumpLog(const DiagnosticOptions &DiagOpts,
Daniel Dunbare29709f2009-11-09 20:55:08 +0000663 unsigned argc, char **argv,
Chris Lattner75a97cb2009-04-17 21:05:01 +0000664 llvm::OwningPtr<DiagnosticClient> &DiagClient) {
Chris Lattner75a97cb2009-04-17 21:05:01 +0000665 std::string ErrorInfo;
Chris Lattner92bcc272009-08-23 02:59:41 +0000666 BuildLogFile = new llvm::raw_fd_ostream(DumpBuildInformation.c_str(),
Dan Gohmanb044c472009-08-25 15:36:09 +0000667 ErrorInfo);
Mike Stump1eb44332009-09-09 15:08:12 +0000668
Chris Lattner75a97cb2009-04-17 21:05:01 +0000669 if (!ErrorInfo.empty()) {
670 llvm::errs() << "error opening -dump-build-information file '"
671 << DumpBuildInformation << "', option ignored!\n";
672 delete BuildLogFile;
673 BuildLogFile = 0;
674 DumpBuildInformation = "";
675 return;
676 }
677
678 (*BuildLogFile) << "clang-cc command line arguments: ";
679 for (unsigned i = 0; i != argc; ++i)
680 (*BuildLogFile) << argv[i] << ' ';
681 (*BuildLogFile) << '\n';
Mike Stump1eb44332009-09-09 15:08:12 +0000682
Daniel Dunbardbf75fe2009-11-11 08:13:24 +0000683 // Chain in a diagnostic client which will log the diagnostics.
684 DiagnosticClient *Logger = new TextDiagnosticPrinter(*BuildLogFile, DiagOpts);
685 DiagClient.reset(new ChainedDiagnosticClient(DiagClient.take(), Logger));
Chris Lattner75a97cb2009-04-17 21:05:01 +0000686}
687
688
689
690//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +0000691// Main driver
692//===----------------------------------------------------------------------===//
693
Daniel Dunbare29709f2009-11-09 20:55:08 +0000694static llvm::raw_ostream *ComputeOutFile(const CompilerInvocation &CompOpts,
695 const std::string &InFile,
Chris Lattner92bcc272009-08-23 02:59:41 +0000696 const char *Extension,
Eli Friedman66d6f042009-05-18 22:20:00 +0000697 bool Binary,
698 llvm::sys::Path& OutPath) {
Chris Lattner92bcc272009-08-23 02:59:41 +0000699 llvm::raw_ostream *Ret;
Eli Friedman66d6f042009-05-18 22:20:00 +0000700 std::string OutFile;
Daniel Dunbare29709f2009-11-09 20:55:08 +0000701 if (!CompOpts.getOutputFile().empty())
702 OutFile = CompOpts.getOutputFile();
Chris Lattner92bcc272009-08-23 02:59:41 +0000703 else if (InFile == "-") {
704 OutFile = "-";
Eli Friedman66d6f042009-05-18 22:20:00 +0000705 } else if (Extension) {
706 llvm::sys::Path Path(InFile);
707 Path.eraseSuffix();
708 Path.appendSuffix(Extension);
Chris Lattnerd57a7ef2009-08-23 22:45:33 +0000709 OutFile = Path.str();
Eli Friedman66d6f042009-05-18 22:20:00 +0000710 } else {
Chris Lattner92bcc272009-08-23 02:59:41 +0000711 OutFile = "-";
Chris Lattner8a5c8092009-02-18 01:20:05 +0000712 }
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +0000713
Chris Lattner92bcc272009-08-23 02:59:41 +0000714 std::string Error;
715 Ret = new llvm::raw_fd_ostream(OutFile.c_str(), Error,
Dan Gohmanb044c472009-08-25 15:36:09 +0000716 (Binary ? llvm::raw_fd_ostream::F_Binary : 0));
Chris Lattner92bcc272009-08-23 02:59:41 +0000717 if (!Error.empty()) {
718 // FIXME: Don't fail this way.
719 llvm::errs() << "ERROR: " << Error << "\n";
720 ::exit(1);
Ted Kremenekdb094a22007-12-05 18:27:04 +0000721 }
Mike Stump1eb44332009-09-09 15:08:12 +0000722
Chris Lattner92bcc272009-08-23 02:59:41 +0000723 if (OutFile != "-")
724 OutPath = OutFile;
Eli Friedman66d6f042009-05-18 22:20:00 +0000725
726 return Ret;
Ted Kremenekdb094a22007-12-05 18:27:04 +0000727}
728
Daniel Dunbare29709f2009-11-09 20:55:08 +0000729static ASTConsumer *CreateConsumerAction(const CompilerInvocation &CompOpts,
730 Preprocessor &PP,
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000731 const std::string &InFile,
732 ProgActions PA,
733 llvm::OwningPtr<llvm::raw_ostream> &OS,
734 llvm::sys::Path &OutPath,
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000735 llvm::LLVMContext& Context) {
Ted Kremenek85888962008-10-21 00:54:44 +0000736 switch (PA) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000737 default:
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000738 return 0;
Eli Friedman66d6f042009-05-18 22:20:00 +0000739
740 case ASTPrint:
Daniel Dunbare29709f2009-11-09 20:55:08 +0000741 OS.reset(ComputeOutFile(CompOpts, InFile, 0, false, OutPath));
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000742 return CreateASTPrinter(OS.get());
Mike Stump1eb44332009-09-09 15:08:12 +0000743
Douglas Gregoree75c052009-05-21 20:55:50 +0000744 case ASTPrintXML:
Daniel Dunbare29709f2009-11-09 20:55:08 +0000745 OS.reset(ComputeOutFile(CompOpts, InFile, "xml", false, OutPath));
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000746 return CreateASTPrinterXML(OS.get());
Douglas Gregoree75c052009-05-21 20:55:50 +0000747
Eli Friedman66d6f042009-05-18 22:20:00 +0000748 case ASTDump:
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000749 return CreateASTDumper();
Eli Friedman66d6f042009-05-18 22:20:00 +0000750
Eli Friedman66d6f042009-05-18 22:20:00 +0000751 case ASTView:
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000752 return CreateASTViewer();
Eli Friedman66d6f042009-05-18 22:20:00 +0000753
Anders Carlsson78762eb2009-09-24 18:54:49 +0000754 case DumpRecordLayouts:
755 return CreateRecordLayoutDumper();
756
Eli Friedman66d6f042009-05-18 22:20:00 +0000757 case InheritanceView:
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000758 return CreateInheritanceViewer(InheritanceViewCls);
Eli Friedman66d6f042009-05-18 22:20:00 +0000759
760 case EmitAssembly:
761 case EmitLLVM:
Mike Stump1eb44332009-09-09 15:08:12 +0000762 case EmitBC:
Eli Friedman66d6f042009-05-18 22:20:00 +0000763 case EmitLLVMOnly: {
764 BackendAction Act;
765 if (ProgAction == EmitAssembly) {
766 Act = Backend_EmitAssembly;
Daniel Dunbare29709f2009-11-09 20:55:08 +0000767 OS.reset(ComputeOutFile(CompOpts, InFile, "s", true, OutPath));
Eli Friedman66d6f042009-05-18 22:20:00 +0000768 } else if (ProgAction == EmitLLVM) {
769 Act = Backend_EmitLL;
Daniel Dunbare29709f2009-11-09 20:55:08 +0000770 OS.reset(ComputeOutFile(CompOpts, InFile, "ll", true, OutPath));
Eli Friedman66d6f042009-05-18 22:20:00 +0000771 } else if (ProgAction == EmitLLVMOnly) {
772 Act = Backend_EmitNothing;
773 } else {
774 Act = Backend_EmitBC;
Daniel Dunbare29709f2009-11-09 20:55:08 +0000775 OS.reset(ComputeOutFile(CompOpts, InFile, "bc", true, OutPath));
Ted Kremenekdb094a22007-12-05 18:27:04 +0000776 }
Ted Kremenekfdfc1982007-12-19 22:24:34 +0000777
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000778 return CreateBackendConsumer(Act, PP.getDiagnostics(), PP.getLangOptions(),
Daniel Dunbar36f4ec32009-11-10 16:19:45 +0000779 CompOpts.getCompileOpts(), InFile, OS.get(),
780 Context);
Eli Friedman66d6f042009-05-18 22:20:00 +0000781 }
782
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000783 case RewriteObjC:
Daniel Dunbare29709f2009-11-09 20:55:08 +0000784 OS.reset(ComputeOutFile(CompOpts, InFile, "cpp", true, OutPath));
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000785 return CreateObjCRewriter(InFile, OS.get(), PP.getDiagnostics(),
786 PP.getLangOptions(), SilenceRewriteMacroWarning);
787
788 case RewriteBlocks:
789 return CreateBlockRewriter(InFile, PP.getDiagnostics(),
790 PP.getLangOptions());
Daniel Dunbar5ee0aa72009-11-11 00:54:56 +0000791
792 case ParseSyntaxOnly:
793 return new ASTConsumer();
794
795 case PrintDeclContext:
796 return CreateDeclContextPrinter();
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000797 }
798}
799
800/// ProcessInputFile - Process a single input file with the specified state.
801///
Daniel Dunbare29709f2009-11-09 20:55:08 +0000802static void ProcessInputFile(const CompilerInvocation &CompOpts,
803 Preprocessor &PP, const std::string &InFile,
Daniel Dunbar90b18272009-11-04 23:56:25 +0000804 ProgActions PA,
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000805 llvm::LLVMContext& Context) {
806 llvm::OwningPtr<llvm::raw_ostream> OS;
807 llvm::OwningPtr<ASTConsumer> Consumer;
808 bool ClearSourceMgr = false;
809 FixItRewriter *FixItRewrite = 0;
810 bool CompleteTranslationUnit = true;
811 llvm::sys::Path OutPath;
812
813 switch (PA) {
814 default:
Daniel Dunbare29709f2009-11-09 20:55:08 +0000815 Consumer.reset(CreateConsumerAction(CompOpts, PP, InFile, PA, OS, OutPath,
Daniel Dunbar26a0cac2009-11-09 22:46:17 +0000816 Context));
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000817
818 if (!Consumer.get()) {
Daniel Dunbar0f9fed72009-11-10 23:55:23 +0000819 PP.getDiagnostics().Report(diag::err_fe_invalid_ast_action);
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000820 return;
821 }
822
823 break;;
824
825 case EmitHTML:
Daniel Dunbare29709f2009-11-09 20:55:08 +0000826 OS.reset(ComputeOutFile(CompOpts, InFile, 0, true, OutPath));
Daniel Dunbar90b18272009-11-04 23:56:25 +0000827 Consumer.reset(CreateHTMLPrinter(OS.get(), PP));
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000828 break;
829
830 case RunAnalysis:
Daniel Dunbare29709f2009-11-09 20:55:08 +0000831 Consumer.reset(CreateAnalysisConsumer(PP, CompOpts.getOutputFile(),
Daniel Dunbar0794d8d2009-09-17 00:48:00 +0000832 ReadAnalyzerOptions()));
833 break;
834
Daniel Dunbarf7973292009-11-11 08:13:32 +0000835 case GeneratePCH: {
836 const std::string &Sysroot = CompOpts.getHeaderSearchOpts().Sysroot;
837 if (RelocatablePCH.getValue() && Sysroot.empty()) {
Douglas Gregore650c8c2009-07-07 00:12:59 +0000838 PP.Diag(SourceLocation(), diag::err_relocatable_without_without_isysroot);
839 RelocatablePCH.setValue(false);
840 }
Mike Stump1eb44332009-09-09 15:08:12 +0000841
Daniel Dunbare29709f2009-11-09 20:55:08 +0000842 OS.reset(ComputeOutFile(CompOpts, InFile, 0, true, OutPath));
Douglas Gregore650c8c2009-07-07 00:12:59 +0000843 if (RelocatablePCH.getValue())
Daniel Dunbarf7973292009-11-11 08:13:32 +0000844 Consumer.reset(CreatePCHGenerator(PP, OS.get(), Sysroot.c_str()));
Douglas Gregore650c8c2009-07-07 00:12:59 +0000845 else
846 Consumer.reset(CreatePCHGenerator(PP, OS.get()));
Eli Friedman66d6f042009-05-18 22:20:00 +0000847 CompleteTranslationUnit = false;
848 break;
Daniel Dunbarf7973292009-11-11 08:13:32 +0000849 }
Chris Lattnerc106c102008-10-12 05:03:36 +0000850 case DumpRawTokens: {
Chris Lattner47099742009-02-18 01:51:21 +0000851 llvm::TimeRegion Timer(ClangFrontendTimer);
Chris Lattnerc106c102008-10-12 05:03:36 +0000852 SourceManager &SM = PP.getSourceManager();
Chris Lattnerc106c102008-10-12 05:03:36 +0000853 // Start lexing the specified input file.
Chris Lattner025c3a62009-01-17 07:35:14 +0000854 Lexer RawLex(SM.getMainFileID(), SM, PP.getLangOptions());
Chris Lattnerc106c102008-10-12 05:03:36 +0000855 RawLex.SetKeepWhitespaceMode(true);
856
857 Token RawTok;
Chris Lattnerc106c102008-10-12 05:03:36 +0000858 RawLex.LexFromRawLexer(RawTok);
859 while (RawTok.isNot(tok::eof)) {
860 PP.DumpToken(RawTok, true);
861 fprintf(stderr, "\n");
862 RawLex.LexFromRawLexer(RawTok);
863 }
864 ClearSourceMgr = true;
865 break;
866 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000867 case DumpTokens: { // Token dump mode.
Chris Lattner47099742009-02-18 01:51:21 +0000868 llvm::TimeRegion Timer(ClangFrontendTimer);
Chris Lattnerd2177732007-07-20 16:59:19 +0000869 Token Tok;
Chris Lattnerc106c102008-10-12 05:03:36 +0000870 // Start preprocessing the specified input file.
Ted Kremenek95041a22007-12-19 22:51:13 +0000871 PP.EnterMainSourceFile();
Reid Spencer5f016e22007-07-11 17:01:13 +0000872 do {
873 PP.Lex(Tok);
874 PP.DumpToken(Tok, true);
875 fprintf(stderr, "\n");
Chris Lattner057aaf62007-10-09 18:03:42 +0000876 } while (Tok.isNot(tok::eof));
Chris Lattnerbd247762007-07-22 06:05:44 +0000877 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000878 break;
879 }
Chris Lattnerd1d64a02009-04-27 21:45:14 +0000880 case RunPreprocessorOnly:
Reid Spencer5f016e22007-07-11 17:01:13 +0000881 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000882
Douglas Gregorbf1bd6e2009-04-02 23:43:50 +0000883 case GeneratePTH: {
Chris Lattner47099742009-02-18 01:51:21 +0000884 llvm::TimeRegion Timer(ClangFrontendTimer);
Daniel Dunbare29709f2009-11-09 20:55:08 +0000885 if (CompOpts.getOutputFile().empty() || CompOpts.getOutputFile() == "-") {
Eli Friedmanf54fce82009-05-19 01:02:07 +0000886 // FIXME: Don't fail this way.
887 // FIXME: Verify that we can actually seek in the given file.
Chris Lattner92bcc272009-08-23 02:59:41 +0000888 llvm::errs() << "ERROR: PTH requires an seekable file for output!\n";
Eli Friedmanf54fce82009-05-19 01:02:07 +0000889 ::exit(1);
890 }
Daniel Dunbare29709f2009-11-09 20:55:08 +0000891 OS.reset(ComputeOutFile(CompOpts, InFile, 0, true, OutPath));
Eli Friedmanf54fce82009-05-19 01:02:07 +0000892 CacheTokens(PP, static_cast<llvm::raw_fd_ostream*>(OS.get()));
Ted Kremenek85888962008-10-21 00:54:44 +0000893 ClearSourceMgr = true;
894 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000895 }
Douglas Gregor6ab35242009-04-09 21:40:53 +0000896
Chris Lattnercc7dea82009-04-27 22:02:30 +0000897 case PrintPreprocessedInput:
Daniel Dunbare29709f2009-11-09 20:55:08 +0000898 OS.reset(ComputeOutFile(CompOpts, InFile, 0, true, OutPath));
Reid Spencer5f016e22007-07-11 17:01:13 +0000899 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000900
Chris Lattnerd1d64a02009-04-27 21:45:14 +0000901 case ParseNoop:
Reid Spencer5f016e22007-07-11 17:01:13 +0000902 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000903
Chris Lattner47099742009-02-18 01:51:21 +0000904 case ParsePrintCallbacks: {
905 llvm::TimeRegion Timer(ClangFrontendTimer);
Daniel Dunbare29709f2009-11-09 20:55:08 +0000906 OS.reset(ComputeOutFile(CompOpts, InFile, 0, true, OutPath));
Eli Friedmanf54fce82009-05-19 01:02:07 +0000907 ParseFile(PP, CreatePrintParserActionsAction(PP, OS.get()));
Chris Lattnerbd247762007-07-22 06:05:44 +0000908 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000909 break;
Chris Lattner47099742009-02-18 01:51:21 +0000910 }
911
Chris Lattnerb57e3d42008-05-08 06:52:13 +0000912 case RewriteMacros:
Daniel Dunbare29709f2009-11-09 20:55:08 +0000913 OS.reset(ComputeOutFile(CompOpts, InFile, 0, true, OutPath));
Eli Friedmanf54fce82009-05-19 01:02:07 +0000914 RewriteMacrosInInput(PP, OS.get());
Chris Lattnerb57e3d42008-05-08 06:52:13 +0000915 ClearSourceMgr = true;
916 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000917
Eli Friedmanf54fce82009-05-19 01:02:07 +0000918 case RewriteTest:
Daniel Dunbare29709f2009-11-09 20:55:08 +0000919 OS.reset(ComputeOutFile(CompOpts, InFile, 0, true, OutPath));
Eli Friedmanf54fce82009-05-19 01:02:07 +0000920 DoRewriteTest(PP, OS.get());
Chris Lattnerb13c5ee2008-10-12 05:29:20 +0000921 ClearSourceMgr = true;
922 break;
Douglas Gregor558cb562009-04-02 01:08:08 +0000923
924 case FixIt:
Douglas Gregor558cb562009-04-02 01:08:08 +0000925 Consumer.reset(new ASTConsumer());
Douglas Gregorde4bf6a2009-04-02 17:13:00 +0000926 FixItRewrite = new FixItRewriter(PP.getDiagnostics(),
Chris Lattner2c78b872009-04-14 23:22:57 +0000927 PP.getSourceManager(),
928 PP.getLangOptions());
Douglas Gregor558cb562009-04-02 01:08:08 +0000929 break;
Chris Lattner47099742009-02-18 01:51:21 +0000930 }
Ted Kremenek46157b52009-01-28 04:29:29 +0000931
Chris Lattner1aee61a2009-04-27 21:25:27 +0000932 if (FixItAtLocations.size() > 0) {
933 // Even without the "-fixit" flag, with may have some specific
934 // locations where the user has requested fixes. Process those
935 // locations now.
936 if (!FixItRewrite)
937 FixItRewrite = new FixItRewriter(PP.getDiagnostics(),
938 PP.getSourceManager(),
939 PP.getLangOptions());
Chris Lattner9ecd26a2009-03-28 01:37:17 +0000940
Chris Lattner1aee61a2009-04-27 21:25:27 +0000941 bool AddedFixitLocation = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000942 for (unsigned Idx = 0, Last = FixItAtLocations.size();
Chris Lattner1aee61a2009-04-27 21:25:27 +0000943 Idx != Last; ++Idx) {
944 RequestedSourceLocation Requested;
Argyrios Kyrtzidis34d25d82009-06-23 22:01:39 +0000945 if (ResolveParsedLocation(FixItAtLocations[Idx],
946 PP.getFileManager(), Requested)) {
Chris Lattner1aee61a2009-04-27 21:25:27 +0000947 fprintf(stderr, "FIX-IT could not find file \"%s\"\n",
948 FixItAtLocations[Idx].FileName.c_str());
949 } else {
950 FixItRewrite->addFixItLocation(Requested);
951 AddedFixitLocation = true;
Douglas Gregor26df2f02009-04-02 19:05:20 +0000952 }
953 }
954
Chris Lattner1aee61a2009-04-27 21:25:27 +0000955 if (!AddedFixitLocation) {
956 // All of the fix-it locations were bad. Don't fix anything.
957 delete FixItRewrite;
958 FixItRewrite = 0;
959 }
960 }
961
962 llvm::OwningPtr<ASTContext> ContextOwner;
Chris Lattnerd1d64a02009-04-27 21:45:14 +0000963 if (Consumer)
Chris Lattner9ecd26a2009-03-28 01:37:17 +0000964 ContextOwner.reset(new ASTContext(PP.getLangOptions(),
965 PP.getSourceManager(),
966 PP.getTargetInfo(),
967 PP.getIdentifierTable(),
968 PP.getSelectorTable(),
Chris Lattner1b63e4f2009-06-14 01:54:56 +0000969 PP.getBuiltinInfo(),
Douglas Gregor2deaea32009-04-22 18:49:13 +0000970 /* FreeMemory = */ !DisableFree,
Chris Lattner1b63e4f2009-06-14 01:54:56 +0000971 /* size_reserve = */0));
Mike Stump1eb44332009-09-09 15:08:12 +0000972
Chris Lattnercc7dea82009-04-27 22:02:30 +0000973 llvm::OwningPtr<PCHReader> Reader;
974 llvm::OwningPtr<ExternalASTSource> Source;
Mike Stump1eb44332009-09-09 15:08:12 +0000975
Daniel Dunbare0a95812009-11-10 22:09:38 +0000976 const std::string &ImplicitPCHInclude =
977 CompOpts.getPreprocessorOpts().getImplicitPCHInclude();
978 if (!ImplicitPCHInclude.empty()) {
Douglas Gregore650c8c2009-07-07 00:12:59 +0000979 // If the user specified -isysroot, it will be used for relocatable PCH
980 // files.
Daniel Dunbarf7973292009-11-11 08:13:32 +0000981 const char *isysrootPCH = CompOpts.getHeaderSearchOpts().Sysroot.c_str();
982 if (isysrootPCH[0] == '\0')
983 isysrootPCH = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000984
Douglas Gregore650c8c2009-07-07 00:12:59 +0000985 Reader.reset(new PCHReader(PP, ContextOwner.get(), isysrootPCH));
Mike Stump1eb44332009-09-09 15:08:12 +0000986
Chris Lattnerd1d64a02009-04-27 21:45:14 +0000987 // The user has asked us to include a precompiled header. Load
988 // the precompiled header into the AST context.
Daniel Dunbare0a95812009-11-10 22:09:38 +0000989 switch (Reader->ReadPCH(ImplicitPCHInclude)) {
Chris Lattnerd1d64a02009-04-27 21:45:14 +0000990 case PCHReader::Success: {
Douglas Gregore721f952009-04-28 18:58:38 +0000991 // Set the predefines buffer as suggested by the PCH
992 // reader. Typically, the predefines buffer will be empty.
993 PP.setPredefines(Reader->getSuggestedPredefines());
994
Chris Lattnerd1d64a02009-04-27 21:45:14 +0000995 // Attach the PCH reader to the AST context as an external AST
996 // source, so that declarations will be deserialized from the
997 // PCH file as needed.
Chris Lattnercc7dea82009-04-27 22:02:30 +0000998 if (ContextOwner) {
999 Source.reset(Reader.take());
Douglas Gregore1d918e2009-04-10 23:10:45 +00001000 ContextOwner->setExternalSource(Source);
Chris Lattnercc7dea82009-04-27 22:02:30 +00001001 }
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001002 break;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001003 }
1004
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001005 case PCHReader::Failure:
1006 // Unrecoverable failure: don't even try to process the input
1007 // file.
1008 return;
1009
1010 case PCHReader::IgnorePCH:
Douglas Gregor1ab86ac2009-04-28 22:01:16 +00001011 // No suitable PCH file could be found. Return an error.
1012 return;
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001013 }
1014
1015 // Finish preprocessor initialization. We do this now (rather
1016 // than earlier) because this initialization creates new source
1017 // location entries in the source manager, which must come after
1018 // the source location entries for the PCH file.
1019 if (InitializeSourceManager(PP, InFile))
1020 return;
Ted Kremenek46157b52009-01-28 04:29:29 +00001021 }
Daniel Dunbarbea5a842009-10-29 01:53:18 +00001022
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001023 // If we have an ASTConsumer, run the parser with it.
Douglas Gregor81b747b2009-09-17 21:32:03 +00001024 if (Consumer) {
1025 CodeCompleteConsumer *(*CreateCodeCompleter)(Sema &, void *) = 0;
1026 void *CreateCodeCompleterData = 0;
Daniel Dunbarbea5a842009-10-29 01:53:18 +00001027
Douglas Gregorb657f112009-09-22 21:11:38 +00001028 if (!CodeCompletionAt.FileName.empty()) {
1029 // Tell the source manager to chop off the given file at a specific
1030 // line and column.
Daniel Dunbarbea5a842009-10-29 01:53:18 +00001031 if (const FileEntry *Entry
Douglas Gregorb657f112009-09-22 21:11:38 +00001032 = PP.getFileManager().getFile(CodeCompletionAt.FileName)) {
1033 // Truncate the named file at the given line/column.
1034 PP.getSourceManager().truncateFileAt(Entry, CodeCompletionAt.Line,
1035 CodeCompletionAt.Column);
Daniel Dunbarbea5a842009-10-29 01:53:18 +00001036
Douglas Gregorb657f112009-09-22 21:11:38 +00001037 // Set up the creation routine for code-completion.
1038 CreateCodeCompleter = BuildPrintingCodeCompleter;
1039 } else {
Daniel Dunbar0f9fed72009-11-10 23:55:23 +00001040 PP.getDiagnostics().Report(diag::err_fe_invalid_code_complete_file)
Douglas Gregorb657f112009-09-22 21:11:38 +00001041 << CodeCompletionAt.FileName;
1042 }
Douglas Gregor81b747b2009-09-17 21:32:03 +00001043 }
1044
Mike Stump1eb44332009-09-09 15:08:12 +00001045 ParseAST(PP, Consumer.get(), *ContextOwner.get(), Stats,
Douglas Gregor81b747b2009-09-17 21:32:03 +00001046 CompleteTranslationUnit,
1047 CreateCodeCompleter, CreateCodeCompleterData);
1048 }
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001049
Daniel Dunbar593c41f2009-11-04 23:41:40 +00001050 // Perform post processing actions and actions which don't use a consumer.
1051 switch (PA) {
1052 default: break;
1053
1054 case RunPreprocessorOnly: { // Just lex as fast as we can, no output.
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001055 llvm::TimeRegion Timer(ClangFrontendTimer);
1056 Token Tok;
1057 // Start parsing the specified input file.
1058 PP.EnterMainSourceFile();
1059 do {
1060 PP.Lex(Tok);
1061 } while (Tok.isNot(tok::eof));
1062 ClearSourceMgr = true;
Daniel Dunbar593c41f2009-11-04 23:41:40 +00001063 break;
1064 }
1065
1066 case ParseNoop: {
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001067 llvm::TimeRegion Timer(ClangFrontendTimer);
1068 ParseFile(PP, new MinimalAction(PP));
1069 ClearSourceMgr = true;
Daniel Dunbar593c41f2009-11-04 23:41:40 +00001070 break;
1071 }
1072
1073 case PrintPreprocessedInput: {
Chris Lattnercc7dea82009-04-27 22:02:30 +00001074 llvm::TimeRegion Timer(ClangFrontendTimer);
Eli Friedman12d3b1d2009-05-19 03:06:47 +00001075 if (DumpMacros)
1076 DoPrintMacros(PP, OS.get());
1077 else
1078 DoPrintPreprocessedInput(PP, OS.get(), EnableCommentOutput,
1079 EnableMacroCommentOutput,
1080 DisableLineMarkers, DumpDefines);
Chris Lattnercc7dea82009-04-27 22:02:30 +00001081 ClearSourceMgr = true;
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001082 }
Mike Stump1eb44332009-09-09 15:08:12 +00001083
Daniel Dunbar593c41f2009-11-04 23:41:40 +00001084 }
1085
Chris Lattner1aee61a2009-04-27 21:25:27 +00001086 if (FixItRewrite)
Daniel Dunbare29709f2009-11-09 20:55:08 +00001087 FixItRewrite->WriteFixedFile(InFile, CompOpts.getOutputFile());
Daniel Dunbar70186ab2009-07-29 02:40:09 +00001088
1089 // Disable the consumer prior to the context, the consumer may perform actions
1090 // in its destructor which require the context.
1091 if (DisableFree)
1092 Consumer.take();
1093 else
1094 Consumer.reset();
Mike Stump1eb44332009-09-09 15:08:12 +00001095
Chris Lattner1aee61a2009-04-27 21:25:27 +00001096 // If in -disable-free mode, don't deallocate ASTContext.
1097 if (DisableFree)
1098 ContextOwner.take();
1099 else
1100 ContextOwner.reset(); // Delete ASTContext
Eli Friedman66d6f042009-05-18 22:20:00 +00001101
Daniel Dunbar879c3ea2008-10-27 22:03:52 +00001102 if (VerifyDiagnostics)
Daniel Dunbar276373d2008-10-27 22:10:13 +00001103 if (CheckDiagnostics(PP))
1104 exit(1);
Chris Lattnere66b65c2008-02-06 01:42:25 +00001105
Reid Spencer5f016e22007-07-11 17:01:13 +00001106 if (Stats) {
Ted Kremenekfdfc1982007-12-19 22:24:34 +00001107 fprintf(stderr, "\nSTATISTICS FOR '%s':\n", InFile.c_str());
Reid Spencer5f016e22007-07-11 17:01:13 +00001108 PP.PrintStats();
1109 PP.getIdentifierTable().PrintStats();
Chris Lattnerdee73592007-12-15 20:48:40 +00001110 PP.getHeaderSearchInfo().PrintStats();
Ted Kremenek1b95a652009-01-09 18:20:21 +00001111 PP.getSourceManager().PrintStats();
Reid Spencer5f016e22007-07-11 17:01:13 +00001112 fprintf(stderr, "\n");
1113 }
Chris Lattnerbd247762007-07-22 06:05:44 +00001114
Mike Stump1eb44332009-09-09 15:08:12 +00001115 // For a multi-file compilation, some things are ok with nuking the source
Chris Lattnerbd247762007-07-22 06:05:44 +00001116 // manager tables, other require stable fileid/macroid's across multiple
1117 // files.
Chris Lattnerdee73592007-12-15 20:48:40 +00001118 if (ClearSourceMgr)
1119 PP.getSourceManager().clearIDTables();
Daniel Dunbard68ba0e2008-11-11 06:35:39 +00001120
Eli Friedman66d6f042009-05-18 22:20:00 +00001121 // Always delete the output stream because we don't want to leak file
1122 // handles. Also, we don't want to try to erase an open file.
1123 OS.reset();
1124
Daniel Dunbar8cb65622009-10-29 21:05:18 +00001125 // If we had errors, try to erase the output file.
1126 if (PP.getDiagnostics().getNumErrors() && !OutPath.isEmpty())
Eli Friedman66d6f042009-05-18 22:20:00 +00001127 OutPath.eraseFromDisk();
Reid Spencer5f016e22007-07-11 17:01:13 +00001128}
1129
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +00001130/// ProcessInputFile - Process a single AST input file with the specified state.
1131///
Daniel Dunbare29709f2009-11-09 20:55:08 +00001132static void ProcessASTInputFile(const CompilerInvocation &CompOpts,
1133 const std::string &InFile, ProgActions PA,
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +00001134 Diagnostic &Diags, FileManager &FileMgr,
1135 llvm::LLVMContext& Context) {
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +00001136 std::string Error;
Steve Naroff36c44642009-10-19 14:34:22 +00001137 llvm::OwningPtr<ASTUnit> AST(ASTUnit::LoadFromPCHFile(InFile, &Error));
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +00001138 if (!AST) {
Daniel Dunbar0f9fed72009-11-10 23:55:23 +00001139 Diags.Report(diag::err_fe_invalid_ast_file) << Error;
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +00001140 return;
1141 }
1142
1143 Preprocessor &PP = AST->getPreprocessor();
1144
1145 llvm::OwningPtr<llvm::raw_ostream> OS;
1146 llvm::sys::Path OutPath;
Daniel Dunbare29709f2009-11-09 20:55:08 +00001147 llvm::OwningPtr<ASTConsumer> Consumer(CreateConsumerAction(CompOpts, PP,
1148 InFile, PA, OS,
Daniel Dunbar26a0cac2009-11-09 22:46:17 +00001149 OutPath, Context));
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +00001150
1151 if (!Consumer.get()) {
Daniel Dunbar0f9fed72009-11-10 23:55:23 +00001152 Diags.Report(diag::err_fe_invalid_ast_action);
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +00001153 return;
1154 }
1155
Daniel Dunbara674bf42009-09-21 03:03:56 +00001156 // Set the main file ID to an empty file.
1157 //
1158 // FIXME: We probably shouldn't need this, but for now this is the simplest
1159 // way to reuse the logic in ParseAST.
1160 const char *EmptyStr = "";
1161 llvm::MemoryBuffer *SB =
1162 llvm::MemoryBuffer::getMemBuffer(EmptyStr, EmptyStr, "<dummy input>");
1163 AST->getSourceManager().createMainFileIDForMemBuffer(SB);
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +00001164
Daniel Dunbara674bf42009-09-21 03:03:56 +00001165 // Stream the input AST to the consumer.
Daniel Dunbarefcbe942009-11-05 02:42:12 +00001166 Diags.getClient()->BeginSourceFile(PP.getLangOptions());
Daniel Dunbara674bf42009-09-21 03:03:56 +00001167 ParseAST(PP, Consumer.get(), AST->getASTContext(), Stats);
Daniel Dunbarefcbe942009-11-05 02:42:12 +00001168 Diags.getClient()->EndSourceFile();
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +00001169
1170 // Release the consumer and the AST, in that order since the consumer may
1171 // perform actions in its destructor which require the context.
1172 if (DisableFree) {
1173 Consumer.take();
1174 AST.take();
1175 } else {
1176 Consumer.reset();
1177 AST.reset();
1178 }
1179
1180 // Always delete the output stream because we don't want to leak file
1181 // handles. Also, we don't want to try to erase an open file.
1182 OS.reset();
1183
Daniel Dunbar8cb65622009-10-29 21:05:18 +00001184 // If we had errors, try to erase the output file.
1185 if (PP.getDiagnostics().getNumErrors() && !OutPath.isEmpty())
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +00001186 OutPath.eraseFromDisk();
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +00001187}
1188
Reid Spencer5f016e22007-07-11 17:01:13 +00001189static llvm::cl::list<std::string>
1190InputFilenames(llvm::cl::Positional, llvm::cl::desc("<input files>"));
1191
Daniel Dunbar70121eb2009-08-10 03:40:28 +00001192static void LLVMErrorHandler(void *UserData, const std::string &Message) {
1193 Diagnostic &Diags = *static_cast<Diagnostic*>(UserData);
1194
Daniel Dunbar0f9fed72009-11-10 23:55:23 +00001195 Diags.Report(diag::err_fe_error_backend) << Message;
Daniel Dunbar70121eb2009-08-10 03:40:28 +00001196
1197 // We cannot recover from llvm errors.
1198 exit(1);
1199}
1200
Daniel Dunbar227b2382009-11-09 22:45:57 +00001201static LangKind GetLanguage() {
1202 // If -x was given, that's the language.
1203 if (BaseLang != langkind_unspecified)
1204 return BaseLang;
Daniel Dunbare29709f2009-11-09 20:55:08 +00001205
Daniel Dunbar227b2382009-11-09 22:45:57 +00001206 // Otherwise guess it from the input filenames;
1207 LangKind LK = langkind_unspecified;
1208 for (unsigned i = 0, e = InputFilenames.size(); i != e; ++i) {
1209 llvm::StringRef Name(InputFilenames[i]);
1210 LangKind ThisKind = llvm::StringSwitch<LangKind>(Name.rsplit('.').second)
1211 .Case("ast", langkind_ast)
1212 .Case("c", langkind_c)
1213 .Cases("S", "s", langkind_asm_cpp)
1214 .Case("i", langkind_c_cpp)
1215 .Case("ii", langkind_cxx_cpp)
1216 .Case("m", langkind_objc)
1217 .Case("mi", langkind_objc_cpp)
1218 .Cases("mm", "M", langkind_objcxx)
1219 .Case("mii", langkind_objcxx_cpp)
1220 .Case("C", langkind_cxx)
1221 .Cases("C", "cc", "cp", langkind_cxx)
1222 .Cases("cpp", "CPP", "c++", "cxx", langkind_cxx)
1223 .Case("cl", langkind_ocl)
1224 .Default(langkind_c);
1225
1226 if (LK != langkind_unspecified && ThisKind != LK) {
1227 llvm::errs() << "error: cannot have multiple input files of distinct "
1228 << "language kinds without -x\n";
1229 exit(1);
1230 }
1231
1232 LK = ThisKind;
1233 }
1234
1235 return LK;
1236}
1237
1238static void ConstructDiagnosticOptions(DiagnosticOptions &Opts) {
Daniel Dunbare29709f2009-11-09 20:55:08 +00001239 // Initialize the diagnostic options.
Daniel Dunbar227b2382009-11-09 22:45:57 +00001240 Opts.ShowColumn = !NoShowColumn;
1241 Opts.ShowLocation = !NoShowLocation;
1242 Opts.ShowCarets = !NoCaretDiagnostics;
1243 Opts.ShowFixits = !NoDiagnosticsFixIt;
1244 Opts.ShowSourceRanges = PrintSourceRangeInfo;
1245 Opts.ShowOptionNames = PrintDiagnosticOption;
1246 Opts.ShowColors = PrintColorDiagnostic;
1247 Opts.MessageLength = MessageLength;
1248}
1249
Daniel Dunbar0498cfc2009-11-10 19:51:53 +00001250static void FinalizeCompileOptions(CompileOptions &Opts,
1251 const LangOptions &Lang) {
1252 if (Lang.NoBuiltin)
1253 Opts.SimplifyLibCalls = 0;
1254 if (Lang.CPlusPlus)
1255 Opts.NoCommon = 1;
1256
1257 // Handle -ftime-report.
1258 Opts.TimePasses = TimeReport;
1259}
1260
Daniel Dunbar227b2382009-11-09 22:45:57 +00001261static void ConstructCompilerInvocation(CompilerInvocation &Opts,
Daniel Dunbar26a0cac2009-11-09 22:46:17 +00001262 const char *Argv0,
Daniel Dunbar227b2382009-11-09 22:45:57 +00001263 const DiagnosticOptions &DiagOpts,
Daniel Dunbar26a0cac2009-11-09 22:46:17 +00001264 TargetInfo &Target,
1265 LangKind LK) {
Daniel Dunbar227b2382009-11-09 22:45:57 +00001266 Opts.getDiagnosticOpts() = DiagOpts;
1267
1268 Opts.getOutputFile() = OutputFile;
Daniel Dunbar26a0cac2009-11-09 22:46:17 +00001269
1270 // Compute the feature set, which may effect the language.
1271 ComputeFeatureMap(Target, Opts.getTargetFeatures());
Daniel Dunbar36f4ec32009-11-10 16:19:45 +00001272
Daniel Dunbarfcb0c3b2009-11-10 18:47:35 +00001273 // Initialize backend options, which may also be used to key some language
1274 // options.
1275 InitializeCompileOptions(Opts.getCompileOpts(), Opts.getTargetFeatures());
1276
Daniel Dunbar26a0cac2009-11-09 22:46:17 +00001277 // Initialize language options.
1278 LangOptions LangInfo;
Daniel Dunbar36f4ec32009-11-10 16:19:45 +00001279
Daniel Dunbar26a0cac2009-11-09 22:46:17 +00001280 // FIXME: These aren't used during operations on ASTs. Split onto a separate
1281 // code path to make this obvious.
Daniel Dunbar56749082009-11-11 07:26:12 +00001282 if (LK != langkind_ast)
1283 InitializeLangOptions(Opts.getLangOpts(), LK, Target,
1284 Opts.getCompileOpts(), Opts.getTargetFeatures());
Daniel Dunbar26a0cac2009-11-09 22:46:17 +00001285
1286 // Initialize the header search options.
Daniel Dunbarf7973292009-11-11 08:13:32 +00001287 InitializeHeaderSearchOptions(Opts.getHeaderSearchOpts(),
1288 GetBuiltinIncludePath(Argv0),
1289 Verbose,
1290 Opts.getLangOpts());
Daniel Dunbar5fc7d342009-11-09 23:12:31 +00001291
1292 // Initialize the other preprocessor options.
1293 InitializePreprocessorOptions(Opts.getPreprocessorOpts());
Daniel Dunbar36f4ec32009-11-10 16:19:45 +00001294
Daniel Dunbar0498cfc2009-11-10 19:51:53 +00001295 // Finalize some code generation options.
Daniel Dunbarfcb0c3b2009-11-10 18:47:35 +00001296 FinalizeCompileOptions(Opts.getCompileOpts(), Opts.getLangOpts());
Daniel Dunbare29709f2009-11-09 20:55:08 +00001297}
1298
Reid Spencer5f016e22007-07-11 17:01:13 +00001299int main(int argc, char **argv) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001300 llvm::sys::PrintStackTraceOnErrorSignal();
Chris Lattner09e94a32009-03-04 21:41:39 +00001301 llvm::PrettyStackTraceProgram X(argc, argv);
Owen Andersond7200462009-07-16 00:14:12 +00001302 llvm::LLVMContext &Context = llvm::getGlobalContext();
Daniel Dunbard6970812009-09-02 23:20:15 +00001303
Daniel Dunbar4d861512009-09-03 04:54:12 +00001304 // Initialize targets first, so that --version shows registered targets.
Chris Lattner2fe11942009-06-17 17:25:50 +00001305 llvm::InitializeAllTargets();
1306 llvm::InitializeAllAsmPrinters();
Daniel Dunbard6970812009-09-02 23:20:15 +00001307
1308 llvm::cl::ParseCommandLineOptions(argc, argv,
1309 "LLVM 'Clang' Compiler: http://clang.llvm.org\n");
Mike Stump1eb44332009-09-09 15:08:12 +00001310
Chris Lattner47099742009-02-18 01:51:21 +00001311 if (TimeReport)
1312 ClangFrontendTimer = new llvm::Timer("Clang front-end time");
Mike Stump1eb44332009-09-09 15:08:12 +00001313
Daniel Dunbar08e6dc62009-05-28 16:37:33 +00001314 if (Verbose)
Mike Stump3cbf5a02009-09-15 21:49:22 +00001315 llvm::errs() << "clang-cc version " CLANG_VERSION_STRING
1316 << " based upon " << PACKAGE_STRING
Daniel Dunbar2e30e592009-09-04 17:43:10 +00001317 << " hosted on " << llvm::sys::getHostTriple() << "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00001318
Reid Spencer5f016e22007-07-11 17:01:13 +00001319 // If no input was specified, read from stdin.
1320 if (InputFilenames.empty())
1321 InputFilenames.push_back("-");
Douglas Gregor68a0d782009-05-02 00:03:46 +00001322
Daniel Dunbar227b2382009-11-09 22:45:57 +00001323 // Construct the diagnostic options first, which cannot fail, so that we can
1324 // build a diagnostic client to use for any errors during option handling.
1325 DiagnosticOptions DiagOpts;
1326 ConstructDiagnosticOptions(DiagOpts);
Daniel Dunbareace8742009-11-04 06:24:30 +00001327
Ted Kremenek31e703b2007-12-11 23:28:38 +00001328 // Create the diagnostic client for reporting errors or for
1329 // implementing -verify.
Chris Lattner409d4e72009-04-17 20:40:01 +00001330 llvm::OwningPtr<DiagnosticClient> DiagClient;
1331 if (VerifyDiagnostics) {
1332 // When checking diagnostics, just buffer them up.
1333 DiagClient.reset(new TextDiagnosticBuffer());
1334 if (InputFilenames.size() != 1) {
Daniel Dunbar227b2382009-11-09 22:45:57 +00001335 fprintf(stderr, "-verify only works on single input files.\n");
Chris Lattner409d4e72009-04-17 20:40:01 +00001336 return 1;
1337 }
Ted Kremenekb4398aa2008-08-07 17:49:57 +00001338 } else {
Daniel Dunbar227b2382009-11-09 22:45:57 +00001339 DiagClient.reset(new TextDiagnosticPrinter(llvm::errs(), DiagOpts));
Reid Spencer5f016e22007-07-11 17:01:13 +00001340 }
Mike Stump1eb44332009-09-09 15:08:12 +00001341
Daniel Dunbarad451cc2009-11-05 02:11:37 +00001342 if (!DumpBuildInformation.empty())
Daniel Dunbar227b2382009-11-09 22:45:57 +00001343 SetUpBuildDumpLog(DiagOpts, argc, argv, DiagClient);
Ted Kremenekb4398aa2008-08-07 17:49:57 +00001344
Reid Spencer5f016e22007-07-11 17:01:13 +00001345 // Configure our handling of diagnostics.
Ted Kremenekb4398aa2008-08-07 17:49:57 +00001346 Diagnostic Diags(DiagClient.get());
Eli Friedman0eeb86e2009-05-19 01:17:04 +00001347 if (ProcessWarningOptions(Diags, OptWarnings, OptPedantic, OptPedanticErrors,
1348 OptNoWarnings))
Sebastian Redl63a9e0f2009-03-06 17:41:35 +00001349 return 1;
Ted Kremenek31e703b2007-12-11 23:28:38 +00001350
Daniel Dunbar70121eb2009-08-10 03:40:28 +00001351 // Set an error handler, so that any LLVM backend diagnostics go through our
1352 // error handler.
1353 llvm::llvm_install_error_handler(LLVMErrorHandler,
1354 static_cast<void*>(&Diags));
1355
Daniel Dunbar7c15e712009-10-30 18:12:31 +00001356 // Initialize base triple. If a -triple option has been specified, use
1357 // that triple. Otherwise, default to the host triple.
1358 llvm::Triple Triple(TargetTriple);
1359 if (Triple.getTriple().empty())
1360 Triple = llvm::Triple(llvm::sys::getHostTriple());
1361
Chris Lattner11215192008-03-14 06:12:05 +00001362 // Get information about the target being compiled for.
Daniel Dunbarbea5a842009-10-29 01:53:18 +00001363 llvm::OwningPtr<TargetInfo>
Chris Lattner2f60af72009-09-12 22:45:58 +00001364 Target(TargetInfo::CreateTargetInfo(Triple.getTriple()));
Mike Stump1eb44332009-09-09 15:08:12 +00001365
Chris Lattner11215192008-03-14 06:12:05 +00001366 if (Target == 0) {
Daniel Dunbar0f9fed72009-11-10 23:55:23 +00001367 Diags.Report(diag::err_fe_unknown_triple) << Triple.getTriple().c_str();
Sebastian Redlc5613db2009-03-07 12:09:25 +00001368 return 1;
Chris Lattner11215192008-03-14 06:12:05 +00001369 }
Mike Stump1eb44332009-09-09 15:08:12 +00001370
Daniel Dunbar73b79592009-09-14 00:02:12 +00001371 // Set the target ABI if specified.
1372 if (!TargetABI.empty()) {
1373 if (!Target->setABI(TargetABI)) {
Daniel Dunbar0f9fed72009-11-10 23:55:23 +00001374 Diags.Report(diag::err_fe_unknown_target_abi) << TargetABI;
Daniel Dunbar73b79592009-09-14 00:02:12 +00001375 return 1;
1376 }
1377 }
1378
Daniel Dunbard4270232009-01-20 23:17:32 +00001379 if (!InheritanceViewCls.empty()) // C++ visualization?
Ted Kremenek7cae2f62008-10-23 23:36:29 +00001380 ProgAction = InheritanceView;
Mike Stump1eb44332009-09-09 15:08:12 +00001381
Daniel Dunbar227b2382009-11-09 22:45:57 +00001382 // Infer the input language.
1383 //
1384 // FIXME: We should move .ast inputs to taking a separate path, they are
1385 // really quite different.
1386 LangKind LK = GetLanguage();
1387
1388 // Now that we have initialized the diagnostics engine and the target, finish
1389 // setting up the compiler invocation.
1390 CompilerInvocation CompOpts;
Daniel Dunbar26a0cac2009-11-09 22:46:17 +00001391 ConstructCompilerInvocation(CompOpts, argv[0], DiagOpts, *Target, LK);
Daniel Dunbar227b2382009-11-09 22:45:57 +00001392
Daniel Dunbar4cc1a252009-11-05 01:53:23 +00001393 // Create the source manager.
1394 SourceManager SourceMgr;
Mike Stump1eb44332009-09-09 15:08:12 +00001395
Chris Lattner2c78b872009-04-14 23:22:57 +00001396 // Create a file manager object to provide access to and cache the filesystem.
1397 FileManager FileMgr;
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001398
Reid Spencer5f016e22007-07-11 17:01:13 +00001399 for (unsigned i = 0, e = InputFilenames.size(); i != e; ++i) {
Ted Kremenek31e703b2007-12-11 23:28:38 +00001400 const std::string &InFile = InputFilenames[i];
Mike Stump1eb44332009-09-09 15:08:12 +00001401
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +00001402 // AST inputs are handled specially.
1403 if (LK == langkind_ast) {
Daniel Dunbar26a0cac2009-11-09 22:46:17 +00001404 ProcessASTInputFile(CompOpts, InFile, ProgAction, Diags, FileMgr,
1405 Context);
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +00001406 continue;
1407 }
1408
Daniel Dunbar4cc1a252009-11-05 01:53:23 +00001409 // Reset the ID tables if we are reusing the SourceManager.
1410 if (i)
1411 SourceMgr.clearIDTables();
Mike Stump1eb44332009-09-09 15:08:12 +00001412
Chris Lattnerf63aea32009-03-04 21:40:56 +00001413 // Process the -I options and set them in the HeaderInfo.
1414 HeaderSearch HeaderInfo(FileMgr);
Mike Stump1eb44332009-09-09 15:08:12 +00001415
Daniel Dunbar26a0cac2009-11-09 22:46:17 +00001416 // Apply all the options to the header search object.
1417 ApplyHeaderSearchOptions(CompOpts.getHeaderSearchOpts(), HeaderInfo,
1418 CompOpts.getLangOpts(), Triple);
Mike Stump1eb44332009-09-09 15:08:12 +00001419
Chris Lattnerf63aea32009-03-04 21:40:56 +00001420 // Set up the preprocessor with these options.
Daniel Dunbar5fc7d342009-11-09 23:12:31 +00001421 llvm::OwningPtr<Preprocessor>
1422 PP(CreatePreprocessor(Diags, CompOpts.getLangOpts(),
1423 CompOpts.getPreprocessorOpts(), *Target, SourceMgr,
1424 HeaderInfo));
Ted Kremenekb4398aa2008-08-07 17:49:57 +00001425
Daniel Dunbar8cb65622009-10-29 21:05:18 +00001426 // Handle generating dependencies, if requested.
Eli Friedmanb5c8f8b2009-05-19 03:35:57 +00001427 if (!DependencyFile.empty()) {
Eli Friedmanb5c8f8b2009-05-19 03:35:57 +00001428 if (DependencyTargets.empty()) {
Daniel Dunbar0f9fed72009-11-10 23:55:23 +00001429 Diags.Report(diag::err_fe_dependency_file_requires_MT);
Eli Friedmanb5c8f8b2009-05-19 03:35:57 +00001430 continue;
1431 }
1432 std::string ErrStr;
Daniel Dunbar8cb65622009-10-29 21:05:18 +00001433 llvm::raw_ostream *DependencyOS =
Dan Gohmanb044c472009-08-25 15:36:09 +00001434 new llvm::raw_fd_ostream(DependencyFile.c_str(), ErrStr);
Eli Friedmanb5c8f8b2009-05-19 03:35:57 +00001435 if (!ErrStr.empty()) {
Daniel Dunbar0f9fed72009-11-10 23:55:23 +00001436 Diags.Report(diag::err_fe_error_opening) << DependencyFile << ErrStr;
Eli Friedmanb5c8f8b2009-05-19 03:35:57 +00001437 continue;
1438 }
1439
1440 AttachDependencyFileGen(PP.get(), DependencyOS, DependencyTargets,
1441 DependenciesIncludeSystemHeaders,
1442 PhonyDependencyTarget);
1443 }
1444
Daniel Dunbare0a95812009-11-10 22:09:38 +00001445 if (CompOpts.getPreprocessorOpts().getImplicitPCHInclude().empty()) {
Chris Lattner1b63e4f2009-06-14 01:54:56 +00001446 if (InitializeSourceManager(*PP.get(), InFile))
1447 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00001448
Chris Lattner1b63e4f2009-06-14 01:54:56 +00001449 // Initialize builtin info.
1450 PP->getBuiltinInfo().InitializeBuiltins(PP->getIdentifierTable(),
Chris Lattner1b63e4f2009-06-14 01:54:56 +00001451 PP->getLangOptions().NoBuiltin);
1452 }
Douglas Gregor14f79002009-04-10 03:52:48 +00001453
Chris Lattnerf63aea32009-03-04 21:40:56 +00001454 // Process the source file.
Daniel Dunbar26a0cac2009-11-09 22:46:17 +00001455 Diags.getClient()->BeginSourceFile(CompOpts.getLangOpts());
1456 ProcessInputFile(CompOpts, *PP, InFile, ProgAction, Context);
Daniel Dunbar227b2382009-11-09 22:45:57 +00001457 Diags.getClient()->EndSourceFile();
Mike Stump1eb44332009-09-09 15:08:12 +00001458
Chris Lattner40469652009-04-17 20:16:08 +00001459 HeaderInfo.ClearFileInfo();
Reid Spencer5f016e22007-07-11 17:01:13 +00001460 }
Chris Lattner11215192008-03-14 06:12:05 +00001461
Daniel Dunbar9253e492009-11-10 00:46:12 +00001462 if (CompOpts.getDiagnosticOpts().ShowCarets)
Mike Stumpfc0fed32009-04-28 01:19:10 +00001463 if (unsigned NumDiagnostics = Diags.getNumDiagnostics())
1464 fprintf(stderr, "%d diagnostic%s generated.\n", NumDiagnostics,
1465 (NumDiagnostics == 1 ? "" : "s"));
Mike Stump1eb44332009-09-09 15:08:12 +00001466
Reid Spencer5f016e22007-07-11 17:01:13 +00001467 if (Stats) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001468 FileMgr.PrintStats();
1469 fprintf(stderr, "\n");
1470 }
Chris Lattner75a97cb2009-04-17 21:05:01 +00001471
1472 delete ClangFrontendTimer;
1473 delete BuildLogFile;
Mike Stump1eb44332009-09-09 15:08:12 +00001474
Daniel Dunbar276373d2008-10-27 22:10:13 +00001475 // If verifying diagnostics and we reached here, all is well.
1476 if (VerifyDiagnostics)
1477 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001478
Daniel Dunbar524b86f2008-10-28 00:38:08 +00001479 // Managed static deconstruction. Useful for making things like
1480 // -time-passes usable.
1481 llvm::llvm_shutdown();
1482
Daniel Dunbar8cb65622009-10-29 21:05:18 +00001483 return (Diags.getNumErrors() != 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00001484}