blob: 77d5ef7082adaf33ade55019a2f5c775e713f270 [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//===----------------------------------------------------------------------===//
17//
18// TODO: Options to support:
19//
20// -ffatal-errors
21// -ftabstop=width
22//
23//===----------------------------------------------------------------------===//
24
25#include "clang.h"
Chris Lattner97e8b6f2007-10-07 06:04:32 +000026#include "ASTConsumers.h"
Daniel Dunbar70f92432008-10-23 05:50:47 +000027#include "clang/Driver/CompileOptions.h"
Ted Kremenekad99dbf2008-11-03 22:31:48 +000028#include "clang/Driver/PathDiagnosticClients.h"
Nico Weber0fca0222008-08-22 09:25:22 +000029#include "clang/Driver/InitHeaderSearch.h"
Nico Weberfd54ebc2008-08-05 23:33:20 +000030#include "clang/Driver/TextDiagnosticBuffer.h"
31#include "clang/Driver/TextDiagnosticPrinter.h"
Chris Lattner500d3292009-01-29 05:15:15 +000032#include "clang/Driver/DriverDiagnostic.h"
Ted Kremenek88f5cde2008-03-27 06:17:42 +000033#include "clang/Analysis/PathDiagnostic.h"
Daniel Dunbare91593e2008-08-11 04:54:23 +000034#include "clang/AST/Decl.h"
Ted Kremenek77cda502007-12-18 21:34:28 +000035#include "clang/AST/TranslationUnit.h"
Chris Lattner8ee3c032008-02-06 02:01:47 +000036#include "clang/CodeGen/ModuleBuilder.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"
Reid Spencer5f016e22007-07-11 17:01:13 +000040#include "clang/Parse/Parser.h"
41#include "clang/Lex/HeaderSearch.h"
42#include "clang/Basic/FileManager.h"
43#include "clang/Basic/SourceManager.h"
44#include "clang/Basic/TargetInfo.h"
Chris Lattnerba0f25f2008-09-30 20:16:56 +000045#include "llvm/ADT/OwningPtr.h"
Chris Lattner8f3dab82007-12-15 23:20:07 +000046#include "llvm/ADT/SmallPtrSet.h"
Chris Lattnerba0f25f2008-09-30 20:16:56 +000047#include "llvm/ADT/StringExtras.h"
48#include "llvm/Config/config.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000049#include "llvm/Support/CommandLine.h"
Daniel Dunbar524b86f2008-10-28 00:38:08 +000050#include "llvm/Support/ManagedStatic.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000051#include "llvm/Support/MemoryBuffer.h"
Zhongxing Xu20922362008-11-26 05:23:17 +000052#include "llvm/Support/PluginLoader.h"
Daniel Dunbare553a722008-10-02 01:21:33 +000053#include "llvm/System/Host.h"
Chris Lattnerdcaa0962008-03-03 03:16:03 +000054#include "llvm/System/Path.h"
Chris Lattnerba0f25f2008-09-30 20:16:56 +000055#include "llvm/System/Signals.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000056using namespace clang;
57
58//===----------------------------------------------------------------------===//
59// Global options.
60//===----------------------------------------------------------------------===//
61
Daniel Dunbard3db4012008-10-16 16:54:18 +000062static bool HadErrors = false;
Daniel Dunbarb0adbba2008-10-04 23:42:49 +000063
Reid Spencer5f016e22007-07-11 17:01:13 +000064static llvm::cl::opt<bool>
65Verbose("v", llvm::cl::desc("Enable verbose output"));
66static llvm::cl::opt<bool>
Nate Begemanaabbb122007-12-30 01:38:50 +000067Stats("print-stats",
68 llvm::cl::desc("Print performance metrics and statistics"));
Daniel Dunbard3db4012008-10-16 16:54:18 +000069static llvm::cl::opt<bool>
70DisableFree("disable-free",
71 llvm::cl::desc("Disable freeing of memory on exit"),
72 llvm::cl::init(false));
Reid Spencer5f016e22007-07-11 17:01:13 +000073
74enum ProgActions {
Steve Naroffb29b4272008-04-14 22:03:09 +000075 RewriteObjC, // ObjC->C Rewriter.
Steve Naroff13188952008-09-18 14:10:13 +000076 RewriteBlocks, // ObjC->C Rewriter for Blocks.
Chris Lattnerb57e3d42008-05-08 06:52:13 +000077 RewriteMacros, // Expand macros but not #includes.
Chris Lattnerb13c5ee2008-10-12 05:29:20 +000078 RewriteTest, // Rewriter playground
Ted Kremenek13e479b2008-03-19 07:53:42 +000079 HTMLTest, // HTML displayer testing stuff.
Daniel Dunbard69bacc2008-10-21 23:49:24 +000080 EmitAssembly, // Emit a .s file.
Reid Spencer5f016e22007-07-11 17:01:13 +000081 EmitLLVM, // Emit a .ll file.
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +000082 EmitBC, // Emit a .bc file.
Ted Kremeneka1fa3a12007-12-13 00:37:31 +000083 SerializeAST, // Emit a .ast file.
Ted Kremenek6a340832008-03-18 21:19:49 +000084 EmitHTML, // Translate input source into HTML.
Chris Lattner3b427b32007-10-11 00:18:28 +000085 ASTPrint, // Parse ASTs and print them.
86 ASTDump, // Parse ASTs and dump them.
87 ASTView, // Parse ASTs and view them in Graphviz.
Zhongxing Xu2d75d6f2009-01-13 01:29:24 +000088 PrintDeclContext, // Print DeclContext and their Decls.
Ted Kremenekbfa82c42007-10-16 23:37:27 +000089 TestSerialization, // Run experimental serialization code.
Reid Spencer5f016e22007-07-11 17:01:13 +000090 ParsePrintCallbacks, // Parse and print each callback.
91 ParseSyntaxOnly, // Parse and perform semantic analysis.
92 ParseNoop, // Parse with noop callbacks.
93 RunPreprocessorOnly, // Just lex, no output.
94 PrintPreprocessedInput, // -E mode.
Chris Lattnerc106c102008-10-12 05:03:36 +000095 DumpTokens, // Dump out preprocessed tokens.
96 DumpRawTokens, // Dump out raw tokens.
Ted Kremenek85888962008-10-21 00:54:44 +000097 RunAnalysis, // Run one or more source code analyses.
Ted Kremenek7cae2f62008-10-23 23:36:29 +000098 GeneratePCH, // Generate precompiled header.
99 InheritanceView // View C++ inheritance for a specified class.
Reid Spencer5f016e22007-07-11 17:01:13 +0000100};
101
102static llvm::cl::opt<ProgActions>
103ProgAction(llvm::cl::desc("Choose output type:"), llvm::cl::ZeroOrMore,
104 llvm::cl::init(ParseSyntaxOnly),
105 llvm::cl::values(
106 clEnumValN(RunPreprocessorOnly, "Eonly",
107 "Just run preprocessor, no output (for timings)"),
108 clEnumValN(PrintPreprocessedInput, "E",
109 "Run preprocessor, emit preprocessed file"),
Chris Lattnerc106c102008-10-12 05:03:36 +0000110 clEnumValN(DumpRawTokens, "dump-raw-tokens",
111 "Lex file in raw mode and dump raw tokens"),
Daniel Dunbard4270232009-01-20 23:17:32 +0000112 clEnumValN(RunAnalysis, "analyze",
113 "Run static analysis engine"),
Chris Lattnerc106c102008-10-12 05:03:36 +0000114 clEnumValN(DumpTokens, "dump-tokens",
Reid Spencer5f016e22007-07-11 17:01:13 +0000115 "Run preprocessor, dump internal rep of tokens"),
116 clEnumValN(ParseNoop, "parse-noop",
117 "Run parser with noop callbacks (for timings)"),
118 clEnumValN(ParseSyntaxOnly, "fsyntax-only",
119 "Run parser and perform semantic analysis"),
120 clEnumValN(ParsePrintCallbacks, "parse-print-callbacks",
121 "Run parser and print each callback invoked"),
Ted Kremenek6a340832008-03-18 21:19:49 +0000122 clEnumValN(EmitHTML, "emit-html",
123 "Output input source as HTML"),
Chris Lattner3b427b32007-10-11 00:18:28 +0000124 clEnumValN(ASTPrint, "ast-print",
125 "Build ASTs and then pretty-print them"),
126 clEnumValN(ASTDump, "ast-dump",
127 "Build ASTs and then debug dump them"),
Chris Lattnerea254db2007-10-11 00:37:43 +0000128 clEnumValN(ASTView, "ast-view",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000129 "Build ASTs and view them with GraphViz"),
Zhongxing Xu2d75d6f2009-01-13 01:29:24 +0000130 clEnumValN(PrintDeclContext, "print-decl-contexts",
131 "Print DeclContexts and their Decls."),
Ted Kremenekbfa82c42007-10-16 23:37:27 +0000132 clEnumValN(TestSerialization, "test-pickling",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000133 "Run prototype serialization code"),
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000134 clEnumValN(EmitAssembly, "S",
135 "Emit native assembly code"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000136 clEnumValN(EmitLLVM, "emit-llvm",
Ted Kremenek27b07c52007-09-06 21:26:58 +0000137 "Build ASTs then convert to LLVM, emit .ll file"),
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +0000138 clEnumValN(EmitBC, "emit-llvm-bc",
139 "Build ASTs then convert to LLVM, emit .bc file"),
Ted Kremenekccc76472007-12-19 19:47:59 +0000140 clEnumValN(SerializeAST, "serialize",
Ted Kremeneka1fa3a12007-12-13 00:37:31 +0000141 "Build ASTs and emit .ast file"),
Chris Lattnerb13c5ee2008-10-12 05:29:20 +0000142 clEnumValN(RewriteTest, "rewrite-test",
143 "Rewriter playground"),
Steve Naroffb29b4272008-04-14 22:03:09 +0000144 clEnumValN(RewriteObjC, "rewrite-objc",
Chris Lattnerb57e3d42008-05-08 06:52:13 +0000145 "Rewrite ObjC into C (code rewriter example)"),
146 clEnumValN(RewriteMacros, "rewrite-macros",
147 "Expand macros without full preprocessing"),
Steve Naroff13188952008-09-18 14:10:13 +0000148 clEnumValN(RewriteBlocks, "rewrite-blocks",
149 "Rewrite Blocks to C"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000150 clEnumValEnd));
151
Ted Kremenekccc76472007-12-19 19:47:59 +0000152
153static llvm::cl::opt<std::string>
154OutputFile("o",
Ted Kremenek50b56412007-12-19 19:50:41 +0000155 llvm::cl::value_desc("path"),
Ted Kremenekccc76472007-12-19 19:47:59 +0000156 llvm::cl::desc("Specify output file (for --serialize, this is a directory)"));
Ted Kremenek55af98c2008-04-14 18:40:58 +0000157
158//===----------------------------------------------------------------------===//
Sanjiv Guptae8b9f5b2008-05-08 08:54:20 +0000159// Code Generator Options
160//===----------------------------------------------------------------------===//
161static llvm::cl::opt<bool>
162GenerateDebugInfo("g",
163 llvm::cl::desc("Generate source level debug information"));
164
Ted Kremenekc2e72992008-12-02 19:57:31 +0000165
166//===----------------------------------------------------------------------===//
167// PTH.
168//===----------------------------------------------------------------------===//
169
170static llvm::cl::opt<std::string>
171TokenCache("token-cache", llvm::cl::value_desc("path"),
172 llvm::cl::desc("Use specified token cache file"));
173
Sanjiv Guptae8b9f5b2008-05-08 08:54:20 +0000174//===----------------------------------------------------------------------===//
Ted Kremenek55af98c2008-04-14 18:40:58 +0000175// Diagnostic Options
176//===----------------------------------------------------------------------===//
177
Ted Kremenek41193e42007-09-26 19:42:19 +0000178static llvm::cl::opt<bool>
179VerifyDiagnostics("verify",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000180 llvm::cl::desc("Verify emitted diagnostics and warnings"));
Ted Kremenek41193e42007-09-26 19:42:19 +0000181
Ted Kremenek88f5cde2008-03-27 06:17:42 +0000182static llvm::cl::opt<std::string>
183HTMLDiag("html-diags",
184 llvm::cl::desc("Generate HTML to report diagnostics"),
185 llvm::cl::value_desc("HTML directory"));
186
Nico Weberfd54ebc2008-08-05 23:33:20 +0000187static llvm::cl::opt<bool>
188NoShowColumn("fno-show-column",
189 llvm::cl::desc("Do not include column number on diagnostics"));
190
191static llvm::cl::opt<bool>
192NoCaretDiagnostics("fno-caret-diagnostics",
193 llvm::cl::desc("Do not include source line and caret with"
194 " diagnostics"));
195
196
Reid Spencer5f016e22007-07-11 17:01:13 +0000197//===----------------------------------------------------------------------===//
Ted Kremenek7cae2f62008-10-23 23:36:29 +0000198// C++ Visualization.
199//===----------------------------------------------------------------------===//
200
201static llvm::cl::opt<std::string>
202InheritanceViewCls("cxx-inheritance-view",
203 llvm::cl::value_desc("class name"),
Daniel Dunbard77b2512009-01-14 18:56:36 +0000204 llvm::cl::desc("View C++ inheritance for a specified class"));
Ted Kremenek7cae2f62008-10-23 23:36:29 +0000205
206//===----------------------------------------------------------------------===//
207// Analyzer Options.
Ted Kremenek55af98c2008-04-14 18:40:58 +0000208//===----------------------------------------------------------------------===//
209
210static llvm::cl::opt<bool>
Ted Kremenekf8ce6992008-08-27 22:31:43 +0000211VisualizeEGDot("analyzer-viz-egraph-graphviz",
212 llvm::cl::desc("Display exploded graph using GraphViz"));
Ted Kremenek55af98c2008-04-14 18:40:58 +0000213
214static llvm::cl::opt<bool>
Ted Kremenekf8ce6992008-08-27 22:31:43 +0000215VisualizeEGUbi("analyzer-viz-egraph-ubigraph",
216 llvm::cl::desc("Display exploded graph using Ubigraph"));
217
218static llvm::cl::opt<bool>
219AnalyzeAll("analyzer-opt-analyze-headers",
Ted Kremenek55af98c2008-04-14 18:40:58 +0000220 llvm::cl::desc("Force the static analyzer to analyze "
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000221 "functions defined in header files"));
Ted Kremenek55af98c2008-04-14 18:40:58 +0000222
Ted Kremenek491918e2009-01-23 20:52:26 +0000223static llvm::cl::opt<bool>
224AnalyzerDisplayProgress("analyzer-display-progress",
225 llvm::cl::desc("Emit verbose output about the analyzer's progress."));
226
Ted Kremenekf4381fd2008-07-02 00:03:09 +0000227static llvm::cl::list<Analyses>
Ted Kremenek95c7b002008-10-24 01:04:59 +0000228AnalysisList(llvm::cl::desc("SCA Checks/Analyses:"),
Ted Kremenekf4381fd2008-07-02 00:03:09 +0000229llvm::cl::values(
Ted Kremenekf7f3c202008-07-15 00:46:02 +0000230#define ANALYSIS(NAME, CMDFLAG, DESC, SCOPE)\
Ted Kremenekfb9a48c2008-07-14 23:41:13 +0000231clEnumValN(NAME, CMDFLAG, DESC),
232#include "Analyses.def"
233clEnumValEnd));
Ted Kremenekf4381fd2008-07-02 00:03:09 +0000234
Ted Kremenek95c7b002008-10-24 01:04:59 +0000235static llvm::cl::opt<AnalysisStores>
236AnalysisStoreOpt(llvm::cl::desc("SCA Low-Level Options (Store):"),
237 llvm::cl::init(BasicStoreModel),
238 llvm::cl::values(
239#define ANALYSIS_STORE(NAME, CMDFLAG, DESC)\
240clEnumValN(NAME##Model, "analyzer-store-" CMDFLAG, DESC),
241#include "Analyses.def"
242clEnumValEnd));
243
Ted Kremenek4fc82c82008-11-03 23:18:07 +0000244static llvm::cl::opt<AnalysisDiagClients>
245AnalysisDiagOpt(llvm::cl::desc("SCA Output Options:"),
246 llvm::cl::init(PD_HTML),
247 llvm::cl::values(
Ted Kremenekc472d792009-01-23 20:06:20 +0000248#define ANALYSIS_DIAGNOSTICS(NAME, CMDFLAG, DESC, CREATFN, AUTOCREATE)\
Ted Kremenek4fc82c82008-11-03 23:18:07 +0000249clEnumValN(PD_##NAME, "analyzer-output-" CMDFLAG, DESC),
250#include "Analyses.def"
251clEnumValEnd));
252
Ted Kremenek55af98c2008-04-14 18:40:58 +0000253//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +0000254// Language Options
255//===----------------------------------------------------------------------===//
256
257enum LangKind {
258 langkind_unspecified,
259 langkind_c,
260 langkind_c_cpp,
Chris Lattnera778d7d2008-10-22 17:29:21 +0000261 langkind_asm_cpp,
Ted Kremenek85888962008-10-21 00:54:44 +0000262 langkind_c_pch,
Reid Spencer5f016e22007-07-11 17:01:13 +0000263 langkind_cxx,
264 langkind_cxx_cpp,
265 langkind_objc,
266 langkind_objc_cpp,
Ted Kremenek85888962008-10-21 00:54:44 +0000267 langkind_objc_pch,
Reid Spencer5f016e22007-07-11 17:01:13 +0000268 langkind_objcxx,
Ted Kremenekf8901912009-01-09 00:38:08 +0000269 langkind_objcxx_cpp,
270 langkind_objcxx_pch
Reid Spencer5f016e22007-07-11 17:01:13 +0000271};
272
273/* TODO: GCC also accepts:
274 c-header c++-header objective-c-header objective-c++-header
Chris Lattnera778d7d2008-10-22 17:29:21 +0000275 assembler
Reid Spencer5f016e22007-07-11 17:01:13 +0000276 ada, f77*, ratfor (!), f95, java, treelang
277 */
278static llvm::cl::opt<LangKind>
279BaseLang("x", llvm::cl::desc("Base language to compile"),
280 llvm::cl::init(langkind_unspecified),
281 llvm::cl::values(clEnumValN(langkind_c, "c", "C"),
282 clEnumValN(langkind_cxx, "c++", "C++"),
283 clEnumValN(langkind_objc, "objective-c", "Objective C"),
284 clEnumValN(langkind_objcxx,"objective-c++","Objective C++"),
285 clEnumValN(langkind_c_cpp, "c-cpp-output",
286 "Preprocessed C"),
Chris Lattnera778d7d2008-10-22 17:29:21 +0000287 clEnumValN(langkind_asm_cpp, "assembler-with-cpp",
288 "Preprocessed asm"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000289 clEnumValN(langkind_cxx_cpp, "c++-cpp-output",
Ted Kremenek85888962008-10-21 00:54:44 +0000290 "Preprocessed C++"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000291 clEnumValN(langkind_objc_cpp, "objective-c-cpp-output",
292 "Preprocessed Objective C"),
293 clEnumValN(langkind_objcxx_cpp,"objective-c++-cpp-output",
294 "Preprocessed Objective C++"),
Ted Kremenek85888962008-10-21 00:54:44 +0000295 clEnumValN(langkind_c_pch,"c-header",
296 "Precompiled C header"),
297 clEnumValN(langkind_objc_pch, "objective-c-header",
Ted Kremenekf8901912009-01-09 00:38:08 +0000298 "Precompiled Objective-C header"),
299 clEnumValN(langkind_objcxx_pch, "objective-c++-header",
300 "Precompiled Objective-C++ header"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000301 clEnumValEnd));
302
303static llvm::cl::opt<bool>
304LangObjC("ObjC", llvm::cl::desc("Set base language to Objective-C"),
305 llvm::cl::Hidden);
306static llvm::cl::opt<bool>
307LangObjCXX("ObjC++", llvm::cl::desc("Set base language to Objective-C++"),
308 llvm::cl::Hidden);
309
Ted Kremenek8904f152007-12-05 23:49:08 +0000310/// InitializeBaseLanguage - Handle the -x foo options.
311static void InitializeBaseLanguage() {
312 if (LangObjC)
313 BaseLang = langkind_objc;
314 else if (LangObjCXX)
315 BaseLang = langkind_objcxx;
316}
317
318static LangKind GetLanguage(const std::string &Filename) {
319 if (BaseLang != langkind_unspecified)
320 return BaseLang;
321
322 std::string::size_type DotPos = Filename.rfind('.');
323
324 if (DotPos == std::string::npos) {
325 BaseLang = langkind_c; // Default to C if no extension.
Chris Lattner9b2f6c42008-01-04 19:12:28 +0000326 return langkind_c;
Reid Spencer5f016e22007-07-11 17:01:13 +0000327 }
328
Ted Kremenek8904f152007-12-05 23:49:08 +0000329 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
330 // C header: .h
331 // C++ header: .hh or .H;
332 // assembler no preprocessing: .s
333 // assembler: .S
334 if (Ext == "c")
335 return langkind_c;
Chris Lattner1b450b02008-10-28 20:33:42 +0000336 else if (Ext == "S")
Chris Lattnera778d7d2008-10-22 17:29:21 +0000337 return langkind_asm_cpp;
Ted Kremenek8904f152007-12-05 23:49:08 +0000338 else if (Ext == "i")
339 return langkind_c_cpp;
340 else if (Ext == "ii")
341 return langkind_cxx_cpp;
342 else if (Ext == "m")
343 return langkind_objc;
344 else if (Ext == "mi")
345 return langkind_objc_cpp;
346 else if (Ext == "mm" || Ext == "M")
347 return langkind_objcxx;
348 else if (Ext == "mii")
349 return langkind_objcxx_cpp;
350 else if (Ext == "C" || Ext == "cc" || Ext == "cpp" || Ext == "CPP" ||
351 Ext == "c++" || Ext == "cp" || Ext == "cxx")
352 return langkind_cxx;
353 else
354 return langkind_c;
355}
356
357
Ted Kremenek85888962008-10-21 00:54:44 +0000358static void InitializeCOptions(LangOptions &Options) {
359 // Do nothing.
360}
361
362static void InitializeObjCOptions(LangOptions &Options) {
363 Options.ObjC1 = Options.ObjC2 = 1;
364}
365
366
367static bool InitializeLangOptions(LangOptions &Options, LangKind LK){
Reid Spencer5f016e22007-07-11 17:01:13 +0000368 // FIXME: implement -fpreprocessed mode.
369 bool NoPreprocess = false;
Ted Kremenek85888962008-10-21 00:54:44 +0000370 bool PCH = false;
Ted Kremenekf8901912009-01-09 00:38:08 +0000371
372 // Test for 'PCH'.
373 switch (LK) {
374 default:
375 break;
376 case langkind_c_pch:
377 LK = langkind_c;
378 PCH = true;
379 break;
380 case langkind_objc_pch:
381 LK = langkind_objc;
382 PCH = true;
383 break;
384 case langkind_objcxx_pch:
385 LK = langkind_objcxx;
386 PCH = true;
387 break;
388 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000389
Ted Kremenek8904f152007-12-05 23:49:08 +0000390 switch (LK) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000391 default: assert(0 && "Unknown language kind!");
Chris Lattnera778d7d2008-10-22 17:29:21 +0000392 case langkind_asm_cpp:
Daniel Dunbarc1571452008-12-01 18:55:22 +0000393 Options.AsmPreprocessor = 1;
Chris Lattnera778d7d2008-10-22 17:29:21 +0000394 // FALLTHROUGH
Reid Spencer5f016e22007-07-11 17:01:13 +0000395 case langkind_c_cpp:
396 NoPreprocess = true;
397 // FALLTHROUGH
398 case langkind_c:
Ted Kremenek85888962008-10-21 00:54:44 +0000399 InitializeCOptions(Options);
Reid Spencer5f016e22007-07-11 17:01:13 +0000400 break;
401 case langkind_cxx_cpp:
402 NoPreprocess = true;
403 // FALLTHROUGH
404 case langkind_cxx:
405 Options.CPlusPlus = 1;
406 break;
407 case langkind_objc_cpp:
408 NoPreprocess = true;
409 // FALLTHROUGH
410 case langkind_objc:
Ted Kremenek85888962008-10-21 00:54:44 +0000411 InitializeObjCOptions(Options);
Reid Spencer5f016e22007-07-11 17:01:13 +0000412 break;
413 case langkind_objcxx_cpp:
414 NoPreprocess = true;
415 // FALLTHROUGH
416 case langkind_objcxx:
417 Options.ObjC1 = Options.ObjC2 = 1;
418 Options.CPlusPlus = 1;
419 break;
420 }
Ted Kremenek85888962008-10-21 00:54:44 +0000421
422 return PCH;
Reid Spencer5f016e22007-07-11 17:01:13 +0000423}
424
425/// LangStds - Language standards we support.
426enum LangStds {
427 lang_unspecified,
428 lang_c89, lang_c94, lang_c99,
Ted Kremenekea644d82008-09-03 21:22:16 +0000429 lang_gnu_START,
430 lang_gnu89 = lang_gnu_START, lang_gnu99,
Chris Lattnerd4b80f12007-07-16 04:18:29 +0000431 lang_cxx98, lang_gnucxx98,
432 lang_cxx0x, lang_gnucxx0x
Reid Spencer5f016e22007-07-11 17:01:13 +0000433};
434
435static llvm::cl::opt<LangStds>
436LangStd("std", llvm::cl::desc("Language standard to compile for"),
437 llvm::cl::init(lang_unspecified),
438 llvm::cl::values(clEnumValN(lang_c89, "c89", "ISO C 1990"),
439 clEnumValN(lang_c89, "c90", "ISO C 1990"),
440 clEnumValN(lang_c89, "iso9899:1990", "ISO C 1990"),
441 clEnumValN(lang_c94, "iso9899:199409",
442 "ISO C 1990 with amendment 1"),
443 clEnumValN(lang_c99, "c99", "ISO C 1999"),
444// clEnumValN(lang_c99, "c9x", "ISO C 1999"),
445 clEnumValN(lang_c99, "iso9899:1999", "ISO C 1999"),
446// clEnumValN(lang_c99, "iso9899:199x", "ISO C 1999"),
447 clEnumValN(lang_gnu89, "gnu89",
448 "ISO C 1990 with GNU extensions (default for C)"),
449 clEnumValN(lang_gnu99, "gnu99",
450 "ISO C 1999 with GNU extensions"),
451 clEnumValN(lang_gnu99, "gnu9x",
452 "ISO C 1999 with GNU extensions"),
453 clEnumValN(lang_cxx98, "c++98",
454 "ISO C++ 1998 with amendments"),
455 clEnumValN(lang_gnucxx98, "gnu++98",
456 "ISO C++ 1998 with amendments and GNU "
457 "extensions (default for C++)"),
Chris Lattnerd4b80f12007-07-16 04:18:29 +0000458 clEnumValN(lang_cxx0x, "c++0x",
459 "Upcoming ISO C++ 200x with amendments"),
460 clEnumValN(lang_gnucxx0x, "gnu++0x",
461 "Upcoming ISO C++ 200x with amendments and GNU "
462 "extensions (default for C++)"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000463 clEnumValEnd));
464
465static llvm::cl::opt<bool>
466NoOperatorNames("fno-operator-names",
467 llvm::cl::desc("Do not treat C++ operator name keywords as "
468 "synonyms for operators"));
469
Anders Carlssonee98ac52007-10-15 02:50:23 +0000470static llvm::cl::opt<bool>
471PascalStrings("fpascal-strings",
472 llvm::cl::desc("Recognize and construct Pascal-style "
473 "string literals"));
Steve Naroffd62701b2008-02-07 03:50:06 +0000474
475static llvm::cl::opt<bool>
476MSExtensions("fms-extensions",
477 llvm::cl::desc("Accept some non-standard constructs used in "
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000478 "Microsoft header files "));
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000479
480static llvm::cl::opt<bool>
481WritableStrings("fwritable-strings",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000482 llvm::cl::desc("Store string literals as writable data"));
Anders Carlsson695dbb62007-11-30 04:21:22 +0000483
484static llvm::cl::opt<bool>
485LaxVectorConversions("flax-vector-conversions",
486 llvm::cl::desc("Allow implicit conversions between vectors"
487 " with a different number of elements or "
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000488 "different element types"));
Chris Lattnerae0ee032008-12-04 23:20:07 +0000489static llvm::cl::opt<bool>
490EnableBlocks("fblocks", llvm::cl::desc("enable the 'blocks' language feature"));
491
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000492static llvm::cl::opt<bool>
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000493ObjCNonFragileABI("fobjc-nonfragile-abi", llvm::cl::desc("enable objective-c's nonfragile abi"));
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000494
Ted Kremenek01d9dbf2008-04-29 04:37:03 +0000495
Daniel Dunbar6379a7a2008-08-11 17:36:14 +0000496// FIXME: This (and all GCC -f options) really come in -f... and
497// -fno-... forms, and additionally support automagic behavior when
498// they are not defined. For example, -fexceptions defaults to on or
499// off depending on the language. We should support this behavior in
500// some form (perhaps just add a facility for distinguishing when an
501// has its default value from when it has been set to its default
502// value).
503static llvm::cl::opt<bool>
504Exceptions("fexceptions",
505 llvm::cl::desc("Enable support for exception handling."));
506
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000507static llvm::cl::opt<bool>
508GNURuntime("fgnu-runtime",
Ted Kremenek85888962008-10-21 00:54:44 +0000509 llvm::cl::desc("Generate output compatible with the standard GNU "
510 "Objective-C runtime."));
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000511
512static llvm::cl::opt<bool>
513NeXTRuntime("fnext-runtime",
Ted Kremenek85888962008-10-21 00:54:44 +0000514 llvm::cl::desc("Generate output compatible with the NeXT "
515 "runtime."));
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000516
Ted Kremenekea644d82008-09-03 21:22:16 +0000517
518
519static llvm::cl::opt<bool>
520Trigraphs("trigraphs", llvm::cl::desc("Process trigraph sequences."));
521
522static llvm::cl::opt<bool>
523Ansi("ansi", llvm::cl::desc("Equivalent to specifying -std=c89."));
524
Reid Spencer5f016e22007-07-11 17:01:13 +0000525// FIXME: add:
Reid Spencer5f016e22007-07-11 17:01:13 +0000526// -fdollars-in-identifiers
Daniel Dunbardcb4a1a2008-08-23 08:43:39 +0000527static void InitializeLanguageStandard(LangOptions &Options, LangKind LK,
528 TargetInfo *Target) {
Chris Lattner8fc4dfb2008-12-04 22:54:33 +0000529 // Allow the target to set the default the langauge options as it sees fit.
530 Target->getDefaultLangOptions(Options);
Ted Kremenekea644d82008-09-03 21:22:16 +0000531
532 if (Ansi) // "The -ansi option is equivalent to -std=c89."
533 LangStd = lang_c89;
534
Reid Spencer5f016e22007-07-11 17:01:13 +0000535 if (LangStd == lang_unspecified) {
536 // Based on the base language, pick one.
Ted Kremenek8904f152007-12-05 23:49:08 +0000537 switch (LK) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000538 default: assert(0 && "Unknown base language");
539 case langkind_c:
Chris Lattnera778d7d2008-10-22 17:29:21 +0000540 case langkind_asm_cpp:
Reid Spencer5f016e22007-07-11 17:01:13 +0000541 case langkind_c_cpp:
Ted Kremenek85888962008-10-21 00:54:44 +0000542 case langkind_c_pch:
Reid Spencer5f016e22007-07-11 17:01:13 +0000543 case langkind_objc:
544 case langkind_objc_cpp:
Ted Kremenek85888962008-10-21 00:54:44 +0000545 case langkind_objc_pch:
Reid Spencer5f016e22007-07-11 17:01:13 +0000546 LangStd = lang_gnu99;
547 break;
548 case langkind_cxx:
549 case langkind_cxx_cpp:
550 case langkind_objcxx:
551 case langkind_objcxx_cpp:
Ted Kremenekf8901912009-01-09 00:38:08 +0000552 case langkind_objcxx_pch:
Reid Spencer5f016e22007-07-11 17:01:13 +0000553 LangStd = lang_gnucxx98;
554 break;
555 }
556 }
557
558 switch (LangStd) {
559 default: assert(0 && "Unknown language standard!");
560
561 // Fall through from newer standards to older ones. This isn't really right.
562 // FIXME: Enable specifically the right features based on the language stds.
Chris Lattnerd4b80f12007-07-16 04:18:29 +0000563 case lang_gnucxx0x:
564 case lang_cxx0x:
565 Options.CPlusPlus0x = 1;
566 // FALL THROUGH
Reid Spencer5f016e22007-07-11 17:01:13 +0000567 case lang_gnucxx98:
568 case lang_cxx98:
569 Options.CPlusPlus = 1;
570 Options.CXXOperatorNames = !NoOperatorNames;
Nate Begeman8aebcb72007-11-15 07:30:50 +0000571 Options.Boolean = 1;
Reid Spencer5f016e22007-07-11 17:01:13 +0000572 // FALL THROUGH.
573 case lang_gnu99:
574 case lang_c99:
Reid Spencer5f016e22007-07-11 17:01:13 +0000575 Options.C99 = 1;
576 Options.HexFloats = 1;
577 // FALL THROUGH.
578 case lang_gnu89:
579 Options.BCPLComment = 1; // Only for C99/C++.
580 // FALL THROUGH.
581 case lang_c94:
Chris Lattner3426b9b2008-02-25 04:01:39 +0000582 Options.Digraphs = 1; // C94, C99, C++.
583 // FALL THROUGH.
Reid Spencer5f016e22007-07-11 17:01:13 +0000584 case lang_c89:
585 break;
586 }
Argyrios Kyrtzidisd1465522008-09-11 04:21:06 +0000587
588 if (Options.CPlusPlus) {
589 Options.C99 = 0;
590 Options.HexFloats = (LangStd == lang_gnucxx98 || LangStd==lang_gnucxx0x);
591 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000592
Chris Lattnerd658b562008-04-05 06:32:51 +0000593 if (LangStd == lang_c89 || LangStd == lang_c94 || LangStd == lang_gnu89)
594 Options.ImplicitInt = 1;
595 else
596 Options.ImplicitInt = 0;
Ted Kremenekea644d82008-09-03 21:22:16 +0000597
598 // Mimicing gcc's behavior, trigraphs are only enabled if -trigraphs or -ansi
599 // is specified, or -std is set to a conforming mode.
Chris Lattner802db9b2008-12-05 00:10:44 +0000600 Options.Trigraphs = LangStd < lang_gnu_START;
601 if (Trigraphs.getPosition())
602 Options.Trigraphs = Trigraphs; // Command line option wins.
Ted Kremenekea644d82008-09-03 21:22:16 +0000603
Chris Lattner802db9b2008-12-05 00:10:44 +0000604 // If in a conformant language mode (e.g. -std=c99) Blocks defaults to off
605 // even if they are normally on for the target. In GNU modes (e.g.
606 // -std=gnu99) the default for blocks depends on the target settings.
Anders Carlssone56f6ff2009-01-21 18:47:36 +0000607 // However, blocks are not turned off when compiling Obj-C or Obj-C++ code.
608 if (!Options.ObjC1 && LangStd < lang_gnu_START)
Chris Lattner802db9b2008-12-05 00:10:44 +0000609 Options.Blocks = 0;
610
Reid Spencer5f016e22007-07-11 17:01:13 +0000611 Options.DollarIdents = 1; // FIXME: Really a target property.
Chris Lattnerae0ee032008-12-04 23:20:07 +0000612 if (PascalStrings.getPosition())
613 Options.PascalStrings = PascalStrings;
Steve Naroffd62701b2008-02-07 03:50:06 +0000614 Options.Microsoft = MSExtensions;
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000615 Options.WritableStrings = WritableStrings;
Anders Carlsson695dbb62007-11-30 04:21:22 +0000616 Options.LaxVectorConversions = LaxVectorConversions;
Daniel Dunbar6379a7a2008-08-11 17:36:14 +0000617 Options.Exceptions = Exceptions;
Chris Lattnerae0ee032008-12-04 23:20:07 +0000618 if (EnableBlocks.getPosition())
619 Options.Blocks = EnableBlocks;
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000620
Chris Lattner8fc4dfb2008-12-04 22:54:33 +0000621 // Override the default runtime if the user requested it.
622 if (NeXTRuntime)
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000623 Options.NeXTRuntime = 1;
Chris Lattner8fc4dfb2008-12-04 22:54:33 +0000624 else if (GNURuntime)
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000625 Options.NeXTRuntime = 0;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000626
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000627 if (ObjCNonFragileABI)
628 Options.ObjCNonFragileABI = 1;
Reid Spencer5f016e22007-07-11 17:01:13 +0000629}
630
Ted Kremenek01d9dbf2008-04-29 04:37:03 +0000631static llvm::cl::opt<bool>
632ObjCExclusiveGC("fobjc-gc-only",
633 llvm::cl::desc("Use GC exclusively for Objective-C related "
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000634 "memory management"));
Ted Kremenek01d9dbf2008-04-29 04:37:03 +0000635
636static llvm::cl::opt<bool>
637ObjCEnableGC("fobjc-gc",
Nico Weberfd54ebc2008-08-05 23:33:20 +0000638 llvm::cl::desc("Enable Objective-C garbage collection"));
Ted Kremenek01d9dbf2008-04-29 04:37:03 +0000639
640void InitializeGCMode(LangOptions &Options) {
641 if (ObjCExclusiveGC)
642 Options.setGCMode(LangOptions::GCOnly);
643 else if (ObjCEnableGC)
644 Options.setGCMode(LangOptions::HybridGC);
645}
646
647
Reid Spencer5f016e22007-07-11 17:01:13 +0000648//===----------------------------------------------------------------------===//
649// Our DiagnosticClient implementation
650//===----------------------------------------------------------------------===//
651
652// FIXME: Werror should take a list of things, -Werror=foo,bar
653static llvm::cl::opt<bool>
654WarningsAsErrors("Werror", llvm::cl::desc("Treat all warnings as errors"));
655
656static llvm::cl::opt<bool>
Chris Lattner5b4681c2008-05-29 15:36:45 +0000657SilenceWarnings("w", llvm::cl::desc("Do not emit any warnings"));
658
659static llvm::cl::opt<bool>
Reid Spencer5f016e22007-07-11 17:01:13 +0000660WarnOnExtensions("pedantic", llvm::cl::init(false),
661 llvm::cl::desc("Issue a warning on uses of GCC extensions"));
662
663static llvm::cl::opt<bool>
664ErrorOnExtensions("pedantic-errors",
665 llvm::cl::desc("Issue an error on uses of GCC extensions"));
666
667static llvm::cl::opt<bool>
Daniel Dunbar2fe09972008-09-12 18:10:20 +0000668SuppressSystemWarnings("suppress-system-warnings",
Daniel Dunbar320a0542008-09-30 20:49:53 +0000669 llvm::cl::desc("Suppress warnings issued in system headers"),
Daniel Dunbar2fe09972008-09-12 18:10:20 +0000670 llvm::cl::init(true));
671
672static llvm::cl::opt<bool>
Daniel Dunbard77b2512009-01-14 18:56:36 +0000673WarnUnusedMacros("Wunused-macros",
Reid Spencer5f016e22007-07-11 17:01:13 +0000674 llvm::cl::desc("Warn for unused macros in the main translation unit"));
675
Ted Kremenekdb87bca2007-11-13 18:37:02 +0000676static llvm::cl::opt<bool>
677WarnFloatEqual("Wfloat-equal",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000678 llvm::cl::desc("Warn about equality comparisons of floating point values"));
Ted Kremenekdb87bca2007-11-13 18:37:02 +0000679
Ted Kremenek73da5902007-12-17 17:50:07 +0000680static llvm::cl::opt<bool>
Fariborz Jahanian17d0d0d2009-01-08 23:23:10 +0000681WarnPropertyReadonlyAttrs("Wreadonly-setter-attrs",
682 llvm::cl::desc("Warn about readonly properties with writable attributes"));
683
684static llvm::cl::opt<bool>
Ted Kremenek73da5902007-12-17 17:50:07 +0000685WarnNoFormatNonLiteral("Wno-format-nonliteral",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000686 llvm::cl::desc("Do not warn about non-literal format strings"));
Ted Kremenek73da5902007-12-17 17:50:07 +0000687
Chris Lattner116a4b12008-01-23 17:19:46 +0000688static llvm::cl::opt<bool>
689WarnUndefMacros("Wundef",
690 llvm::cl::desc("Warn on use of undefined macros in #if's"));
691
Chris Lattner37d10842008-05-05 21:18:06 +0000692static llvm::cl::opt<bool>
Ted Kremenek358256d2008-05-30 16:42:02 +0000693WarnImplicitFunctionDeclaration("Wimplicit-function-declaration",
694 llvm::cl::desc("Warn about uses of implicitly defined functions"));
Chris Lattner116a4b12008-01-23 17:19:46 +0000695
Steve Narofffe6b0dc2008-10-21 10:37:50 +0000696static llvm::cl::opt<bool>
697WarnNoStrictSelectorMatch("Wno-strict-selector-match",
698 llvm::cl::desc("Do not warn about duplicate methods that have the same size and alignment"),
699 llvm::cl::init(true));
700
Reid Spencer5f016e22007-07-11 17:01:13 +0000701/// InitializeDiagnostics - Initialize the diagnostic object, based on the
702/// current command line option settings.
703static void InitializeDiagnostics(Diagnostic &Diags) {
Chris Lattner5b4681c2008-05-29 15:36:45 +0000704 Diags.setIgnoreAllWarnings(SilenceWarnings);
Reid Spencer5f016e22007-07-11 17:01:13 +0000705 Diags.setWarningsAsErrors(WarningsAsErrors);
706 Diags.setWarnOnExtensions(WarnOnExtensions);
707 Diags.setErrorOnExtensions(ErrorOnExtensions);
708
Daniel Dunbar2fe09972008-09-12 18:10:20 +0000709 // Suppress warnings in system headers unless requested not to.
710 Diags.setSuppressSystemWarnings(SuppressSystemWarnings);
711
Reid Spencer5f016e22007-07-11 17:01:13 +0000712 // Silence the "macro is not used" warning unless requested.
713 if (!WarnUnusedMacros)
714 Diags.setDiagnosticMapping(diag::pp_macro_not_used, diag::MAP_IGNORE);
Ted Kremenekdb87bca2007-11-13 18:37:02 +0000715
716 // Silence "floating point comparison" warnings unless requested.
717 if (!WarnFloatEqual)
718 Diags.setDiagnosticMapping(diag::warn_floatingpoint_eq, diag::MAP_IGNORE);
Ted Kremenek73da5902007-12-17 17:50:07 +0000719
Fariborz Jahanian17d0d0d2009-01-08 23:23:10 +0000720 if (!WarnPropertyReadonlyAttrs)
721 Diags.setDiagnosticMapping(diag::warn_objc_property_attr_mutually_exclusive,
722 diag::MAP_IGNORE);
723
Ted Kremenek73da5902007-12-17 17:50:07 +0000724 // Silence "format string is not a string literal" warnings if requested
725 if (WarnNoFormatNonLiteral)
Ted Kremenek7c1d3df2007-12-17 17:50:39 +0000726 Diags.setDiagnosticMapping(diag::warn_printf_not_string_constant,
727 diag::MAP_IGNORE);
Chris Lattner116a4b12008-01-23 17:19:46 +0000728 if (!WarnUndefMacros)
729 Diags.setDiagnosticMapping(diag::warn_pp_undef_identifier,diag::MAP_IGNORE);
Steve Naroffe7a37302008-02-11 22:40:08 +0000730
Chris Lattner88eccaf2009-01-29 06:55:46 +0000731 if (WarnImplicitFunctionDeclaration)
732 Diags.setDiagnosticMapping(diag::ext_implicit_function_decl,
733 diag::MAP_WARNING);
734 else
Chris Lattner37d10842008-05-05 21:18:06 +0000735 Diags.setDiagnosticMapping(diag::warn_implicit_function_decl,
736 diag::MAP_IGNORE);
Reid Spencer5f016e22007-07-11 17:01:13 +0000737}
738
739//===----------------------------------------------------------------------===//
Ted Kremenekcb330932008-02-18 21:21:23 +0000740// Analysis-specific options.
741//===----------------------------------------------------------------------===//
742
743static llvm::cl::opt<std::string>
744AnalyzeSpecificFunction("analyze-function",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000745 llvm::cl::desc("Run analysis on specific function"));
Ted Kremenekcb330932008-02-18 21:21:23 +0000746
Ted Kremenekffe0f432008-03-07 22:58:01 +0000747static llvm::cl::opt<bool>
Ted Kremenekd71ed262008-04-10 22:16:52 +0000748TrimGraph("trim-egraph",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000749 llvm::cl::desc("Only show error-related paths in the analysis graph"));
Ted Kremenekffe0f432008-03-07 22:58:01 +0000750
Ted Kremenekcb330932008-02-18 21:21:23 +0000751//===----------------------------------------------------------------------===//
Ted Kremenekae360762007-12-03 22:06:55 +0000752// Target Triple Processing.
753//===----------------------------------------------------------------------===//
754
755static llvm::cl::opt<std::string>
756TargetTriple("triple",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000757 llvm::cl::desc("Specify target triple (e.g. i686-apple-darwin9)"));
Ted Kremenekae360762007-12-03 22:06:55 +0000758
Chris Lattner42e67372008-03-05 01:18:20 +0000759static llvm::cl::opt<std::string>
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000760Arch("arch", llvm::cl::desc("Specify target architecture (e.g. i686)"));
Ted Kremenekae360762007-12-03 22:06:55 +0000761
Chris Lattner6a30c1f2008-09-30 01:13:12 +0000762static llvm::cl::opt<std::string>
763MacOSVersionMin("mmacosx-version-min",
764 llvm::cl::desc("Specify target Mac OS/X version (e.g. 10.5)"));
765
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000766// If -mmacosx-version-min=10.3.9 is specified, change the triple from being
767// something like powerpc-apple-darwin9 to powerpc-apple-darwin7
768static void HandleMacOSVersionMin(std::string &Triple) {
769 std::string::size_type DarwinDashIdx = Triple.find("-darwin");
770 if (DarwinDashIdx == std::string::npos) {
771 fprintf(stderr,
772 "-mmacosx-version-min only valid for darwin (Mac OS/X) targets\n");
773 exit(1);
774 }
775 unsigned DarwinNumIdx = DarwinDashIdx + strlen("-darwin");
776
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000777 // Remove the number.
778 Triple.resize(DarwinNumIdx);
779
780 // Validate that MacOSVersionMin is a 'version number', starting with 10.[3-9]
781 bool MacOSVersionMinIsInvalid = false;
782 int VersionNum = 0;
783 if (MacOSVersionMin.size() < 4 ||
784 MacOSVersionMin.substr(0, 3) != "10." ||
785 !isdigit(MacOSVersionMin[3])) {
786 MacOSVersionMinIsInvalid = true;
787 } else {
788 const char *Start = MacOSVersionMin.c_str()+3;
789 char *End = 0;
790 VersionNum = (int)strtol(Start, &End, 10);
791
Chris Lattner079f2c462008-09-30 20:30:12 +0000792 // The version number must be in the range 0-9.
793 MacOSVersionMinIsInvalid = (unsigned)VersionNum > 9;
794
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000795 // Turn MacOSVersionMin into a darwin number: e.g. 10.3.9 is 3 -> 7.
796 Triple += llvm::itostr(VersionNum+4);
797
Chris Lattner079f2c462008-09-30 20:30:12 +0000798 if (End[0] == '.' && isdigit(End[1]) && End[2] == '\0') { // 10.4.7 is ok.
799 // Add the period piece (.7) to the end of the triple. This gives us
800 // something like ...-darwin8.7
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000801 Triple += End;
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000802 } else if (End[0] != '\0') { // "10.4" is ok. 10.4x is not.
803 MacOSVersionMinIsInvalid = true;
804 }
805 }
806
807 if (MacOSVersionMinIsInvalid) {
808 fprintf(stderr,
809 "-mmacosx-version-min=%s is invalid, expected something like '10.4'.\n",
810 MacOSVersionMin.c_str());
811 exit(1);
812 }
813}
814
815/// CreateTargetTriple - Process the various options that affect the target
816/// triple and build a final aggregate triple that we are compiling for.
Chris Lattner6fd9fa12008-03-09 01:35:13 +0000817static std::string CreateTargetTriple() {
Ted Kremenekae360762007-12-03 22:06:55 +0000818 // Initialize base triple. If a -triple option has been specified, use
819 // that triple. Otherwise, default to the host triple.
Chris Lattner6590d212007-12-12 05:01:48 +0000820 std::string Triple = TargetTriple;
Daniel Dunbare553a722008-10-02 01:21:33 +0000821 if (Triple.empty()) {
822 Triple = LLVM_HOSTTRIPLE;
823
Daniel Dunbara6291902008-12-12 18:34:35 +0000824 // Force i<N>86 to i386 when using LLVM_HOSTTRIPLE.
825 if (Triple[0] == 'i' && isdigit(Triple[1]) &&
826 Triple[2] == '8' && Triple[3] == '6')
827 Triple[1] = '3';
828
Daniel Dunbare553a722008-10-02 01:21:33 +0000829 // On darwin, we want to update the version to match that of the
830 // host.
831 std::string::size_type DarwinDashIdx = Triple.find("-darwin");
832 if (DarwinDashIdx != std::string::npos) {
833 Triple.resize(DarwinDashIdx + strlen("-darwin"));
834
Daniel Dunbara6291902008-12-12 18:34:35 +0000835 // Only add the major part of the os version.
Chris Lattnera05ff452009-01-22 20:57:52 +0000836 std::string Version = llvm::sys::getOSVersion();
Daniel Dunbara6291902008-12-12 18:34:35 +0000837 Triple += Version.substr(0, Version.find('.'));
Daniel Dunbare553a722008-10-02 01:21:33 +0000838 }
839 }
Ted Kremenekae360762007-12-03 22:06:55 +0000840
Chris Lattner6fd9fa12008-03-09 01:35:13 +0000841 // If -arch foo was specified, remove the architecture from the triple we have
842 // so far and replace it with the specified one.
Chris Lattner6a30c1f2008-09-30 01:13:12 +0000843 if (!Arch.empty()) {
844 // Decompose the base triple into "arch" and suffix.
845 std::string::size_type FirstDashIdx = Triple.find('-');
Chris Lattner6fd9fa12008-03-09 01:35:13 +0000846
Chris Lattner6a30c1f2008-09-30 01:13:12 +0000847 if (FirstDashIdx == std::string::npos) {
848 fprintf(stderr,
849 "Malformed target triple: \"%s\" ('-' could not be found).\n",
850 Triple.c_str());
851 exit(1);
852 }
Ted Kremenekae360762007-12-03 22:06:55 +0000853
Chris Lattner6a30c1f2008-09-30 01:13:12 +0000854 Triple = Arch + std::string(Triple.begin()+FirstDashIdx, Triple.end());
855 }
856
857 // If -mmacosx-version-min=10.3.9 is specified, change the triple from being
858 // something like powerpc-apple-darwin9 to powerpc-apple-darwin7
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000859 if (!MacOSVersionMin.empty())
860 HandleMacOSVersionMin(Triple);
Ted Kremenekae360762007-12-03 22:06:55 +0000861
Chris Lattner6a30c1f2008-09-30 01:13:12 +0000862 return Triple;
Ted Kremenekae360762007-12-03 22:06:55 +0000863}
864
865//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +0000866// Preprocessor Initialization
867//===----------------------------------------------------------------------===//
868
869// FIXME: Preprocessor builtins to support.
870// -A... - Play with #assertions
871// -undef - Undefine all predefined macros
872
873static llvm::cl::list<std::string>
874D_macros("D", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
875 llvm::cl::desc("Predefine the specified macro"));
876static llvm::cl::list<std::string>
877U_macros("U", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
878 llvm::cl::desc("Undefine the specified macro"));
879
Chris Lattner64299f82008-01-10 01:53:41 +0000880static llvm::cl::list<std::string>
881ImplicitIncludes("include", llvm::cl::value_desc("file"),
882 llvm::cl::desc("Include file before parsing"));
883
884
Reid Spencer5f016e22007-07-11 17:01:13 +0000885// Append a #define line to Buf for Macro. Macro should be of the form XXX,
886// in which case we emit "#define XXX 1" or "XXX=Y z W" in which case we emit
887// "#define XXX Y z W". To get a #define with no value, use "XXX=".
888static void DefineBuiltinMacro(std::vector<char> &Buf, const char *Macro,
889 const char *Command = "#define ") {
890 Buf.insert(Buf.end(), Command, Command+strlen(Command));
891 if (const char *Equal = strchr(Macro, '=')) {
892 // Turn the = into ' '.
893 Buf.insert(Buf.end(), Macro, Equal);
894 Buf.push_back(' ');
895 Buf.insert(Buf.end(), Equal+1, Equal+strlen(Equal));
896 } else {
897 // Push "macroname 1".
898 Buf.insert(Buf.end(), Macro, Macro+strlen(Macro));
899 Buf.push_back(' ');
900 Buf.push_back('1');
901 }
902 Buf.push_back('\n');
903}
904
Chris Lattner64299f82008-01-10 01:53:41 +0000905/// AddImplicitInclude - Add an implicit #include of the specified file to the
906/// predefines buffer.
907static void AddImplicitInclude(std::vector<char> &Buf, const std::string &File){
908 const char *Inc = "#include \"";
909 Buf.insert(Buf.end(), Inc, Inc+strlen(Inc));
910 Buf.insert(Buf.end(), File.begin(), File.end());
911 Buf.push_back('"');
912 Buf.push_back('\n');
913}
914
Reid Spencer5f016e22007-07-11 17:01:13 +0000915
Chris Lattner53b0dab2007-10-09 22:10:18 +0000916/// InitializePreprocessor - Initialize the preprocessor getting it and the
Chris Lattner51574ea2008-04-19 23:25:44 +0000917/// environment ready to process a single file. This returns true on error.
Chris Lattner53b0dab2007-10-09 22:10:18 +0000918///
Chris Lattner51574ea2008-04-19 23:25:44 +0000919static bool InitializePreprocessor(Preprocessor &PP,
920 bool InitializeSourceMgr,
921 const std::string &InFile) {
Chris Lattnerdee73592007-12-15 20:48:40 +0000922 FileManager &FileMgr = PP.getFileManager();
Reid Spencer5f016e22007-07-11 17:01:13 +0000923
Chris Lattner53b0dab2007-10-09 22:10:18 +0000924 // Figure out where to get and map in the main file.
Chris Lattnerdee73592007-12-15 20:48:40 +0000925 SourceManager &SourceMgr = PP.getSourceManager();
Ted Kremenek339b9c22008-04-17 22:31:54 +0000926
927 if (InitializeSourceMgr) {
928 if (InFile != "-") {
929 const FileEntry *File = FileMgr.getFile(InFile);
930 if (File) SourceMgr.createMainFileID(File, SourceLocation());
Chris Lattner2b2453a2009-01-17 06:22:33 +0000931 if (SourceMgr.getMainFileID().isInvalid()) {
Ted Kremenek339b9c22008-04-17 22:31:54 +0000932 fprintf(stderr, "Error reading '%s'!\n",InFile.c_str());
Chris Lattner51574ea2008-04-19 23:25:44 +0000933 return true;
Ted Kremenek339b9c22008-04-17 22:31:54 +0000934 }
935 } else {
936 llvm::MemoryBuffer *SB = llvm::MemoryBuffer::getSTDIN();
937 if (SB) SourceMgr.createMainFileIDForMemBuffer(SB);
Chris Lattner2b2453a2009-01-17 06:22:33 +0000938 if (SourceMgr.getMainFileID().isInvalid()) {
Ted Kremenek339b9c22008-04-17 22:31:54 +0000939 fprintf(stderr, "Error reading standard input! Empty?\n");
Chris Lattner51574ea2008-04-19 23:25:44 +0000940 return true;
Ted Kremenek339b9c22008-04-17 22:31:54 +0000941 }
Chris Lattner53b0dab2007-10-09 22:10:18 +0000942 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000943 }
Sam Bishop1102d6b2008-04-14 14:41:57 +0000944
Chris Lattneraa391972008-04-19 23:09:31 +0000945 std::vector<char> PredefineBuffer;
946
Reid Spencer5f016e22007-07-11 17:01:13 +0000947 // Add macros from the command line.
Sam Bishop1102d6b2008-04-14 14:41:57 +0000948 unsigned d = 0, D = D_macros.size();
949 unsigned u = 0, U = U_macros.size();
950 while (d < D || u < U) {
951 if (u == U || (d < D && D_macros.getPosition(d) < U_macros.getPosition(u)))
952 DefineBuiltinMacro(PredefineBuffer, D_macros[d++].c_str());
953 else
954 DefineBuiltinMacro(PredefineBuffer, U_macros[u++].c_str(), "#undef ");
955 }
956
Chris Lattner64299f82008-01-10 01:53:41 +0000957 // FIXME: Read any files specified by -imacros.
958
959 // Add implicit #includes from -include.
960 for (unsigned i = 0, e = ImplicitIncludes.size(); i != e; ++i)
961 AddImplicitInclude(PredefineBuffer, ImplicitIncludes[i]);
Chris Lattner53b0dab2007-10-09 22:10:18 +0000962
Chris Lattneraa391972008-04-19 23:09:31 +0000963 // Null terminate PredefinedBuffer and add it.
Chris Lattner53b0dab2007-10-09 22:10:18 +0000964 PredefineBuffer.push_back(0);
Chris Lattneraa391972008-04-19 23:09:31 +0000965 PP.setPredefines(&PredefineBuffer[0]);
Chris Lattner53b0dab2007-10-09 22:10:18 +0000966
967 // Once we've read this, we're done.
Chris Lattner51574ea2008-04-19 23:25:44 +0000968 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000969}
970
971//===----------------------------------------------------------------------===//
972// Preprocessor include path information.
973//===----------------------------------------------------------------------===//
974
975// This tool exports a large number of command line options to control how the
976// preprocessor searches for header files. At root, however, the Preprocessor
977// object takes a very simple interface: a list of directories to search for
978//
979// FIXME: -nostdinc,-nostdinc++
Chris Lattner0c946412007-08-26 17:47:35 +0000980// FIXME: -imultilib
Reid Spencer5f016e22007-07-11 17:01:13 +0000981//
Chris Lattner64299f82008-01-10 01:53:41 +0000982// FIXME: -imacros
Reid Spencer5f016e22007-07-11 17:01:13 +0000983
984static llvm::cl::opt<bool>
985nostdinc("nostdinc", llvm::cl::desc("Disable standard #include directories"));
986
987// Various command line options. These four add directories to each chain.
988static llvm::cl::list<std::string>
989F_dirs("F", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
990 llvm::cl::desc("Add directory to framework include search path"));
991static llvm::cl::list<std::string>
992I_dirs("I", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
993 llvm::cl::desc("Add directory to include search path"));
994static llvm::cl::list<std::string>
995idirafter_dirs("idirafter", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
996 llvm::cl::desc("Add directory to AFTER include search path"));
997static llvm::cl::list<std::string>
998iquote_dirs("iquote", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
999 llvm::cl::desc("Add directory to QUOTE include search path"));
1000static llvm::cl::list<std::string>
1001isystem_dirs("isystem", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1002 llvm::cl::desc("Add directory to SYSTEM include search path"));
1003
1004// These handle -iprefix/-iwithprefix/-iwithprefixbefore.
1005static llvm::cl::list<std::string>
1006iprefix_vals("iprefix", llvm::cl::value_desc("prefix"), llvm::cl::Prefix,
1007 llvm::cl::desc("Set the -iwithprefix/-iwithprefixbefore prefix"));
1008static llvm::cl::list<std::string>
1009iwithprefix_vals("iwithprefix", llvm::cl::value_desc("dir"), llvm::cl::Prefix,
1010 llvm::cl::desc("Set directory to SYSTEM include search path with prefix"));
1011static llvm::cl::list<std::string>
1012iwithprefixbefore_vals("iwithprefixbefore", llvm::cl::value_desc("dir"),
1013 llvm::cl::Prefix,
1014 llvm::cl::desc("Set directory to include search path with prefix"));
1015
Chris Lattner0c946412007-08-26 17:47:35 +00001016static llvm::cl::opt<std::string>
1017isysroot("isysroot", llvm::cl::value_desc("dir"), llvm::cl::init("/"),
1018 llvm::cl::desc("Set the system root directory (usually /)"));
1019
Reid Spencer5f016e22007-07-11 17:01:13 +00001020// Finally, implement the code that groks the options above.
Chris Lattner5f9eae52008-03-01 08:07:28 +00001021
Reid Spencer5f016e22007-07-11 17:01:13 +00001022/// InitializeIncludePaths - Process the -I options and set them in the
1023/// HeaderSearch object.
Nico Weber0fca0222008-08-22 09:25:22 +00001024void InitializeIncludePaths(const char *Argv0, HeaderSearch &Headers,
1025 FileManager &FM, const LangOptions &Lang) {
1026 InitHeaderSearch Init(Headers, Verbose, isysroot);
1027
Ted Kremenekf3721112008-05-31 00:27:00 +00001028 // Handle -I... and -F... options, walking the lists in parallel.
1029 unsigned Iidx = 0, Fidx = 0;
1030 while (Iidx < I_dirs.size() && Fidx < F_dirs.size()) {
1031 if (I_dirs.getPosition(Iidx) < F_dirs.getPosition(Fidx)) {
Nico Weber0fca0222008-08-22 09:25:22 +00001032 Init.AddPath(I_dirs[Iidx], InitHeaderSearch::Angled, false, true, false);
Ted Kremenekf3721112008-05-31 00:27:00 +00001033 ++Iidx;
1034 } else {
Nico Weber0fca0222008-08-22 09:25:22 +00001035 Init.AddPath(F_dirs[Fidx], InitHeaderSearch::Angled, false, true, true);
Ted Kremenekf3721112008-05-31 00:27:00 +00001036 ++Fidx;
1037 }
1038 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001039
Ted Kremenekf3721112008-05-31 00:27:00 +00001040 // Consume what's left from whatever list was longer.
1041 for (; Iidx != I_dirs.size(); ++Iidx)
Nico Weber0fca0222008-08-22 09:25:22 +00001042 Init.AddPath(I_dirs[Iidx], InitHeaderSearch::Angled, false, true, false);
Ted Kremenekf3721112008-05-31 00:27:00 +00001043 for (; Fidx != F_dirs.size(); ++Fidx)
Nico Weber0fca0222008-08-22 09:25:22 +00001044 Init.AddPath(F_dirs[Fidx], InitHeaderSearch::Angled, false, true, true);
Reid Spencer5f016e22007-07-11 17:01:13 +00001045
1046 // Handle -idirafter... options.
1047 for (unsigned i = 0, e = idirafter_dirs.size(); i != e; ++i)
Nico Weber0fca0222008-08-22 09:25:22 +00001048 Init.AddPath(idirafter_dirs[i], InitHeaderSearch::After,
1049 false, true, false);
Reid Spencer5f016e22007-07-11 17:01:13 +00001050
1051 // Handle -iquote... options.
1052 for (unsigned i = 0, e = iquote_dirs.size(); i != e; ++i)
Nico Weber0fca0222008-08-22 09:25:22 +00001053 Init.AddPath(iquote_dirs[i], InitHeaderSearch::Quoted, false, true, false);
Reid Spencer5f016e22007-07-11 17:01:13 +00001054
1055 // Handle -isystem... options.
1056 for (unsigned i = 0, e = isystem_dirs.size(); i != e; ++i)
Nico Weber0fca0222008-08-22 09:25:22 +00001057 Init.AddPath(isystem_dirs[i], InitHeaderSearch::System, false, true, false);
Reid Spencer5f016e22007-07-11 17:01:13 +00001058
1059 // Walk the -iprefix/-iwithprefix/-iwithprefixbefore argument lists in
1060 // parallel, processing the values in order of occurance to get the right
1061 // prefixes.
1062 {
1063 std::string Prefix = ""; // FIXME: this isn't the correct default prefix.
1064 unsigned iprefix_idx = 0;
1065 unsigned iwithprefix_idx = 0;
1066 unsigned iwithprefixbefore_idx = 0;
1067 bool iprefix_done = iprefix_vals.empty();
1068 bool iwithprefix_done = iwithprefix_vals.empty();
1069 bool iwithprefixbefore_done = iwithprefixbefore_vals.empty();
1070 while (!iprefix_done || !iwithprefix_done || !iwithprefixbefore_done) {
1071 if (!iprefix_done &&
1072 (iwithprefix_done ||
1073 iprefix_vals.getPosition(iprefix_idx) <
1074 iwithprefix_vals.getPosition(iwithprefix_idx)) &&
1075 (iwithprefixbefore_done ||
1076 iprefix_vals.getPosition(iprefix_idx) <
1077 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
1078 Prefix = iprefix_vals[iprefix_idx];
1079 ++iprefix_idx;
1080 iprefix_done = iprefix_idx == iprefix_vals.size();
1081 } else if (!iwithprefix_done &&
1082 (iwithprefixbefore_done ||
1083 iwithprefix_vals.getPosition(iwithprefix_idx) <
1084 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
Nico Weber0fca0222008-08-22 09:25:22 +00001085 Init.AddPath(Prefix+iwithprefix_vals[iwithprefix_idx],
1086 InitHeaderSearch::System, false, false, false);
Reid Spencer5f016e22007-07-11 17:01:13 +00001087 ++iwithprefix_idx;
1088 iwithprefix_done = iwithprefix_idx == iwithprefix_vals.size();
1089 } else {
Nico Weber0fca0222008-08-22 09:25:22 +00001090 Init.AddPath(Prefix+iwithprefixbefore_vals[iwithprefixbefore_idx],
1091 InitHeaderSearch::Angled, false, false, false);
Reid Spencer5f016e22007-07-11 17:01:13 +00001092 ++iwithprefixbefore_idx;
1093 iwithprefixbefore_done =
1094 iwithprefixbefore_idx == iwithprefixbefore_vals.size();
1095 }
1096 }
1097 }
Chris Lattner5f9eae52008-03-01 08:07:28 +00001098
Nico Weber0fca0222008-08-22 09:25:22 +00001099 Init.AddDefaultEnvVarPaths(Lang);
Chris Lattner5f9eae52008-03-01 08:07:28 +00001100
Chris Lattnerdcaa0962008-03-03 03:16:03 +00001101 // Add the clang headers, which are relative to the clang driver.
1102 llvm::sys::Path MainExecutablePath =
Chris Lattner985e1822008-03-03 05:57:43 +00001103 llvm::sys::Path::GetMainExecutable(Argv0,
1104 (void*)(intptr_t)InitializeIncludePaths);
Chris Lattnerdcaa0962008-03-03 03:16:03 +00001105 if (!MainExecutablePath.isEmpty()) {
1106 MainExecutablePath.eraseComponent(); // Remove /clang from foo/bin/clang
1107 MainExecutablePath.eraseComponent(); // Remove /bin from foo/bin
1108 MainExecutablePath.appendComponent("Headers"); // Get foo/Headers
Nico Weber0fca0222008-08-22 09:25:22 +00001109 Init.AddPath(MainExecutablePath.c_str(), InitHeaderSearch::System,
1110 false, false, false);
Chris Lattnerdcaa0962008-03-03 03:16:03 +00001111 }
1112
Nico Weber0fca0222008-08-22 09:25:22 +00001113 if (!nostdinc)
1114 Init.AddDefaultSystemIncludePaths(Lang);
Reid Spencer5f016e22007-07-11 17:01:13 +00001115
1116 // Now that we have collected all of the include paths, merge them all
1117 // together and tell the preprocessor about them.
1118
Nico Weber0fca0222008-08-22 09:25:22 +00001119 Init.Realize();
Reid Spencer5f016e22007-07-11 17:01:13 +00001120}
1121
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001122//===----------------------------------------------------------------------===//
1123// Driver PreprocessorFactory - For lazily generating preprocessors ...
1124//===----------------------------------------------------------------------===//
1125
1126namespace {
1127class VISIBILITY_HIDDEN DriverPreprocessorFactory : public PreprocessorFactory {
Ted Kremenek339b9c22008-04-17 22:31:54 +00001128 const std::string &InFile;
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001129 Diagnostic &Diags;
1130 const LangOptions &LangInfo;
1131 TargetInfo &Target;
1132 SourceManager &SourceMgr;
1133 HeaderSearch &HeaderInfo;
Ted Kremenek339b9c22008-04-17 22:31:54 +00001134 bool InitializeSourceMgr;
1135
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001136public:
Ted Kremenek339b9c22008-04-17 22:31:54 +00001137 DriverPreprocessorFactory(const std::string &infile,
1138 Diagnostic &diags, const LangOptions &opts,
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001139 TargetInfo &target, SourceManager &SM,
1140 HeaderSearch &Headers)
Ted Kremenek339b9c22008-04-17 22:31:54 +00001141 : InFile(infile), Diags(diags), LangInfo(opts), Target(target),
1142 SourceMgr(SM), HeaderInfo(Headers), InitializeSourceMgr(true) {}
1143
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001144
1145 virtual ~DriverPreprocessorFactory() {}
1146
1147 virtual Preprocessor* CreatePreprocessor() {
Ted Kremenek72b1b152009-01-15 18:47:46 +00001148 llvm::OwningPtr<PTHManager> PTHMgr;
1149
1150 // Use PTH?
1151 if (!TokenCache.empty())
Ted Kremenek8a6aec62009-01-28 20:49:33 +00001152 PTHMgr.reset(PTHManager::Create(TokenCache, &Diags));
Ted Kremenek72b1b152009-01-15 18:47:46 +00001153
1154 // Create the Preprocessor.
1155 llvm::OwningPtr<Preprocessor> PP(new Preprocessor(Diags, LangInfo, Target,
1156 SourceMgr, HeaderInfo,
1157 PTHMgr.get()));
1158
1159 // Note that this is different then passing PTHMgr to Preprocessor's ctor.
1160 // That argument is used as the IdentifierInfoLookup argument to
1161 // IdentifierTable's ctor.
1162 if (PTHMgr) {
1163 PTHMgr->setPreprocessor(PP.get());
1164 PP->setPTHManager(PTHMgr.take());
1165 }
Ted Kremenek339b9c22008-04-17 22:31:54 +00001166
Chris Lattner51574ea2008-04-19 23:25:44 +00001167 if (InitializePreprocessor(*PP, InitializeSourceMgr, InFile)) {
Ted Kremenek339b9c22008-04-17 22:31:54 +00001168 return NULL;
1169 }
1170
Daniel Dunbar750c3582008-10-24 22:12:41 +00001171 /// FIXME: PP can only handle one callback
1172 if (ProgAction != PrintPreprocessedInput) {
1173 const char* ErrStr;
Ted Kremenek72b1b152009-01-15 18:47:46 +00001174 bool DFG = CreateDependencyFileGen(PP.get(), OutputFile, InFile, ErrStr);
Daniel Dunbar750c3582008-10-24 22:12:41 +00001175 if (!DFG && ErrStr) {
Ted Kremenek9a30c242008-10-25 20:19:34 +00001176 fprintf(stderr, "%s", ErrStr);
Daniel Dunbar750c3582008-10-24 22:12:41 +00001177 return NULL;
1178 }
1179 }
1180
Ted Kremenek339b9c22008-04-17 22:31:54 +00001181 InitializeSourceMgr = false;
Ted Kremenek72b1b152009-01-15 18:47:46 +00001182 return PP.take();
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001183 }
1184};
1185}
Reid Spencer5f016e22007-07-11 17:01:13 +00001186
Reid Spencer5f016e22007-07-11 17:01:13 +00001187//===----------------------------------------------------------------------===//
1188// Basic Parser driver
1189//===----------------------------------------------------------------------===//
1190
Chris Lattner51574ea2008-04-19 23:25:44 +00001191static void ParseFile(Preprocessor &PP, MinimalAction *PA) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001192 Parser P(PP, *PA);
Ted Kremenek95041a22007-12-19 22:51:13 +00001193 PP.EnterMainSourceFile();
Reid Spencer5f016e22007-07-11 17:01:13 +00001194
1195 // Parsing the specified input file.
1196 P.ParseTranslationUnit();
1197 delete PA;
1198}
1199
1200//===----------------------------------------------------------------------===//
Daniel Dunbar70f92432008-10-23 05:50:47 +00001201// Code generation options
1202//===----------------------------------------------------------------------===//
1203
1204static llvm::cl::opt<bool>
1205OptSize("Os",
1206 llvm::cl::desc("Optimize for size"));
1207
1208// It might be nice to add bounds to the CommandLine library directly.
1209struct OptLevelParser : public llvm::cl::parser<unsigned> {
1210 bool parse(llvm::cl::Option &O, const char *ArgName,
1211 const std::string &Arg, unsigned &Val) {
1212 if (llvm::cl::parser<unsigned>::parse(O, ArgName, Arg, Val))
1213 return true;
1214 // FIXME: Support -O4.
1215 if (Val > 3)
1216 return O.error(": '" + Arg + "' invalid optimization level!");
1217 return false;
1218 }
1219};
1220static llvm::cl::opt<unsigned, false, OptLevelParser>
1221OptLevel("O", llvm::cl::Prefix,
1222 llvm::cl::desc("Optimization level"),
1223 llvm::cl::init(0));
1224
1225static void InitializeCompileOptions(CompileOptions &Opts) {
Daniel Dunbar70f92432008-10-23 05:50:47 +00001226 Opts.OptimizeSize = OptSize;
Daniel Dunbarac7ffe02008-10-29 07:56:11 +00001227 if (OptSize) {
1228 // -Os implies -O2
1229 // FIXME: Diagnose conflicting options.
1230 Opts.OptimizationLevel = 2;
1231 } else {
1232 Opts.OptimizationLevel = OptLevel;
1233 }
Daniel Dunbar8e8f3b72008-10-29 03:42:18 +00001234
1235 // FIXME: There are llvm-gcc options to control these selectively.
1236 Opts.InlineFunctions = (Opts.OptimizationLevel > 1);
1237 Opts.UnrollLoops = (Opts.OptimizationLevel > 1 && !OptSize);
1238 Opts.SimplifyLibCalls = 1;
Daniel Dunbardd913e52008-10-31 09:34:21 +00001239
1240#ifdef NDEBUG
1241 Opts.VerifyModule = 0;
1242#endif
Daniel Dunbar70f92432008-10-23 05:50:47 +00001243}
1244
1245//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +00001246// Main driver
1247//===----------------------------------------------------------------------===//
1248
Ted Kremenekdb094a22007-12-05 18:27:04 +00001249/// CreateASTConsumer - Create the ASTConsumer for the corresponding program
1250/// action. These consumers can operate on both ASTs that are freshly
1251/// parsed from source files as well as those deserialized from Bitcode.
Ted Kremenekfdfc1982007-12-19 22:24:34 +00001252static ASTConsumer* CreateASTConsumer(const std::string& InFile,
Ted Kremeneka1fa3a12007-12-13 00:37:31 +00001253 Diagnostic& Diag, FileManager& FileMgr,
Chris Lattnere66b65c2008-02-06 01:42:25 +00001254 const LangOptions& LangOpts,
Chris Lattner3245a0a2008-04-16 06:11:58 +00001255 Preprocessor *PP,
Ted Kremenek815c78f2008-08-05 18:50:11 +00001256 PreprocessorFactory *PPF) {
Ted Kremenekdb094a22007-12-05 18:27:04 +00001257 switch (ProgAction) {
1258 default:
1259 return NULL;
1260
1261 case ASTPrint:
1262 return CreateASTPrinter();
1263
1264 case ASTDump:
1265 return CreateASTDumper();
1266
1267 case ASTView:
Ted Kremenek6a340832008-03-18 21:19:49 +00001268 return CreateASTViewer();
Zhongxing Xu2d75d6f2009-01-13 01:29:24 +00001269
1270 case PrintDeclContext:
1271 return CreateDeclContextPrinter();
Ted Kremenek6a340832008-03-18 21:19:49 +00001272
1273 case EmitHTML:
Ted Kremenek339b9c22008-04-17 22:31:54 +00001274 return CreateHTMLPrinter(OutputFile, Diag, PP, PPF);
Ted Kremenek902141f2008-07-02 18:23:21 +00001275
Ted Kremenek7cae2f62008-10-23 23:36:29 +00001276 case InheritanceView:
1277 return CreateInheritanceViewer(InheritanceViewCls);
1278
Ted Kremenekdb094a22007-12-05 18:27:04 +00001279 case TestSerialization:
Ted Kremeneke7d07d12008-06-04 15:55:15 +00001280 return CreateSerializationTest(Diag, FileMgr);
Ted Kremenekdb094a22007-12-05 18:27:04 +00001281
Daniel Dunbard69bacc2008-10-21 23:49:24 +00001282 case EmitAssembly:
Ted Kremenekdb094a22007-12-05 18:27:04 +00001283 case EmitLLVM:
Daniel Dunbar70f92432008-10-23 05:50:47 +00001284 case EmitBC: {
1285 BackendAction Act;
1286 if (ProgAction == EmitAssembly) {
1287 Act = Backend_EmitAssembly;
1288 } else if (ProgAction == EmitLLVM) {
1289 Act = Backend_EmitLL;
1290 } else {
1291 Act = Backend_EmitBC;
1292 }
1293 CompileOptions Opts;
1294 InitializeCompileOptions(Opts);
1295 return CreateBackendConsumer(Act, Diag, LangOpts, Opts,
Daniel Dunbard69bacc2008-10-21 23:49:24 +00001296 InFile, OutputFile, GenerateDebugInfo);
Daniel Dunbar70f92432008-10-23 05:50:47 +00001297 }
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +00001298
Ted Kremenek3910c7c2007-12-19 17:25:59 +00001299 case SerializeAST:
Ted Kremeneka1fa3a12007-12-13 00:37:31 +00001300 // FIXME: Allow user to tailor where the file is written.
Ted Kremeneke7d07d12008-06-04 15:55:15 +00001301 return CreateASTSerializer(InFile, OutputFile, Diag);
Ted Kremeneka1fa3a12007-12-13 00:37:31 +00001302
Steve Naroffb29b4272008-04-14 22:03:09 +00001303 case RewriteObjC:
Chris Lattnerc68ab772008-03-22 00:08:40 +00001304 return CreateCodeRewriterTest(InFile, OutputFile, Diag, LangOpts);
Steve Naroff13188952008-09-18 14:10:13 +00001305
1306 case RewriteBlocks:
1307 return CreateBlockRewriter(InFile, OutputFile, Diag, LangOpts);
Ted Kremenekf4381fd2008-07-02 00:03:09 +00001308
1309 case RunAnalysis:
Ted Kremenekf4381fd2008-07-02 00:03:09 +00001310 return CreateAnalysisConsumer(&AnalysisList[0],
1311 &AnalysisList[0]+AnalysisList.size(),
Ted Kremenek4fc82c82008-11-03 23:18:07 +00001312 AnalysisStoreOpt, AnalysisDiagOpt,
Ted Kremenekf4381fd2008-07-02 00:03:09 +00001313 Diag, PP, PPF, LangOpts,
1314 AnalyzeSpecificFunction,
Ted Kremenekf8ce6992008-08-27 22:31:43 +00001315 OutputFile, VisualizeEGDot, VisualizeEGUbi,
Ted Kremenek491918e2009-01-23 20:52:26 +00001316 TrimGraph, AnalyzeAll,
1317 AnalyzerDisplayProgress);
Ted Kremenekdb094a22007-12-05 18:27:04 +00001318 }
1319}
1320
Reid Spencer5f016e22007-07-11 17:01:13 +00001321/// ProcessInputFile - Process a single input file with the specified state.
1322///
Ted Kremenek339b9c22008-04-17 22:31:54 +00001323static void ProcessInputFile(Preprocessor &PP, PreprocessorFactory &PPF,
Ted Kremenek85888962008-10-21 00:54:44 +00001324 const std::string &InFile, ProgActions PA) {
Ted Kremenek7e7e6252008-08-08 02:46:37 +00001325 llvm::OwningPtr<ASTConsumer> Consumer;
Chris Lattnerbd247762007-07-22 06:05:44 +00001326 bool ClearSourceMgr = false;
Ted Kremenekd39bcd82007-09-26 18:39:29 +00001327
Ted Kremenek85888962008-10-21 00:54:44 +00001328 switch (PA) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001329 default:
Ted Kremenek7e7e6252008-08-08 02:46:37 +00001330 Consumer.reset(CreateASTConsumer(InFile, PP.getDiagnostics(),
1331 PP.getFileManager(), PP.getLangOptions(),
1332 &PP, &PPF));
Ted Kremenekdb094a22007-12-05 18:27:04 +00001333
1334 if (!Consumer) {
1335 fprintf(stderr, "Unexpected program action!\n");
Daniel Dunbarb0adbba2008-10-04 23:42:49 +00001336 HadErrors = true;
Ted Kremenekdb094a22007-12-05 18:27:04 +00001337 return;
1338 }
Ted Kremenekfdfc1982007-12-19 22:24:34 +00001339
Ted Kremenekdb094a22007-12-05 18:27:04 +00001340 break;
1341
Chris Lattnerc106c102008-10-12 05:03:36 +00001342 case DumpRawTokens: {
1343 SourceManager &SM = PP.getSourceManager();
Chris Lattnerc106c102008-10-12 05:03:36 +00001344 // Start lexing the specified input file.
Chris Lattner025c3a62009-01-17 07:35:14 +00001345 Lexer RawLex(SM.getMainFileID(), SM, PP.getLangOptions());
Chris Lattnerc106c102008-10-12 05:03:36 +00001346 RawLex.SetKeepWhitespaceMode(true);
1347
1348 Token RawTok;
Chris Lattnerc106c102008-10-12 05:03:36 +00001349 RawLex.LexFromRawLexer(RawTok);
1350 while (RawTok.isNot(tok::eof)) {
1351 PP.DumpToken(RawTok, true);
1352 fprintf(stderr, "\n");
1353 RawLex.LexFromRawLexer(RawTok);
1354 }
1355 ClearSourceMgr = true;
1356 break;
1357 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001358 case DumpTokens: { // Token dump mode.
Chris Lattnerd2177732007-07-20 16:59:19 +00001359 Token Tok;
Chris Lattnerc106c102008-10-12 05:03:36 +00001360 // Start preprocessing the specified input file.
Ted Kremenek95041a22007-12-19 22:51:13 +00001361 PP.EnterMainSourceFile();
Reid Spencer5f016e22007-07-11 17:01:13 +00001362 do {
1363 PP.Lex(Tok);
1364 PP.DumpToken(Tok, true);
1365 fprintf(stderr, "\n");
Chris Lattner057aaf62007-10-09 18:03:42 +00001366 } while (Tok.isNot(tok::eof));
Chris Lattnerbd247762007-07-22 06:05:44 +00001367 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001368 break;
1369 }
1370 case RunPreprocessorOnly: { // Just lex as fast as we can, no output.
Chris Lattnerd2177732007-07-20 16:59:19 +00001371 Token Tok;
Reid Spencer5f016e22007-07-11 17:01:13 +00001372 // Start parsing the specified input file.
Ted Kremenek95041a22007-12-19 22:51:13 +00001373 PP.EnterMainSourceFile();
Reid Spencer5f016e22007-07-11 17:01:13 +00001374 do {
1375 PP.Lex(Tok);
Chris Lattner057aaf62007-10-09 18:03:42 +00001376 } while (Tok.isNot(tok::eof));
Chris Lattnerbd247762007-07-22 06:05:44 +00001377 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001378 break;
1379 }
Ted Kremenek85888962008-10-21 00:54:44 +00001380
1381 case GeneratePCH: {
1382 CacheTokens(PP, OutputFile);
1383 ClearSourceMgr = true;
1384 break;
1385 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001386
1387 case PrintPreprocessedInput: // -E mode.
Chris Lattnere988bc22008-01-27 23:55:11 +00001388 DoPrintPreprocessedInput(PP, OutputFile);
Chris Lattnerbd247762007-07-22 06:05:44 +00001389 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001390 break;
Chris Lattnerb57e3d42008-05-08 06:52:13 +00001391
Reid Spencer5f016e22007-07-11 17:01:13 +00001392 case ParseNoop: // -parse-noop
Daniel Dunbare10b0f22008-10-31 08:56:51 +00001393 ParseFile(PP, new MinimalAction(PP));
Chris Lattnerbd247762007-07-22 06:05:44 +00001394 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001395 break;
1396
1397 case ParsePrintCallbacks:
Daniel Dunbare10b0f22008-10-31 08:56:51 +00001398 ParseFile(PP, CreatePrintParserActionsAction(PP));
Chris Lattnerbd247762007-07-22 06:05:44 +00001399 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001400 break;
Ted Kremenek44579782007-09-25 18:37:20 +00001401
Ted Kremenekd39bcd82007-09-26 18:39:29 +00001402 case ParseSyntaxOnly: // -fsyntax-only
Ted Kremenek7e7e6252008-08-08 02:46:37 +00001403 Consumer.reset(new ASTConsumer());
Ted Kremenek2bf55142007-09-17 20:49:30 +00001404 break;
Chris Lattnerb57e3d42008-05-08 06:52:13 +00001405
1406 case RewriteMacros:
Chris Lattner09510522008-05-09 22:43:24 +00001407 RewriteMacrosInInput(PP, InFile, OutputFile);
Chris Lattnerb57e3d42008-05-08 06:52:13 +00001408 ClearSourceMgr = true;
1409 break;
Chris Lattnerb13c5ee2008-10-12 05:29:20 +00001410
1411 case RewriteTest:
1412 DoRewriteTest(PP, InFile, OutputFile);
1413 ClearSourceMgr = true;
1414 break;
Chris Lattner580980b2007-09-16 19:46:59 +00001415 }
Ted Kremenek46157b52009-01-28 04:29:29 +00001416
1417 if (Consumer) {
1418 TranslationUnit *TU = 0;
1419 if (DisableFree) {
1420 ASTContext *Context = new ASTContext(PP.getLangOptions(),
1421 PP.getSourceManager(),
1422 PP.getTargetInfo(),
1423 PP.getIdentifierTable(),
1424 PP.getSelectorTable(),
1425 /* FreeMemory = */ false);
1426 TU = new TranslationUnit(*Context);
1427 }
1428 ParseAST(PP, Consumer.get(), TU, Stats);
1429 }
Daniel Dunbar879c3ea2008-10-27 22:03:52 +00001430
1431 if (VerifyDiagnostics)
Daniel Dunbar276373d2008-10-27 22:10:13 +00001432 if (CheckDiagnostics(PP))
1433 exit(1);
Chris Lattnere66b65c2008-02-06 01:42:25 +00001434
Reid Spencer5f016e22007-07-11 17:01:13 +00001435 if (Stats) {
Ted Kremenekfdfc1982007-12-19 22:24:34 +00001436 fprintf(stderr, "\nSTATISTICS FOR '%s':\n", InFile.c_str());
Reid Spencer5f016e22007-07-11 17:01:13 +00001437 PP.PrintStats();
1438 PP.getIdentifierTable().PrintStats();
Chris Lattnerdee73592007-12-15 20:48:40 +00001439 PP.getHeaderSearchInfo().PrintStats();
Ted Kremenek1b95a652009-01-09 18:20:21 +00001440 PP.getSourceManager().PrintStats();
Reid Spencer5f016e22007-07-11 17:01:13 +00001441 fprintf(stderr, "\n");
1442 }
Chris Lattnerbd247762007-07-22 06:05:44 +00001443
1444 // For a multi-file compilation, some things are ok with nuking the source
1445 // manager tables, other require stable fileid/macroid's across multiple
1446 // files.
Chris Lattnerdee73592007-12-15 20:48:40 +00001447 if (ClearSourceMgr)
1448 PP.getSourceManager().clearIDTables();
Daniel Dunbard68ba0e2008-11-11 06:35:39 +00001449
1450 if (DisableFree)
1451 Consumer.take();
Reid Spencer5f016e22007-07-11 17:01:13 +00001452}
1453
Ted Kremenek20e97482007-12-12 23:41:08 +00001454static void ProcessSerializedFile(const std::string& InFile, Diagnostic& Diag,
1455 FileManager& FileMgr) {
1456
1457 if (VerifyDiagnostics) {
1458 fprintf(stderr, "-verify does not yet work with serialized ASTs.\n");
1459 exit (1);
1460 }
1461
1462 llvm::sys::Path Filename(InFile);
1463
1464 if (!Filename.isValid()) {
1465 fprintf(stderr, "serialized file '%s' not available.\n",InFile.c_str());
1466 exit (1);
1467 }
1468
Ted Kremenekc1e9dea2008-04-23 16:25:39 +00001469 llvm::OwningPtr<TranslationUnit> TU(ReadASTBitcodeFile(Filename, FileMgr));
Ted Kremenekfe4e0152007-12-13 18:11:11 +00001470
1471 if (!TU) {
1472 fprintf(stderr, "error: file '%s' could not be deserialized\n",
1473 InFile.c_str());
1474 exit (1);
1475 }
1476
Ted Kremenek63ea8632007-12-19 19:27:38 +00001477 // Observe that we use the source file name stored in the deserialized
1478 // translation unit, rather than InFile.
Ted Kremenekee533642007-12-20 19:47:16 +00001479 llvm::OwningPtr<ASTConsumer>
Ted Kremeneke7d07d12008-06-04 15:55:15 +00001480 Consumer(CreateASTConsumer(InFile, Diag, FileMgr, TU->getLangOptions(),
Ted Kremenek815c78f2008-08-05 18:50:11 +00001481 0, 0));
Nico Weber7bfaaae2008-08-10 19:59:06 +00001482
Ted Kremenek20e97482007-12-12 23:41:08 +00001483 if (!Consumer) {
1484 fprintf(stderr, "Unsupported program action with serialized ASTs!\n");
1485 exit (1);
1486 }
Nico Weber7bfaaae2008-08-10 19:59:06 +00001487
Ted Kremenekc1e9dea2008-04-23 16:25:39 +00001488 Consumer->Initialize(TU->getContext());
Nico Weber7bfaaae2008-08-10 19:59:06 +00001489
Chris Lattnere66b65c2008-02-06 01:42:25 +00001490 // FIXME: We need to inform Consumer about completed TagDecls as well.
Ted Kremenek20e97482007-12-12 23:41:08 +00001491 for (TranslationUnit::iterator I=TU->begin(), E=TU->end(); I!=E; ++I)
1492 Consumer->HandleTopLevelDecl(*I);
Ted Kremenek20e97482007-12-12 23:41:08 +00001493}
1494
1495
Reid Spencer5f016e22007-07-11 17:01:13 +00001496static llvm::cl::list<std::string>
1497InputFilenames(llvm::cl::Positional, llvm::cl::desc("<input files>"));
1498
Ted Kremenek20e97482007-12-12 23:41:08 +00001499static bool isSerializedFile(const std::string& InFile) {
1500 if (InFile.size() < 4)
1501 return false;
1502
1503 const char* s = InFile.c_str()+InFile.size()-4;
1504
1505 return s[0] == '.' &&
1506 s[1] == 'a' &&
1507 s[2] == 's' &&
1508 s[3] == 't';
1509}
1510
Reid Spencer5f016e22007-07-11 17:01:13 +00001511
1512int main(int argc, char **argv) {
Chris Lattnerdcaa0962008-03-03 03:16:03 +00001513 llvm::cl::ParseCommandLineOptions(argc, argv, " llvm clang cfe\n");
Reid Spencer5f016e22007-07-11 17:01:13 +00001514 llvm::sys::PrintStackTraceOnErrorSignal();
1515
1516 // If no input was specified, read from stdin.
1517 if (InputFilenames.empty())
1518 InputFilenames.push_back("-");
Ted Kremenek31e703b2007-12-11 23:28:38 +00001519
Reid Spencer5f016e22007-07-11 17:01:13 +00001520 // Create a file manager object to provide access to and cache the filesystem.
1521 FileManager FileMgr;
1522
Ted Kremenek31e703b2007-12-11 23:28:38 +00001523 // Create the diagnostic client for reporting errors or for
1524 // implementing -verify.
Nico Weber7bfaaae2008-08-10 19:59:06 +00001525 DiagnosticClient* TextDiagClient = 0;
Ted Kremenek88f5cde2008-03-27 06:17:42 +00001526
Ted Kremenekb4398aa2008-08-07 17:49:57 +00001527 if (!VerifyDiagnostics) {
1528 // Print diagnostics to stderr by default.
Chris Lattnera03a5b52008-11-19 06:56:25 +00001529 TextDiagClient = new TextDiagnosticPrinter(llvm::errs(),
1530 !NoShowColumn,
Ted Kremenekb4398aa2008-08-07 17:49:57 +00001531 !NoCaretDiagnostics);
1532 } else {
1533 // When checking diagnostics, just buffer them up.
1534 TextDiagClient = new TextDiagnosticBuffer();
1535
1536 if (InputFilenames.size() != 1) {
1537 fprintf(stderr,
1538 "-verify only works on single input files for now.\n");
1539 return 1;
Reid Spencer5f016e22007-07-11 17:01:13 +00001540 }
1541 }
Ted Kremenekb4398aa2008-08-07 17:49:57 +00001542
Reid Spencer5f016e22007-07-11 17:01:13 +00001543 // Configure our handling of diagnostics.
Ted Kremenekb4398aa2008-08-07 17:49:57 +00001544 llvm::OwningPtr<DiagnosticClient> DiagClient(TextDiagClient);
1545 Diagnostic Diags(DiagClient.get());
Ted Kremenek31e703b2007-12-11 23:28:38 +00001546 InitializeDiagnostics(Diags);
1547
Chris Lattner4f037832007-12-05 23:24:17 +00001548 // -I- is a deprecated GCC feature, scan for it and reject it.
1549 for (unsigned i = 0, e = I_dirs.size(); i != e; ++i) {
1550 if (I_dirs[i] == "-") {
Chris Lattner5917fe12008-11-18 05:05:28 +00001551 Diags.Report(FullSourceLoc(), diag::err_pp_I_dash_not_supported);
Chris Lattner4f037832007-12-05 23:24:17 +00001552 I_dirs.erase(I_dirs.begin()+i);
1553 --i;
1554 }
1555 }
Chris Lattner11215192008-03-14 06:12:05 +00001556
1557 // Get information about the target being compiled for.
1558 std::string Triple = CreateTargetTriple();
Ted Kremenek7a08e282008-08-07 18:13:12 +00001559 llvm::OwningPtr<TargetInfo> Target(TargetInfo::CreateTargetInfo(Triple));
1560
Chris Lattner11215192008-03-14 06:12:05 +00001561 if (Target == 0) {
1562 fprintf(stderr, "Sorry, I don't know what target this is: %s\n",
1563 Triple.c_str());
1564 fprintf(stderr, "Please use -triple or -arch.\n");
1565 exit(1);
1566 }
Chris Lattner4f037832007-12-05 23:24:17 +00001567
Daniel Dunbard4270232009-01-20 23:17:32 +00001568 if (!InheritanceViewCls.empty()) // C++ visualization?
Ted Kremenek7cae2f62008-10-23 23:36:29 +00001569 ProgAction = InheritanceView;
Ted Kremenekb4398aa2008-08-07 17:49:57 +00001570
Ted Kremenekc0c03bc2008-06-06 22:42:39 +00001571 llvm::OwningPtr<SourceManager> SourceMgr;
1572
Reid Spencer5f016e22007-07-11 17:01:13 +00001573 for (unsigned i = 0, e = InputFilenames.size(); i != e; ++i) {
Ted Kremenek31e703b2007-12-11 23:28:38 +00001574 const std::string &InFile = InputFilenames[i];
Ted Kremenek31e703b2007-12-11 23:28:38 +00001575
Ted Kremenekb4398aa2008-08-07 17:49:57 +00001576 if (isSerializedFile(InFile)) {
1577 Diags.setClient(TextDiagClient);
Ted Kremenek20e97482007-12-12 23:41:08 +00001578 ProcessSerializedFile(InFile,Diags,FileMgr);
Ted Kremenekb4398aa2008-08-07 17:49:57 +00001579 }
Ted Kremenek20e97482007-12-12 23:41:08 +00001580 else {
1581 /// Create a SourceManager object. This tracks and owns all the file
1582 /// buffers allocated to a translation unit.
Ted Kremenekc0c03bc2008-06-06 22:42:39 +00001583 if (!SourceMgr)
1584 SourceMgr.reset(new SourceManager());
1585 else
1586 SourceMgr->clearIDTables();
Ted Kremenek31e703b2007-12-11 23:28:38 +00001587
Ted Kremenek20e97482007-12-12 23:41:08 +00001588 // Initialize language options, inferring file types from input filenames.
1589 LangOptions LangInfo;
1590 InitializeBaseLanguage();
1591 LangKind LK = GetLanguage(InFile);
Ted Kremenek85888962008-10-21 00:54:44 +00001592 bool PCH = InitializeLangOptions(LangInfo, LK);
Ted Kremenek01d9dbf2008-04-29 04:37:03 +00001593 InitializeGCMode(LangInfo);
Chris Lattner8fc4dfb2008-12-04 22:54:33 +00001594 InitializeLanguageStandard(LangInfo, LK, Target.get());
Ted Kremenek85888962008-10-21 00:54:44 +00001595
Ted Kremenek20e97482007-12-12 23:41:08 +00001596 // Process the -I options and set them in the HeaderInfo.
1597 HeaderSearch HeaderInfo(FileMgr);
Ted Kremenekc68ecb52008-06-06 01:47:30 +00001598
Chris Lattnerdcaa0962008-03-03 03:16:03 +00001599 InitializeIncludePaths(argv[0], HeaderInfo, FileMgr, LangInfo);
Ted Kremenek20e97482007-12-12 23:41:08 +00001600
Ted Kremenek20e97482007-12-12 23:41:08 +00001601 // Set up the preprocessor with these options.
Ted Kremenek339b9c22008-04-17 22:31:54 +00001602 DriverPreprocessorFactory PPFactory(InFile, Diags, LangInfo, *Target,
Ted Kremenekc0c03bc2008-06-06 22:42:39 +00001603 *SourceMgr.get(), HeaderInfo);
Ted Kremenek20e97482007-12-12 23:41:08 +00001604
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001605 llvm::OwningPtr<Preprocessor> PP(PPFactory.CreatePreprocessor());
1606
Ted Kremenek339b9c22008-04-17 22:31:54 +00001607 if (!PP)
Ted Kremenek76edd0e2007-12-19 22:29:55 +00001608 continue;
Ted Kremenekb4398aa2008-08-07 17:49:57 +00001609
1610 // Create the HTMLDiagnosticsClient if we are using one. Otherwise,
1611 // always reset to using TextDiagClient.
1612 llvm::OwningPtr<DiagnosticClient> TmpClient;
Ted Kremenek76edd0e2007-12-19 22:29:55 +00001613
Ted Kremenekb4398aa2008-08-07 17:49:57 +00001614 if (!HTMLDiag.empty()) {
1615 TmpClient.reset(CreateHTMLDiagnosticClient(HTMLDiag, PP.get(),
1616 &PPFactory));
1617 Diags.setClient(TmpClient.get());
1618 }
1619 else
1620 Diags.setClient(TextDiagClient);
1621
1622 // Process the source file.
Ted Kremenek85888962008-10-21 00:54:44 +00001623 ProcessInputFile(*PP, PPFactory, InFile, PCH ? GeneratePCH : ProgAction);
1624
Ted Kremenekc0c03bc2008-06-06 22:42:39 +00001625 HeaderInfo.ClearFileInfo();
Ted Kremenek20e97482007-12-12 23:41:08 +00001626 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001627 }
Chris Lattner11215192008-03-14 06:12:05 +00001628
Mike Stump007f2a92009-01-28 02:43:35 +00001629 if (Verbose)
1630 fprintf(stderr, "clang version 1.0 based upon " PACKAGE_STRING
1631 " hosted on " LLVM_HOSTTRIPLE "\n");
1632
Ted Kremenek7a08e282008-08-07 18:13:12 +00001633 if (unsigned NumDiagnostics = Diags.getNumDiagnostics())
Reid Spencer5f016e22007-07-11 17:01:13 +00001634 fprintf(stderr, "%d diagnostic%s generated.\n", NumDiagnostics,
1635 (NumDiagnostics == 1 ? "" : "s"));
1636
1637 if (Stats) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001638 FileMgr.PrintStats();
1639 fprintf(stderr, "\n");
1640 }
1641
Daniel Dunbar276373d2008-10-27 22:10:13 +00001642 // If verifying diagnostics and we reached here, all is well.
1643 if (VerifyDiagnostics)
1644 return 0;
1645
Daniel Dunbar524b86f2008-10-28 00:38:08 +00001646 // Managed static deconstruction. Useful for making things like
1647 // -time-passes usable.
1648 llvm::llvm_shutdown();
1649
Daniel Dunbarb0adbba2008-10-04 23:42:49 +00001650 return HadErrors || (Diags.getNumErrors() != 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00001651}