blob: 77fb3c8f01701178653250a8120858f26b823b85 [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"
Ted Kremenek88f5cde2008-03-27 06:17:42 +000032#include "clang/Analysis/PathDiagnostic.h"
Daniel Dunbare91593e2008-08-11 04:54:23 +000033#include "clang/AST/Decl.h"
Ted Kremenek77cda502007-12-18 21:34:28 +000034#include "clang/AST/TranslationUnit.h"
Chris Lattner8ee3c032008-02-06 02:01:47 +000035#include "clang/CodeGen/ModuleBuilder.h"
Chris Lattnere91c1342008-02-06 00:23:21 +000036#include "clang/Sema/ParseAST.h"
Chris Lattner556beb72007-09-15 22:56:56 +000037#include "clang/AST/ASTConsumer.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000038#include "clang/Parse/Parser.h"
39#include "clang/Lex/HeaderSearch.h"
40#include "clang/Basic/FileManager.h"
41#include "clang/Basic/SourceManager.h"
42#include "clang/Basic/TargetInfo.h"
Chris Lattnerba0f25f2008-09-30 20:16:56 +000043#include "llvm/ADT/OwningPtr.h"
Chris Lattner8f3dab82007-12-15 23:20:07 +000044#include "llvm/ADT/SmallPtrSet.h"
Chris Lattnerba0f25f2008-09-30 20:16:56 +000045#include "llvm/ADT/StringExtras.h"
46#include "llvm/Config/config.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000047#include "llvm/Support/CommandLine.h"
Daniel Dunbar524b86f2008-10-28 00:38:08 +000048#include "llvm/Support/ManagedStatic.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000049#include "llvm/Support/MemoryBuffer.h"
Zhongxing Xu20922362008-11-26 05:23:17 +000050#include "llvm/Support/PluginLoader.h"
Daniel Dunbare553a722008-10-02 01:21:33 +000051#include "llvm/System/Host.h"
Chris Lattnerdcaa0962008-03-03 03:16:03 +000052#include "llvm/System/Path.h"
Chris Lattnerba0f25f2008-09-30 20:16:56 +000053#include "llvm/System/Signals.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000054using namespace clang;
55
56//===----------------------------------------------------------------------===//
57// Global options.
58//===----------------------------------------------------------------------===//
59
Daniel Dunbard3db4012008-10-16 16:54:18 +000060static bool HadErrors = false;
Daniel Dunbarb0adbba2008-10-04 23:42:49 +000061
Reid Spencer5f016e22007-07-11 17:01:13 +000062static llvm::cl::opt<bool>
63Verbose("v", llvm::cl::desc("Enable verbose output"));
64static llvm::cl::opt<bool>
Nate Begemanaabbb122007-12-30 01:38:50 +000065Stats("print-stats",
66 llvm::cl::desc("Print performance metrics and statistics"));
Daniel Dunbard3db4012008-10-16 16:54:18 +000067static llvm::cl::opt<bool>
68DisableFree("disable-free",
69 llvm::cl::desc("Disable freeing of memory on exit"),
70 llvm::cl::init(false));
Reid Spencer5f016e22007-07-11 17:01:13 +000071
72enum ProgActions {
Steve Naroffb29b4272008-04-14 22:03:09 +000073 RewriteObjC, // ObjC->C Rewriter.
Steve Naroff13188952008-09-18 14:10:13 +000074 RewriteBlocks, // ObjC->C Rewriter for Blocks.
Chris Lattnerb57e3d42008-05-08 06:52:13 +000075 RewriteMacros, // Expand macros but not #includes.
Chris Lattnerb13c5ee2008-10-12 05:29:20 +000076 RewriteTest, // Rewriter playground
Ted Kremenek13e479b2008-03-19 07:53:42 +000077 HTMLTest, // HTML displayer testing stuff.
Daniel Dunbard69bacc2008-10-21 23:49:24 +000078 EmitAssembly, // Emit a .s file.
Reid Spencer5f016e22007-07-11 17:01:13 +000079 EmitLLVM, // Emit a .ll file.
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +000080 EmitBC, // Emit a .bc file.
Ted Kremeneka1fa3a12007-12-13 00:37:31 +000081 SerializeAST, // Emit a .ast file.
Ted Kremenek6a340832008-03-18 21:19:49 +000082 EmitHTML, // Translate input source into HTML.
Chris Lattner3b427b32007-10-11 00:18:28 +000083 ASTPrint, // Parse ASTs and print them.
84 ASTDump, // Parse ASTs and dump them.
85 ASTView, // Parse ASTs and view them in Graphviz.
Ted Kremenekbfa82c42007-10-16 23:37:27 +000086 TestSerialization, // Run experimental serialization code.
Reid Spencer5f016e22007-07-11 17:01:13 +000087 ParsePrintCallbacks, // Parse and print each callback.
88 ParseSyntaxOnly, // Parse and perform semantic analysis.
89 ParseNoop, // Parse with noop callbacks.
90 RunPreprocessorOnly, // Just lex, no output.
91 PrintPreprocessedInput, // -E mode.
Chris Lattnerc106c102008-10-12 05:03:36 +000092 DumpTokens, // Dump out preprocessed tokens.
93 DumpRawTokens, // Dump out raw tokens.
Ted Kremenek85888962008-10-21 00:54:44 +000094 RunAnalysis, // Run one or more source code analyses.
Ted Kremenek7cae2f62008-10-23 23:36:29 +000095 GeneratePCH, // Generate precompiled header.
96 InheritanceView // View C++ inheritance for a specified class.
Reid Spencer5f016e22007-07-11 17:01:13 +000097};
98
99static llvm::cl::opt<ProgActions>
100ProgAction(llvm::cl::desc("Choose output type:"), llvm::cl::ZeroOrMore,
101 llvm::cl::init(ParseSyntaxOnly),
102 llvm::cl::values(
103 clEnumValN(RunPreprocessorOnly, "Eonly",
104 "Just run preprocessor, no output (for timings)"),
105 clEnumValN(PrintPreprocessedInput, "E",
106 "Run preprocessor, emit preprocessed file"),
Chris Lattnerc106c102008-10-12 05:03:36 +0000107 clEnumValN(DumpRawTokens, "dump-raw-tokens",
108 "Lex file in raw mode and dump raw tokens"),
109 clEnumValN(DumpTokens, "dump-tokens",
Reid Spencer5f016e22007-07-11 17:01:13 +0000110 "Run preprocessor, dump internal rep of tokens"),
111 clEnumValN(ParseNoop, "parse-noop",
112 "Run parser with noop callbacks (for timings)"),
113 clEnumValN(ParseSyntaxOnly, "fsyntax-only",
114 "Run parser and perform semantic analysis"),
115 clEnumValN(ParsePrintCallbacks, "parse-print-callbacks",
116 "Run parser and print each callback invoked"),
Ted Kremenek6a340832008-03-18 21:19:49 +0000117 clEnumValN(EmitHTML, "emit-html",
118 "Output input source as HTML"),
Chris Lattner3b427b32007-10-11 00:18:28 +0000119 clEnumValN(ASTPrint, "ast-print",
120 "Build ASTs and then pretty-print them"),
121 clEnumValN(ASTDump, "ast-dump",
122 "Build ASTs and then debug dump them"),
Chris Lattnerea254db2007-10-11 00:37:43 +0000123 clEnumValN(ASTView, "ast-view",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000124 "Build ASTs and view them with GraphViz"),
Ted Kremenekbfa82c42007-10-16 23:37:27 +0000125 clEnumValN(TestSerialization, "test-pickling",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000126 "Run prototype serialization code"),
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000127 clEnumValN(EmitAssembly, "S",
128 "Emit native assembly code"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000129 clEnumValN(EmitLLVM, "emit-llvm",
Ted Kremenek27b07c52007-09-06 21:26:58 +0000130 "Build ASTs then convert to LLVM, emit .ll file"),
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +0000131 clEnumValN(EmitBC, "emit-llvm-bc",
132 "Build ASTs then convert to LLVM, emit .bc file"),
Ted Kremenekccc76472007-12-19 19:47:59 +0000133 clEnumValN(SerializeAST, "serialize",
Ted Kremeneka1fa3a12007-12-13 00:37:31 +0000134 "Build ASTs and emit .ast file"),
Chris Lattnerb13c5ee2008-10-12 05:29:20 +0000135 clEnumValN(RewriteTest, "rewrite-test",
136 "Rewriter playground"),
Steve Naroffb29b4272008-04-14 22:03:09 +0000137 clEnumValN(RewriteObjC, "rewrite-objc",
Chris Lattnerb57e3d42008-05-08 06:52:13 +0000138 "Rewrite ObjC into C (code rewriter example)"),
139 clEnumValN(RewriteMacros, "rewrite-macros",
140 "Expand macros without full preprocessing"),
Steve Naroff13188952008-09-18 14:10:13 +0000141 clEnumValN(RewriteBlocks, "rewrite-blocks",
142 "Rewrite Blocks to C"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000143 clEnumValEnd));
144
Ted Kremenekccc76472007-12-19 19:47:59 +0000145
146static llvm::cl::opt<std::string>
147OutputFile("o",
Ted Kremenek50b56412007-12-19 19:50:41 +0000148 llvm::cl::value_desc("path"),
Ted Kremenekccc76472007-12-19 19:47:59 +0000149 llvm::cl::desc("Specify output file (for --serialize, this is a directory)"));
Ted Kremenek55af98c2008-04-14 18:40:58 +0000150
151//===----------------------------------------------------------------------===//
Sanjiv Guptae8b9f5b2008-05-08 08:54:20 +0000152// Code Generator Options
153//===----------------------------------------------------------------------===//
154static llvm::cl::opt<bool>
155GenerateDebugInfo("g",
156 llvm::cl::desc("Generate source level debug information"));
157
Ted Kremenekc2e72992008-12-02 19:57:31 +0000158
159//===----------------------------------------------------------------------===//
160// PTH.
161//===----------------------------------------------------------------------===//
162
163static llvm::cl::opt<std::string>
164TokenCache("token-cache", llvm::cl::value_desc("path"),
165 llvm::cl::desc("Use specified token cache file"));
166
Sanjiv Guptae8b9f5b2008-05-08 08:54:20 +0000167//===----------------------------------------------------------------------===//
Ted Kremenek55af98c2008-04-14 18:40:58 +0000168// Diagnostic Options
169//===----------------------------------------------------------------------===//
170
Ted Kremenek41193e42007-09-26 19:42:19 +0000171static llvm::cl::opt<bool>
172VerifyDiagnostics("verify",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000173 llvm::cl::desc("Verify emitted diagnostics and warnings"));
Ted Kremenek41193e42007-09-26 19:42:19 +0000174
Ted Kremenek88f5cde2008-03-27 06:17:42 +0000175static llvm::cl::opt<std::string>
176HTMLDiag("html-diags",
177 llvm::cl::desc("Generate HTML to report diagnostics"),
178 llvm::cl::value_desc("HTML directory"));
179
Nico Weberfd54ebc2008-08-05 23:33:20 +0000180static llvm::cl::opt<bool>
181NoShowColumn("fno-show-column",
182 llvm::cl::desc("Do not include column number on diagnostics"));
183
184static llvm::cl::opt<bool>
185NoCaretDiagnostics("fno-caret-diagnostics",
186 llvm::cl::desc("Do not include source line and caret with"
187 " diagnostics"));
188
189
Reid Spencer5f016e22007-07-11 17:01:13 +0000190//===----------------------------------------------------------------------===//
Ted Kremenek7cae2f62008-10-23 23:36:29 +0000191// C++ Visualization.
192//===----------------------------------------------------------------------===//
193
194static llvm::cl::opt<std::string>
195InheritanceViewCls("cxx-inheritance-view",
196 llvm::cl::value_desc("class name"),
197 llvm::cl::desc("View C++ inhertance for a specified class"));
198
199//===----------------------------------------------------------------------===//
200// Analyzer Options.
Ted Kremenek55af98c2008-04-14 18:40:58 +0000201//===----------------------------------------------------------------------===//
202
203static llvm::cl::opt<bool>
Ted Kremenekf8ce6992008-08-27 22:31:43 +0000204VisualizeEGDot("analyzer-viz-egraph-graphviz",
205 llvm::cl::desc("Display exploded graph using GraphViz"));
Ted Kremenek55af98c2008-04-14 18:40:58 +0000206
207static llvm::cl::opt<bool>
Ted Kremenekf8ce6992008-08-27 22:31:43 +0000208VisualizeEGUbi("analyzer-viz-egraph-ubigraph",
209 llvm::cl::desc("Display exploded graph using Ubigraph"));
210
211static llvm::cl::opt<bool>
212AnalyzeAll("analyzer-opt-analyze-headers",
Ted Kremenek55af98c2008-04-14 18:40:58 +0000213 llvm::cl::desc("Force the static analyzer to analyze "
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000214 "functions defined in header files"));
Ted Kremenek55af98c2008-04-14 18:40:58 +0000215
Ted Kremenekf4381fd2008-07-02 00:03:09 +0000216static llvm::cl::list<Analyses>
Ted Kremenek95c7b002008-10-24 01:04:59 +0000217AnalysisList(llvm::cl::desc("SCA Checks/Analyses:"),
Ted Kremenekf4381fd2008-07-02 00:03:09 +0000218llvm::cl::values(
Ted Kremenekf7f3c202008-07-15 00:46:02 +0000219#define ANALYSIS(NAME, CMDFLAG, DESC, SCOPE)\
Ted Kremenekfb9a48c2008-07-14 23:41:13 +0000220clEnumValN(NAME, CMDFLAG, DESC),
221#include "Analyses.def"
222clEnumValEnd));
Ted Kremenekf4381fd2008-07-02 00:03:09 +0000223
Ted Kremenek95c7b002008-10-24 01:04:59 +0000224static llvm::cl::opt<AnalysisStores>
225AnalysisStoreOpt(llvm::cl::desc("SCA Low-Level Options (Store):"),
226 llvm::cl::init(BasicStoreModel),
227 llvm::cl::values(
228#define ANALYSIS_STORE(NAME, CMDFLAG, DESC)\
229clEnumValN(NAME##Model, "analyzer-store-" CMDFLAG, DESC),
230#include "Analyses.def"
231clEnumValEnd));
232
Ted Kremenek4fc82c82008-11-03 23:18:07 +0000233static llvm::cl::opt<AnalysisDiagClients>
234AnalysisDiagOpt(llvm::cl::desc("SCA Output Options:"),
235 llvm::cl::init(PD_HTML),
236 llvm::cl::values(
237#define ANALYSIS_DIAGNOSTICS(NAME, CMDFLAG, DESC, CREATFN)\
238clEnumValN(PD_##NAME, "analyzer-output-" CMDFLAG, DESC),
239#include "Analyses.def"
240clEnumValEnd));
241
Ted Kremenek55af98c2008-04-14 18:40:58 +0000242//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +0000243// Language Options
244//===----------------------------------------------------------------------===//
245
246enum LangKind {
247 langkind_unspecified,
248 langkind_c,
249 langkind_c_cpp,
Chris Lattnera778d7d2008-10-22 17:29:21 +0000250 langkind_asm_cpp,
Ted Kremenek85888962008-10-21 00:54:44 +0000251 langkind_c_pch,
Reid Spencer5f016e22007-07-11 17:01:13 +0000252 langkind_cxx,
253 langkind_cxx_cpp,
254 langkind_objc,
255 langkind_objc_cpp,
Ted Kremenek85888962008-10-21 00:54:44 +0000256 langkind_objc_pch,
Reid Spencer5f016e22007-07-11 17:01:13 +0000257 langkind_objcxx,
258 langkind_objcxx_cpp
259};
260
261/* TODO: GCC also accepts:
262 c-header c++-header objective-c-header objective-c++-header
Chris Lattnera778d7d2008-10-22 17:29:21 +0000263 assembler
Reid Spencer5f016e22007-07-11 17:01:13 +0000264 ada, f77*, ratfor (!), f95, java, treelang
265 */
266static llvm::cl::opt<LangKind>
267BaseLang("x", llvm::cl::desc("Base language to compile"),
268 llvm::cl::init(langkind_unspecified),
269 llvm::cl::values(clEnumValN(langkind_c, "c", "C"),
270 clEnumValN(langkind_cxx, "c++", "C++"),
271 clEnumValN(langkind_objc, "objective-c", "Objective C"),
272 clEnumValN(langkind_objcxx,"objective-c++","Objective C++"),
273 clEnumValN(langkind_c_cpp, "c-cpp-output",
274 "Preprocessed C"),
Chris Lattnera778d7d2008-10-22 17:29:21 +0000275 clEnumValN(langkind_asm_cpp, "assembler-with-cpp",
276 "Preprocessed asm"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000277 clEnumValN(langkind_cxx_cpp, "c++-cpp-output",
Ted Kremenek85888962008-10-21 00:54:44 +0000278 "Preprocessed C++"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000279 clEnumValN(langkind_objc_cpp, "objective-c-cpp-output",
280 "Preprocessed Objective C"),
281 clEnumValN(langkind_objcxx_cpp,"objective-c++-cpp-output",
282 "Preprocessed Objective C++"),
Ted Kremenek85888962008-10-21 00:54:44 +0000283 clEnumValN(langkind_c_pch,"c-header",
284 "Precompiled C header"),
285 clEnumValN(langkind_objc_pch, "objective-c-header",
286 "Precompiled Objective C header"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000287 clEnumValEnd));
288
289static llvm::cl::opt<bool>
290LangObjC("ObjC", llvm::cl::desc("Set base language to Objective-C"),
291 llvm::cl::Hidden);
292static llvm::cl::opt<bool>
293LangObjCXX("ObjC++", llvm::cl::desc("Set base language to Objective-C++"),
294 llvm::cl::Hidden);
295
Ted Kremenek8904f152007-12-05 23:49:08 +0000296/// InitializeBaseLanguage - Handle the -x foo options.
297static void InitializeBaseLanguage() {
298 if (LangObjC)
299 BaseLang = langkind_objc;
300 else if (LangObjCXX)
301 BaseLang = langkind_objcxx;
302}
303
304static LangKind GetLanguage(const std::string &Filename) {
305 if (BaseLang != langkind_unspecified)
306 return BaseLang;
307
308 std::string::size_type DotPos = Filename.rfind('.');
309
310 if (DotPos == std::string::npos) {
311 BaseLang = langkind_c; // Default to C if no extension.
Chris Lattner9b2f6c42008-01-04 19:12:28 +0000312 return langkind_c;
Reid Spencer5f016e22007-07-11 17:01:13 +0000313 }
314
Ted Kremenek8904f152007-12-05 23:49:08 +0000315 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
316 // C header: .h
317 // C++ header: .hh or .H;
318 // assembler no preprocessing: .s
319 // assembler: .S
320 if (Ext == "c")
321 return langkind_c;
Chris Lattner1b450b02008-10-28 20:33:42 +0000322 else if (Ext == "S")
Chris Lattnera778d7d2008-10-22 17:29:21 +0000323 return langkind_asm_cpp;
Ted Kremenek8904f152007-12-05 23:49:08 +0000324 else if (Ext == "i")
325 return langkind_c_cpp;
326 else if (Ext == "ii")
327 return langkind_cxx_cpp;
328 else if (Ext == "m")
329 return langkind_objc;
330 else if (Ext == "mi")
331 return langkind_objc_cpp;
332 else if (Ext == "mm" || Ext == "M")
333 return langkind_objcxx;
334 else if (Ext == "mii")
335 return langkind_objcxx_cpp;
336 else if (Ext == "C" || Ext == "cc" || Ext == "cpp" || Ext == "CPP" ||
337 Ext == "c++" || Ext == "cp" || Ext == "cxx")
338 return langkind_cxx;
339 else
340 return langkind_c;
341}
342
343
Ted Kremenek85888962008-10-21 00:54:44 +0000344static void InitializeCOptions(LangOptions &Options) {
345 // Do nothing.
346}
347
348static void InitializeObjCOptions(LangOptions &Options) {
349 Options.ObjC1 = Options.ObjC2 = 1;
350}
351
352
353static bool InitializeLangOptions(LangOptions &Options, LangKind LK){
Reid Spencer5f016e22007-07-11 17:01:13 +0000354 // FIXME: implement -fpreprocessed mode.
355 bool NoPreprocess = false;
Ted Kremenek85888962008-10-21 00:54:44 +0000356 bool PCH = false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000357
Ted Kremenek8904f152007-12-05 23:49:08 +0000358 switch (LK) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000359 default: assert(0 && "Unknown language kind!");
Ted Kremenek85888962008-10-21 00:54:44 +0000360 case langkind_c_pch:
361 InitializeCOptions(Options);
362 PCH = true;
363 break;
Chris Lattnera778d7d2008-10-22 17:29:21 +0000364 case langkind_asm_cpp:
Daniel Dunbarc1571452008-12-01 18:55:22 +0000365 Options.AsmPreprocessor = 1;
Chris Lattnera778d7d2008-10-22 17:29:21 +0000366 // FALLTHROUGH
Reid Spencer5f016e22007-07-11 17:01:13 +0000367 case langkind_c_cpp:
368 NoPreprocess = true;
369 // FALLTHROUGH
370 case langkind_c:
Ted Kremenek85888962008-10-21 00:54:44 +0000371 InitializeCOptions(Options);
Reid Spencer5f016e22007-07-11 17:01:13 +0000372 break;
373 case langkind_cxx_cpp:
374 NoPreprocess = true;
375 // FALLTHROUGH
376 case langkind_cxx:
377 Options.CPlusPlus = 1;
378 break;
Ted Kremenek85888962008-10-21 00:54:44 +0000379 case langkind_objc_pch:
380 InitializeObjCOptions(Options);
381 PCH = true;
382 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000383 case langkind_objc_cpp:
384 NoPreprocess = true;
385 // FALLTHROUGH
386 case langkind_objc:
Ted Kremenek85888962008-10-21 00:54:44 +0000387 InitializeObjCOptions(Options);
Reid Spencer5f016e22007-07-11 17:01:13 +0000388 break;
389 case langkind_objcxx_cpp:
390 NoPreprocess = true;
391 // FALLTHROUGH
392 case langkind_objcxx:
393 Options.ObjC1 = Options.ObjC2 = 1;
394 Options.CPlusPlus = 1;
395 break;
396 }
Ted Kremenek85888962008-10-21 00:54:44 +0000397
398 return PCH;
Reid Spencer5f016e22007-07-11 17:01:13 +0000399}
400
401/// LangStds - Language standards we support.
402enum LangStds {
403 lang_unspecified,
404 lang_c89, lang_c94, lang_c99,
Ted Kremenekea644d82008-09-03 21:22:16 +0000405 lang_gnu_START,
406 lang_gnu89 = lang_gnu_START, lang_gnu99,
Chris Lattnerd4b80f12007-07-16 04:18:29 +0000407 lang_cxx98, lang_gnucxx98,
408 lang_cxx0x, lang_gnucxx0x
Reid Spencer5f016e22007-07-11 17:01:13 +0000409};
410
411static llvm::cl::opt<LangStds>
412LangStd("std", llvm::cl::desc("Language standard to compile for"),
413 llvm::cl::init(lang_unspecified),
414 llvm::cl::values(clEnumValN(lang_c89, "c89", "ISO C 1990"),
415 clEnumValN(lang_c89, "c90", "ISO C 1990"),
416 clEnumValN(lang_c89, "iso9899:1990", "ISO C 1990"),
417 clEnumValN(lang_c94, "iso9899:199409",
418 "ISO C 1990 with amendment 1"),
419 clEnumValN(lang_c99, "c99", "ISO C 1999"),
420// clEnumValN(lang_c99, "c9x", "ISO C 1999"),
421 clEnumValN(lang_c99, "iso9899:1999", "ISO C 1999"),
422// clEnumValN(lang_c99, "iso9899:199x", "ISO C 1999"),
423 clEnumValN(lang_gnu89, "gnu89",
424 "ISO C 1990 with GNU extensions (default for C)"),
425 clEnumValN(lang_gnu99, "gnu99",
426 "ISO C 1999 with GNU extensions"),
427 clEnumValN(lang_gnu99, "gnu9x",
428 "ISO C 1999 with GNU extensions"),
429 clEnumValN(lang_cxx98, "c++98",
430 "ISO C++ 1998 with amendments"),
431 clEnumValN(lang_gnucxx98, "gnu++98",
432 "ISO C++ 1998 with amendments and GNU "
433 "extensions (default for C++)"),
Chris Lattnerd4b80f12007-07-16 04:18:29 +0000434 clEnumValN(lang_cxx0x, "c++0x",
435 "Upcoming ISO C++ 200x with amendments"),
436 clEnumValN(lang_gnucxx0x, "gnu++0x",
437 "Upcoming ISO C++ 200x with amendments and GNU "
438 "extensions (default for C++)"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000439 clEnumValEnd));
440
441static llvm::cl::opt<bool>
442NoOperatorNames("fno-operator-names",
443 llvm::cl::desc("Do not treat C++ operator name keywords as "
444 "synonyms for operators"));
445
Anders Carlssonee98ac52007-10-15 02:50:23 +0000446static llvm::cl::opt<bool>
447PascalStrings("fpascal-strings",
448 llvm::cl::desc("Recognize and construct Pascal-style "
449 "string literals"));
Steve Naroffd62701b2008-02-07 03:50:06 +0000450
451static llvm::cl::opt<bool>
452MSExtensions("fms-extensions",
453 llvm::cl::desc("Accept some non-standard constructs used in "
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000454 "Microsoft header files "));
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000455
456static llvm::cl::opt<bool>
457WritableStrings("fwritable-strings",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000458 llvm::cl::desc("Store string literals as writable data"));
Anders Carlsson695dbb62007-11-30 04:21:22 +0000459
460static llvm::cl::opt<bool>
461LaxVectorConversions("flax-vector-conversions",
462 llvm::cl::desc("Allow implicit conversions between vectors"
463 " with a different number of elements or "
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000464 "different element types"));
Chris Lattnerae0ee032008-12-04 23:20:07 +0000465static llvm::cl::opt<bool>
466EnableBlocks("fblocks", llvm::cl::desc("enable the 'blocks' language feature"));
467
Ted Kremenek01d9dbf2008-04-29 04:37:03 +0000468
Daniel Dunbar6379a7a2008-08-11 17:36:14 +0000469// FIXME: This (and all GCC -f options) really come in -f... and
470// -fno-... forms, and additionally support automagic behavior when
471// they are not defined. For example, -fexceptions defaults to on or
472// off depending on the language. We should support this behavior in
473// some form (perhaps just add a facility for distinguishing when an
474// has its default value from when it has been set to its default
475// value).
476static llvm::cl::opt<bool>
477Exceptions("fexceptions",
478 llvm::cl::desc("Enable support for exception handling."));
479
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000480static llvm::cl::opt<bool>
481GNURuntime("fgnu-runtime",
Ted Kremenek85888962008-10-21 00:54:44 +0000482 llvm::cl::desc("Generate output compatible with the standard GNU "
483 "Objective-C runtime."));
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000484
485static llvm::cl::opt<bool>
486NeXTRuntime("fnext-runtime",
Ted Kremenek85888962008-10-21 00:54:44 +0000487 llvm::cl::desc("Generate output compatible with the NeXT "
488 "runtime."));
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000489
Ted Kremenekea644d82008-09-03 21:22:16 +0000490
491
492static llvm::cl::opt<bool>
493Trigraphs("trigraphs", llvm::cl::desc("Process trigraph sequences."));
494
495static llvm::cl::opt<bool>
496Ansi("ansi", llvm::cl::desc("Equivalent to specifying -std=c89."));
497
Reid Spencer5f016e22007-07-11 17:01:13 +0000498// FIXME: add:
Reid Spencer5f016e22007-07-11 17:01:13 +0000499// -fdollars-in-identifiers
Daniel Dunbardcb4a1a2008-08-23 08:43:39 +0000500static void InitializeLanguageStandard(LangOptions &Options, LangKind LK,
501 TargetInfo *Target) {
Chris Lattner8fc4dfb2008-12-04 22:54:33 +0000502 // Allow the target to set the default the langauge options as it sees fit.
503 Target->getDefaultLangOptions(Options);
Ted Kremenekea644d82008-09-03 21:22:16 +0000504
505 if (Ansi) // "The -ansi option is equivalent to -std=c89."
506 LangStd = lang_c89;
507
Reid Spencer5f016e22007-07-11 17:01:13 +0000508 if (LangStd == lang_unspecified) {
509 // Based on the base language, pick one.
Ted Kremenek8904f152007-12-05 23:49:08 +0000510 switch (LK) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000511 default: assert(0 && "Unknown base language");
512 case langkind_c:
Chris Lattnera778d7d2008-10-22 17:29:21 +0000513 case langkind_asm_cpp:
Reid Spencer5f016e22007-07-11 17:01:13 +0000514 case langkind_c_cpp:
Ted Kremenek85888962008-10-21 00:54:44 +0000515 case langkind_c_pch:
Reid Spencer5f016e22007-07-11 17:01:13 +0000516 case langkind_objc:
517 case langkind_objc_cpp:
Ted Kremenek85888962008-10-21 00:54:44 +0000518 case langkind_objc_pch:
Reid Spencer5f016e22007-07-11 17:01:13 +0000519 LangStd = lang_gnu99;
520 break;
521 case langkind_cxx:
522 case langkind_cxx_cpp:
523 case langkind_objcxx:
524 case langkind_objcxx_cpp:
525 LangStd = lang_gnucxx98;
526 break;
527 }
528 }
529
530 switch (LangStd) {
531 default: assert(0 && "Unknown language standard!");
532
533 // Fall through from newer standards to older ones. This isn't really right.
534 // FIXME: Enable specifically the right features based on the language stds.
Chris Lattnerd4b80f12007-07-16 04:18:29 +0000535 case lang_gnucxx0x:
536 case lang_cxx0x:
537 Options.CPlusPlus0x = 1;
538 // FALL THROUGH
Reid Spencer5f016e22007-07-11 17:01:13 +0000539 case lang_gnucxx98:
540 case lang_cxx98:
541 Options.CPlusPlus = 1;
542 Options.CXXOperatorNames = !NoOperatorNames;
Nate Begeman8aebcb72007-11-15 07:30:50 +0000543 Options.Boolean = 1;
Reid Spencer5f016e22007-07-11 17:01:13 +0000544 // FALL THROUGH.
545 case lang_gnu99:
546 case lang_c99:
Reid Spencer5f016e22007-07-11 17:01:13 +0000547 Options.C99 = 1;
548 Options.HexFloats = 1;
549 // FALL THROUGH.
550 case lang_gnu89:
551 Options.BCPLComment = 1; // Only for C99/C++.
552 // FALL THROUGH.
553 case lang_c94:
Chris Lattner3426b9b2008-02-25 04:01:39 +0000554 Options.Digraphs = 1; // C94, C99, C++.
555 // FALL THROUGH.
Reid Spencer5f016e22007-07-11 17:01:13 +0000556 case lang_c89:
557 break;
558 }
Argyrios Kyrtzidisd1465522008-09-11 04:21:06 +0000559
560 if (Options.CPlusPlus) {
561 Options.C99 = 0;
562 Options.HexFloats = (LangStd == lang_gnucxx98 || LangStd==lang_gnucxx0x);
563 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000564
Chris Lattnerd658b562008-04-05 06:32:51 +0000565 if (LangStd == lang_c89 || LangStd == lang_c94 || LangStd == lang_gnu89)
566 Options.ImplicitInt = 1;
567 else
568 Options.ImplicitInt = 0;
Ted Kremenekea644d82008-09-03 21:22:16 +0000569
570 // Mimicing gcc's behavior, trigraphs are only enabled if -trigraphs or -ansi
571 // is specified, or -std is set to a conforming mode.
Chris Lattner802db9b2008-12-05 00:10:44 +0000572 Options.Trigraphs = LangStd < lang_gnu_START;
573 if (Trigraphs.getPosition())
574 Options.Trigraphs = Trigraphs; // Command line option wins.
Ted Kremenekea644d82008-09-03 21:22:16 +0000575
Chris Lattner802db9b2008-12-05 00:10:44 +0000576 // If in a conformant language mode (e.g. -std=c99) Blocks defaults to off
577 // even if they are normally on for the target. In GNU modes (e.g.
578 // -std=gnu99) the default for blocks depends on the target settings.
579 if (LangStd < lang_gnu_START)
580 Options.Blocks = 0;
581
Reid Spencer5f016e22007-07-11 17:01:13 +0000582 Options.DollarIdents = 1; // FIXME: Really a target property.
Chris Lattnerae0ee032008-12-04 23:20:07 +0000583 if (PascalStrings.getPosition())
584 Options.PascalStrings = PascalStrings;
Steve Naroffd62701b2008-02-07 03:50:06 +0000585 Options.Microsoft = MSExtensions;
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000586 Options.WritableStrings = WritableStrings;
Anders Carlsson695dbb62007-11-30 04:21:22 +0000587 Options.LaxVectorConversions = LaxVectorConversions;
Daniel Dunbar6379a7a2008-08-11 17:36:14 +0000588 Options.Exceptions = Exceptions;
Chris Lattnerae0ee032008-12-04 23:20:07 +0000589 if (EnableBlocks.getPosition())
590 Options.Blocks = EnableBlocks;
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000591
Chris Lattner8fc4dfb2008-12-04 22:54:33 +0000592 // Override the default runtime if the user requested it.
593 if (NeXTRuntime)
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000594 Options.NeXTRuntime = 1;
Chris Lattner8fc4dfb2008-12-04 22:54:33 +0000595 else if (GNURuntime)
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000596 Options.NeXTRuntime = 0;
Reid Spencer5f016e22007-07-11 17:01:13 +0000597}
598
Ted Kremenek01d9dbf2008-04-29 04:37:03 +0000599static llvm::cl::opt<bool>
600ObjCExclusiveGC("fobjc-gc-only",
601 llvm::cl::desc("Use GC exclusively for Objective-C related "
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000602 "memory management"));
Ted Kremenek01d9dbf2008-04-29 04:37:03 +0000603
604static llvm::cl::opt<bool>
605ObjCEnableGC("fobjc-gc",
Nico Weberfd54ebc2008-08-05 23:33:20 +0000606 llvm::cl::desc("Enable Objective-C garbage collection"));
Ted Kremenek01d9dbf2008-04-29 04:37:03 +0000607
608void InitializeGCMode(LangOptions &Options) {
609 if (ObjCExclusiveGC)
610 Options.setGCMode(LangOptions::GCOnly);
611 else if (ObjCEnableGC)
612 Options.setGCMode(LangOptions::HybridGC);
613}
614
615
Reid Spencer5f016e22007-07-11 17:01:13 +0000616//===----------------------------------------------------------------------===//
617// Our DiagnosticClient implementation
618//===----------------------------------------------------------------------===//
619
620// FIXME: Werror should take a list of things, -Werror=foo,bar
621static llvm::cl::opt<bool>
622WarningsAsErrors("Werror", llvm::cl::desc("Treat all warnings as errors"));
623
624static llvm::cl::opt<bool>
Chris Lattner5b4681c2008-05-29 15:36:45 +0000625SilenceWarnings("w", llvm::cl::desc("Do not emit any warnings"));
626
627static llvm::cl::opt<bool>
Reid Spencer5f016e22007-07-11 17:01:13 +0000628WarnOnExtensions("pedantic", llvm::cl::init(false),
629 llvm::cl::desc("Issue a warning on uses of GCC extensions"));
630
631static llvm::cl::opt<bool>
632ErrorOnExtensions("pedantic-errors",
633 llvm::cl::desc("Issue an error on uses of GCC extensions"));
634
635static llvm::cl::opt<bool>
Daniel Dunbar2fe09972008-09-12 18:10:20 +0000636SuppressSystemWarnings("suppress-system-warnings",
Daniel Dunbar320a0542008-09-30 20:49:53 +0000637 llvm::cl::desc("Suppress warnings issued in system headers"),
Daniel Dunbar2fe09972008-09-12 18:10:20 +0000638 llvm::cl::init(true));
639
640static llvm::cl::opt<bool>
Reid Spencer5f016e22007-07-11 17:01:13 +0000641WarnUnusedMacros("Wunused_macros",
642 llvm::cl::desc("Warn for unused macros in the main translation unit"));
643
Ted Kremenekdb87bca2007-11-13 18:37:02 +0000644static llvm::cl::opt<bool>
645WarnFloatEqual("Wfloat-equal",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000646 llvm::cl::desc("Warn about equality comparisons of floating point values"));
Ted Kremenekdb87bca2007-11-13 18:37:02 +0000647
Ted Kremenek73da5902007-12-17 17:50:07 +0000648static llvm::cl::opt<bool>
Fariborz Jahanian17d0d0d2009-01-08 23:23:10 +0000649WarnPropertyReadonlyAttrs("Wreadonly-setter-attrs",
650 llvm::cl::desc("Warn about readonly properties with writable attributes"));
651
652static llvm::cl::opt<bool>
Ted Kremenek73da5902007-12-17 17:50:07 +0000653WarnNoFormatNonLiteral("Wno-format-nonliteral",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000654 llvm::cl::desc("Do not warn about non-literal format strings"));
Ted Kremenek73da5902007-12-17 17:50:07 +0000655
Chris Lattner116a4b12008-01-23 17:19:46 +0000656static llvm::cl::opt<bool>
657WarnUndefMacros("Wundef",
658 llvm::cl::desc("Warn on use of undefined macros in #if's"));
659
Chris Lattner37d10842008-05-05 21:18:06 +0000660static llvm::cl::opt<bool>
Ted Kremenek358256d2008-05-30 16:42:02 +0000661WarnImplicitFunctionDeclaration("Wimplicit-function-declaration",
662 llvm::cl::desc("Warn about uses of implicitly defined functions"));
Chris Lattner116a4b12008-01-23 17:19:46 +0000663
Steve Narofffe6b0dc2008-10-21 10:37:50 +0000664static llvm::cl::opt<bool>
665WarnNoStrictSelectorMatch("Wno-strict-selector-match",
666 llvm::cl::desc("Do not warn about duplicate methods that have the same size and alignment"),
667 llvm::cl::init(true));
668
Reid Spencer5f016e22007-07-11 17:01:13 +0000669/// InitializeDiagnostics - Initialize the diagnostic object, based on the
670/// current command line option settings.
671static void InitializeDiagnostics(Diagnostic &Diags) {
Chris Lattner5b4681c2008-05-29 15:36:45 +0000672 Diags.setIgnoreAllWarnings(SilenceWarnings);
Reid Spencer5f016e22007-07-11 17:01:13 +0000673 Diags.setWarningsAsErrors(WarningsAsErrors);
674 Diags.setWarnOnExtensions(WarnOnExtensions);
675 Diags.setErrorOnExtensions(ErrorOnExtensions);
676
Daniel Dunbar2fe09972008-09-12 18:10:20 +0000677 // Suppress warnings in system headers unless requested not to.
678 Diags.setSuppressSystemWarnings(SuppressSystemWarnings);
679
Reid Spencer5f016e22007-07-11 17:01:13 +0000680 // Silence the "macro is not used" warning unless requested.
681 if (!WarnUnusedMacros)
682 Diags.setDiagnosticMapping(diag::pp_macro_not_used, diag::MAP_IGNORE);
Ted Kremenekdb87bca2007-11-13 18:37:02 +0000683
684 // Silence "floating point comparison" warnings unless requested.
685 if (!WarnFloatEqual)
686 Diags.setDiagnosticMapping(diag::warn_floatingpoint_eq, diag::MAP_IGNORE);
Ted Kremenek73da5902007-12-17 17:50:07 +0000687
Fariborz Jahanian17d0d0d2009-01-08 23:23:10 +0000688 if (!WarnPropertyReadonlyAttrs)
689 Diags.setDiagnosticMapping(diag::warn_objc_property_attr_mutually_exclusive,
690 diag::MAP_IGNORE);
691
Ted Kremenek73da5902007-12-17 17:50:07 +0000692 // Silence "format string is not a string literal" warnings if requested
693 if (WarnNoFormatNonLiteral)
Ted Kremenek7c1d3df2007-12-17 17:50:39 +0000694 Diags.setDiagnosticMapping(diag::warn_printf_not_string_constant,
695 diag::MAP_IGNORE);
Chris Lattner116a4b12008-01-23 17:19:46 +0000696 if (!WarnUndefMacros)
697 Diags.setDiagnosticMapping(diag::warn_pp_undef_identifier,diag::MAP_IGNORE);
Steve Naroffe7a37302008-02-11 22:40:08 +0000698
Chris Lattner37d10842008-05-05 21:18:06 +0000699 if (!WarnImplicitFunctionDeclaration)
700 Diags.setDiagnosticMapping(diag::warn_implicit_function_decl,
701 diag::MAP_IGNORE);
702
Steve Naroffe7a37302008-02-11 22:40:08 +0000703 if (MSExtensions) // MS allows unnamed struct/union fields.
704 Diags.setDiagnosticMapping(diag::w_no_declarators, diag::MAP_IGNORE);
Chris Lattner8aedf192008-05-04 23:52:02 +0000705
706 // If -pedantic-errors is set, turn extensions that warn by default into
707 // errors.
708 if (ErrorOnExtensions) {
709 Diags.setDiagnosticMapping(diag::warn_hex_escape_too_large,
710 diag::MAP_ERROR);
711 Diags.setDiagnosticMapping(diag::warn_octal_escape_too_large,
712 diag::MAP_ERROR);
713 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000714}
715
716//===----------------------------------------------------------------------===//
Ted Kremenekcb330932008-02-18 21:21:23 +0000717// Analysis-specific options.
718//===----------------------------------------------------------------------===//
719
720static llvm::cl::opt<std::string>
721AnalyzeSpecificFunction("analyze-function",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000722 llvm::cl::desc("Run analysis on specific function"));
Ted Kremenekcb330932008-02-18 21:21:23 +0000723
Ted Kremenekffe0f432008-03-07 22:58:01 +0000724static llvm::cl::opt<bool>
Ted Kremenekd71ed262008-04-10 22:16:52 +0000725TrimGraph("trim-egraph",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000726 llvm::cl::desc("Only show error-related paths in the analysis graph"));
Ted Kremenekffe0f432008-03-07 22:58:01 +0000727
Ted Kremenekcb330932008-02-18 21:21:23 +0000728//===----------------------------------------------------------------------===//
Ted Kremenekae360762007-12-03 22:06:55 +0000729// Target Triple Processing.
730//===----------------------------------------------------------------------===//
731
732static llvm::cl::opt<std::string>
733TargetTriple("triple",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000734 llvm::cl::desc("Specify target triple (e.g. i686-apple-darwin9)"));
Ted Kremenekae360762007-12-03 22:06:55 +0000735
Chris Lattner42e67372008-03-05 01:18:20 +0000736static llvm::cl::opt<std::string>
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000737Arch("arch", llvm::cl::desc("Specify target architecture (e.g. i686)"));
Ted Kremenekae360762007-12-03 22:06:55 +0000738
Chris Lattner6a30c1f2008-09-30 01:13:12 +0000739static llvm::cl::opt<std::string>
740MacOSVersionMin("mmacosx-version-min",
741 llvm::cl::desc("Specify target Mac OS/X version (e.g. 10.5)"));
742
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000743// If -mmacosx-version-min=10.3.9 is specified, change the triple from being
744// something like powerpc-apple-darwin9 to powerpc-apple-darwin7
745static void HandleMacOSVersionMin(std::string &Triple) {
746 std::string::size_type DarwinDashIdx = Triple.find("-darwin");
747 if (DarwinDashIdx == std::string::npos) {
748 fprintf(stderr,
749 "-mmacosx-version-min only valid for darwin (Mac OS/X) targets\n");
750 exit(1);
751 }
752 unsigned DarwinNumIdx = DarwinDashIdx + strlen("-darwin");
753
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000754 // Remove the number.
755 Triple.resize(DarwinNumIdx);
756
757 // Validate that MacOSVersionMin is a 'version number', starting with 10.[3-9]
758 bool MacOSVersionMinIsInvalid = false;
759 int VersionNum = 0;
760 if (MacOSVersionMin.size() < 4 ||
761 MacOSVersionMin.substr(0, 3) != "10." ||
762 !isdigit(MacOSVersionMin[3])) {
763 MacOSVersionMinIsInvalid = true;
764 } else {
765 const char *Start = MacOSVersionMin.c_str()+3;
766 char *End = 0;
767 VersionNum = (int)strtol(Start, &End, 10);
768
Chris Lattner079f2c462008-09-30 20:30:12 +0000769 // The version number must be in the range 0-9.
770 MacOSVersionMinIsInvalid = (unsigned)VersionNum > 9;
771
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000772 // Turn MacOSVersionMin into a darwin number: e.g. 10.3.9 is 3 -> 7.
773 Triple += llvm::itostr(VersionNum+4);
774
Chris Lattner079f2c462008-09-30 20:30:12 +0000775 if (End[0] == '.' && isdigit(End[1]) && End[2] == '\0') { // 10.4.7 is ok.
776 // Add the period piece (.7) to the end of the triple. This gives us
777 // something like ...-darwin8.7
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000778 Triple += End;
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000779 } else if (End[0] != '\0') { // "10.4" is ok. 10.4x is not.
780 MacOSVersionMinIsInvalid = true;
781 }
782 }
783
784 if (MacOSVersionMinIsInvalid) {
785 fprintf(stderr,
786 "-mmacosx-version-min=%s is invalid, expected something like '10.4'.\n",
787 MacOSVersionMin.c_str());
788 exit(1);
789 }
790}
791
792/// CreateTargetTriple - Process the various options that affect the target
793/// triple and build a final aggregate triple that we are compiling for.
Chris Lattner6fd9fa12008-03-09 01:35:13 +0000794static std::string CreateTargetTriple() {
Ted Kremenekae360762007-12-03 22:06:55 +0000795 // Initialize base triple. If a -triple option has been specified, use
796 // that triple. Otherwise, default to the host triple.
Chris Lattner6590d212007-12-12 05:01:48 +0000797 std::string Triple = TargetTriple;
Daniel Dunbare553a722008-10-02 01:21:33 +0000798 if (Triple.empty()) {
799 Triple = LLVM_HOSTTRIPLE;
800
Daniel Dunbara6291902008-12-12 18:34:35 +0000801 // Force i<N>86 to i386 when using LLVM_HOSTTRIPLE.
802 if (Triple[0] == 'i' && isdigit(Triple[1]) &&
803 Triple[2] == '8' && Triple[3] == '6')
804 Triple[1] = '3';
805
Daniel Dunbare553a722008-10-02 01:21:33 +0000806 // On darwin, we want to update the version to match that of the
807 // host.
808 std::string::size_type DarwinDashIdx = Triple.find("-darwin");
809 if (DarwinDashIdx != std::string::npos) {
810 Triple.resize(DarwinDashIdx + strlen("-darwin"));
811
Daniel Dunbara6291902008-12-12 18:34:35 +0000812 // Only add the major part of the os version.
813 std::string Version = llvm::sys::osVersion();
814 Triple += Version.substr(0, Version.find('.'));
Daniel Dunbare553a722008-10-02 01:21:33 +0000815 }
816 }
Ted Kremenekae360762007-12-03 22:06:55 +0000817
Chris Lattner6fd9fa12008-03-09 01:35:13 +0000818 // If -arch foo was specified, remove the architecture from the triple we have
819 // so far and replace it with the specified one.
Chris Lattner6a30c1f2008-09-30 01:13:12 +0000820 if (!Arch.empty()) {
821 // Decompose the base triple into "arch" and suffix.
822 std::string::size_type FirstDashIdx = Triple.find('-');
Chris Lattner6fd9fa12008-03-09 01:35:13 +0000823
Chris Lattner6a30c1f2008-09-30 01:13:12 +0000824 if (FirstDashIdx == std::string::npos) {
825 fprintf(stderr,
826 "Malformed target triple: \"%s\" ('-' could not be found).\n",
827 Triple.c_str());
828 exit(1);
829 }
Ted Kremenekae360762007-12-03 22:06:55 +0000830
Chris Lattner6a30c1f2008-09-30 01:13:12 +0000831 Triple = Arch + std::string(Triple.begin()+FirstDashIdx, Triple.end());
832 }
833
834 // If -mmacosx-version-min=10.3.9 is specified, change the triple from being
835 // something like powerpc-apple-darwin9 to powerpc-apple-darwin7
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000836 if (!MacOSVersionMin.empty())
837 HandleMacOSVersionMin(Triple);
Ted Kremenekae360762007-12-03 22:06:55 +0000838
Chris Lattner6a30c1f2008-09-30 01:13:12 +0000839 return Triple;
Ted Kremenekae360762007-12-03 22:06:55 +0000840}
841
842//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +0000843// Preprocessor Initialization
844//===----------------------------------------------------------------------===//
845
846// FIXME: Preprocessor builtins to support.
847// -A... - Play with #assertions
848// -undef - Undefine all predefined macros
849
850static llvm::cl::list<std::string>
851D_macros("D", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
852 llvm::cl::desc("Predefine the specified macro"));
853static llvm::cl::list<std::string>
854U_macros("U", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
855 llvm::cl::desc("Undefine the specified macro"));
856
Chris Lattner64299f82008-01-10 01:53:41 +0000857static llvm::cl::list<std::string>
858ImplicitIncludes("include", llvm::cl::value_desc("file"),
859 llvm::cl::desc("Include file before parsing"));
860
861
Reid Spencer5f016e22007-07-11 17:01:13 +0000862// Append a #define line to Buf for Macro. Macro should be of the form XXX,
863// in which case we emit "#define XXX 1" or "XXX=Y z W" in which case we emit
864// "#define XXX Y z W". To get a #define with no value, use "XXX=".
865static void DefineBuiltinMacro(std::vector<char> &Buf, const char *Macro,
866 const char *Command = "#define ") {
867 Buf.insert(Buf.end(), Command, Command+strlen(Command));
868 if (const char *Equal = strchr(Macro, '=')) {
869 // Turn the = into ' '.
870 Buf.insert(Buf.end(), Macro, Equal);
871 Buf.push_back(' ');
872 Buf.insert(Buf.end(), Equal+1, Equal+strlen(Equal));
873 } else {
874 // Push "macroname 1".
875 Buf.insert(Buf.end(), Macro, Macro+strlen(Macro));
876 Buf.push_back(' ');
877 Buf.push_back('1');
878 }
879 Buf.push_back('\n');
880}
881
Chris Lattner64299f82008-01-10 01:53:41 +0000882/// AddImplicitInclude - Add an implicit #include of the specified file to the
883/// predefines buffer.
884static void AddImplicitInclude(std::vector<char> &Buf, const std::string &File){
885 const char *Inc = "#include \"";
886 Buf.insert(Buf.end(), Inc, Inc+strlen(Inc));
887 Buf.insert(Buf.end(), File.begin(), File.end());
888 Buf.push_back('"');
889 Buf.push_back('\n');
890}
891
Reid Spencer5f016e22007-07-11 17:01:13 +0000892
Chris Lattner53b0dab2007-10-09 22:10:18 +0000893/// InitializePreprocessor - Initialize the preprocessor getting it and the
Chris Lattner51574ea2008-04-19 23:25:44 +0000894/// environment ready to process a single file. This returns true on error.
Chris Lattner53b0dab2007-10-09 22:10:18 +0000895///
Chris Lattner51574ea2008-04-19 23:25:44 +0000896static bool InitializePreprocessor(Preprocessor &PP,
897 bool InitializeSourceMgr,
898 const std::string &InFile) {
Chris Lattnerdee73592007-12-15 20:48:40 +0000899 FileManager &FileMgr = PP.getFileManager();
Reid Spencer5f016e22007-07-11 17:01:13 +0000900
Chris Lattner53b0dab2007-10-09 22:10:18 +0000901 // Figure out where to get and map in the main file.
Chris Lattnerdee73592007-12-15 20:48:40 +0000902 SourceManager &SourceMgr = PP.getSourceManager();
Ted Kremenek339b9c22008-04-17 22:31:54 +0000903
904 if (InitializeSourceMgr) {
905 if (InFile != "-") {
906 const FileEntry *File = FileMgr.getFile(InFile);
907 if (File) SourceMgr.createMainFileID(File, SourceLocation());
908 if (SourceMgr.getMainFileID() == 0) {
909 fprintf(stderr, "Error reading '%s'!\n",InFile.c_str());
Chris Lattner51574ea2008-04-19 23:25:44 +0000910 return true;
Ted Kremenek339b9c22008-04-17 22:31:54 +0000911 }
912 } else {
913 llvm::MemoryBuffer *SB = llvm::MemoryBuffer::getSTDIN();
914 if (SB) SourceMgr.createMainFileIDForMemBuffer(SB);
915 if (SourceMgr.getMainFileID() == 0) {
916 fprintf(stderr, "Error reading standard input! Empty?\n");
Chris Lattner51574ea2008-04-19 23:25:44 +0000917 return true;
Ted Kremenek339b9c22008-04-17 22:31:54 +0000918 }
Chris Lattner53b0dab2007-10-09 22:10:18 +0000919 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000920 }
Sam Bishop1102d6b2008-04-14 14:41:57 +0000921
Chris Lattneraa391972008-04-19 23:09:31 +0000922 std::vector<char> PredefineBuffer;
923
Reid Spencer5f016e22007-07-11 17:01:13 +0000924 // Add macros from the command line.
Sam Bishop1102d6b2008-04-14 14:41:57 +0000925 unsigned d = 0, D = D_macros.size();
926 unsigned u = 0, U = U_macros.size();
927 while (d < D || u < U) {
928 if (u == U || (d < D && D_macros.getPosition(d) < U_macros.getPosition(u)))
929 DefineBuiltinMacro(PredefineBuffer, D_macros[d++].c_str());
930 else
931 DefineBuiltinMacro(PredefineBuffer, U_macros[u++].c_str(), "#undef ");
932 }
933
Chris Lattner64299f82008-01-10 01:53:41 +0000934 // FIXME: Read any files specified by -imacros.
935
936 // Add implicit #includes from -include.
937 for (unsigned i = 0, e = ImplicitIncludes.size(); i != e; ++i)
938 AddImplicitInclude(PredefineBuffer, ImplicitIncludes[i]);
Chris Lattner53b0dab2007-10-09 22:10:18 +0000939
Chris Lattneraa391972008-04-19 23:09:31 +0000940 // Null terminate PredefinedBuffer and add it.
Chris Lattner53b0dab2007-10-09 22:10:18 +0000941 PredefineBuffer.push_back(0);
Chris Lattneraa391972008-04-19 23:09:31 +0000942 PP.setPredefines(&PredefineBuffer[0]);
Chris Lattner53b0dab2007-10-09 22:10:18 +0000943
Ted Kremenekc2e72992008-12-02 19:57:31 +0000944 // Use PTH.
945 if (!TokenCache.empty()) {
946 PTHManager* PM = PTHManager::Create(TokenCache, PP);
947 if (PM) PP.setPTHManager(PM);
948 }
949
Chris Lattner53b0dab2007-10-09 22:10:18 +0000950 // Once we've read this, we're done.
Chris Lattner51574ea2008-04-19 23:25:44 +0000951 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000952}
953
954//===----------------------------------------------------------------------===//
955// Preprocessor include path information.
956//===----------------------------------------------------------------------===//
957
958// This tool exports a large number of command line options to control how the
959// preprocessor searches for header files. At root, however, the Preprocessor
960// object takes a very simple interface: a list of directories to search for
961//
962// FIXME: -nostdinc,-nostdinc++
Chris Lattner0c946412007-08-26 17:47:35 +0000963// FIXME: -imultilib
Reid Spencer5f016e22007-07-11 17:01:13 +0000964//
Chris Lattner64299f82008-01-10 01:53:41 +0000965// FIXME: -imacros
Reid Spencer5f016e22007-07-11 17:01:13 +0000966
967static llvm::cl::opt<bool>
968nostdinc("nostdinc", llvm::cl::desc("Disable standard #include directories"));
969
970// Various command line options. These four add directories to each chain.
971static llvm::cl::list<std::string>
972F_dirs("F", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
973 llvm::cl::desc("Add directory to framework include search path"));
974static llvm::cl::list<std::string>
975I_dirs("I", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
976 llvm::cl::desc("Add directory to include search path"));
977static llvm::cl::list<std::string>
978idirafter_dirs("idirafter", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
979 llvm::cl::desc("Add directory to AFTER include search path"));
980static llvm::cl::list<std::string>
981iquote_dirs("iquote", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
982 llvm::cl::desc("Add directory to QUOTE include search path"));
983static llvm::cl::list<std::string>
984isystem_dirs("isystem", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
985 llvm::cl::desc("Add directory to SYSTEM include search path"));
986
987// These handle -iprefix/-iwithprefix/-iwithprefixbefore.
988static llvm::cl::list<std::string>
989iprefix_vals("iprefix", llvm::cl::value_desc("prefix"), llvm::cl::Prefix,
990 llvm::cl::desc("Set the -iwithprefix/-iwithprefixbefore prefix"));
991static llvm::cl::list<std::string>
992iwithprefix_vals("iwithprefix", llvm::cl::value_desc("dir"), llvm::cl::Prefix,
993 llvm::cl::desc("Set directory to SYSTEM include search path with prefix"));
994static llvm::cl::list<std::string>
995iwithprefixbefore_vals("iwithprefixbefore", llvm::cl::value_desc("dir"),
996 llvm::cl::Prefix,
997 llvm::cl::desc("Set directory to include search path with prefix"));
998
Chris Lattner0c946412007-08-26 17:47:35 +0000999static llvm::cl::opt<std::string>
1000isysroot("isysroot", llvm::cl::value_desc("dir"), llvm::cl::init("/"),
1001 llvm::cl::desc("Set the system root directory (usually /)"));
1002
Reid Spencer5f016e22007-07-11 17:01:13 +00001003// Finally, implement the code that groks the options above.
Chris Lattner5f9eae52008-03-01 08:07:28 +00001004
Reid Spencer5f016e22007-07-11 17:01:13 +00001005/// InitializeIncludePaths - Process the -I options and set them in the
1006/// HeaderSearch object.
Nico Weber0fca0222008-08-22 09:25:22 +00001007void InitializeIncludePaths(const char *Argv0, HeaderSearch &Headers,
1008 FileManager &FM, const LangOptions &Lang) {
1009 InitHeaderSearch Init(Headers, Verbose, isysroot);
1010
Ted Kremenekf3721112008-05-31 00:27:00 +00001011 // Handle -I... and -F... options, walking the lists in parallel.
1012 unsigned Iidx = 0, Fidx = 0;
1013 while (Iidx < I_dirs.size() && Fidx < F_dirs.size()) {
1014 if (I_dirs.getPosition(Iidx) < F_dirs.getPosition(Fidx)) {
Nico Weber0fca0222008-08-22 09:25:22 +00001015 Init.AddPath(I_dirs[Iidx], InitHeaderSearch::Angled, false, true, false);
Ted Kremenekf3721112008-05-31 00:27:00 +00001016 ++Iidx;
1017 } else {
Nico Weber0fca0222008-08-22 09:25:22 +00001018 Init.AddPath(F_dirs[Fidx], InitHeaderSearch::Angled, false, true, true);
Ted Kremenekf3721112008-05-31 00:27:00 +00001019 ++Fidx;
1020 }
1021 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001022
Ted Kremenekf3721112008-05-31 00:27:00 +00001023 // Consume what's left from whatever list was longer.
1024 for (; Iidx != I_dirs.size(); ++Iidx)
Nico Weber0fca0222008-08-22 09:25:22 +00001025 Init.AddPath(I_dirs[Iidx], InitHeaderSearch::Angled, false, true, false);
Ted Kremenekf3721112008-05-31 00:27:00 +00001026 for (; Fidx != F_dirs.size(); ++Fidx)
Nico Weber0fca0222008-08-22 09:25:22 +00001027 Init.AddPath(F_dirs[Fidx], InitHeaderSearch::Angled, false, true, true);
Reid Spencer5f016e22007-07-11 17:01:13 +00001028
1029 // Handle -idirafter... options.
1030 for (unsigned i = 0, e = idirafter_dirs.size(); i != e; ++i)
Nico Weber0fca0222008-08-22 09:25:22 +00001031 Init.AddPath(idirafter_dirs[i], InitHeaderSearch::After,
1032 false, true, false);
Reid Spencer5f016e22007-07-11 17:01:13 +00001033
1034 // Handle -iquote... options.
1035 for (unsigned i = 0, e = iquote_dirs.size(); i != e; ++i)
Nico Weber0fca0222008-08-22 09:25:22 +00001036 Init.AddPath(iquote_dirs[i], InitHeaderSearch::Quoted, false, true, false);
Reid Spencer5f016e22007-07-11 17:01:13 +00001037
1038 // Handle -isystem... options.
1039 for (unsigned i = 0, e = isystem_dirs.size(); i != e; ++i)
Nico Weber0fca0222008-08-22 09:25:22 +00001040 Init.AddPath(isystem_dirs[i], InitHeaderSearch::System, false, true, false);
Reid Spencer5f016e22007-07-11 17:01:13 +00001041
1042 // Walk the -iprefix/-iwithprefix/-iwithprefixbefore argument lists in
1043 // parallel, processing the values in order of occurance to get the right
1044 // prefixes.
1045 {
1046 std::string Prefix = ""; // FIXME: this isn't the correct default prefix.
1047 unsigned iprefix_idx = 0;
1048 unsigned iwithprefix_idx = 0;
1049 unsigned iwithprefixbefore_idx = 0;
1050 bool iprefix_done = iprefix_vals.empty();
1051 bool iwithprefix_done = iwithprefix_vals.empty();
1052 bool iwithprefixbefore_done = iwithprefixbefore_vals.empty();
1053 while (!iprefix_done || !iwithprefix_done || !iwithprefixbefore_done) {
1054 if (!iprefix_done &&
1055 (iwithprefix_done ||
1056 iprefix_vals.getPosition(iprefix_idx) <
1057 iwithprefix_vals.getPosition(iwithprefix_idx)) &&
1058 (iwithprefixbefore_done ||
1059 iprefix_vals.getPosition(iprefix_idx) <
1060 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
1061 Prefix = iprefix_vals[iprefix_idx];
1062 ++iprefix_idx;
1063 iprefix_done = iprefix_idx == iprefix_vals.size();
1064 } else if (!iwithprefix_done &&
1065 (iwithprefixbefore_done ||
1066 iwithprefix_vals.getPosition(iwithprefix_idx) <
1067 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
Nico Weber0fca0222008-08-22 09:25:22 +00001068 Init.AddPath(Prefix+iwithprefix_vals[iwithprefix_idx],
1069 InitHeaderSearch::System, false, false, false);
Reid Spencer5f016e22007-07-11 17:01:13 +00001070 ++iwithprefix_idx;
1071 iwithprefix_done = iwithprefix_idx == iwithprefix_vals.size();
1072 } else {
Nico Weber0fca0222008-08-22 09:25:22 +00001073 Init.AddPath(Prefix+iwithprefixbefore_vals[iwithprefixbefore_idx],
1074 InitHeaderSearch::Angled, false, false, false);
Reid Spencer5f016e22007-07-11 17:01:13 +00001075 ++iwithprefixbefore_idx;
1076 iwithprefixbefore_done =
1077 iwithprefixbefore_idx == iwithprefixbefore_vals.size();
1078 }
1079 }
1080 }
Chris Lattner5f9eae52008-03-01 08:07:28 +00001081
Nico Weber0fca0222008-08-22 09:25:22 +00001082 Init.AddDefaultEnvVarPaths(Lang);
Chris Lattner5f9eae52008-03-01 08:07:28 +00001083
Chris Lattnerdcaa0962008-03-03 03:16:03 +00001084 // Add the clang headers, which are relative to the clang driver.
1085 llvm::sys::Path MainExecutablePath =
Chris Lattner985e1822008-03-03 05:57:43 +00001086 llvm::sys::Path::GetMainExecutable(Argv0,
1087 (void*)(intptr_t)InitializeIncludePaths);
Chris Lattnerdcaa0962008-03-03 03:16:03 +00001088 if (!MainExecutablePath.isEmpty()) {
1089 MainExecutablePath.eraseComponent(); // Remove /clang from foo/bin/clang
1090 MainExecutablePath.eraseComponent(); // Remove /bin from foo/bin
1091 MainExecutablePath.appendComponent("Headers"); // Get foo/Headers
Nico Weber0fca0222008-08-22 09:25:22 +00001092 Init.AddPath(MainExecutablePath.c_str(), InitHeaderSearch::System,
1093 false, false, false);
Chris Lattnerdcaa0962008-03-03 03:16:03 +00001094 }
1095
Nico Weber0fca0222008-08-22 09:25:22 +00001096 if (!nostdinc)
1097 Init.AddDefaultSystemIncludePaths(Lang);
Reid Spencer5f016e22007-07-11 17:01:13 +00001098
1099 // Now that we have collected all of the include paths, merge them all
1100 // together and tell the preprocessor about them.
1101
Nico Weber0fca0222008-08-22 09:25:22 +00001102 Init.Realize();
Reid Spencer5f016e22007-07-11 17:01:13 +00001103}
1104
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001105//===----------------------------------------------------------------------===//
1106// Driver PreprocessorFactory - For lazily generating preprocessors ...
1107//===----------------------------------------------------------------------===//
1108
1109namespace {
1110class VISIBILITY_HIDDEN DriverPreprocessorFactory : public PreprocessorFactory {
Ted Kremenek339b9c22008-04-17 22:31:54 +00001111 const std::string &InFile;
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001112 Diagnostic &Diags;
1113 const LangOptions &LangInfo;
1114 TargetInfo &Target;
1115 SourceManager &SourceMgr;
1116 HeaderSearch &HeaderInfo;
Ted Kremenek339b9c22008-04-17 22:31:54 +00001117 bool InitializeSourceMgr;
1118
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001119public:
Ted Kremenek339b9c22008-04-17 22:31:54 +00001120 DriverPreprocessorFactory(const std::string &infile,
1121 Diagnostic &diags, const LangOptions &opts,
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001122 TargetInfo &target, SourceManager &SM,
1123 HeaderSearch &Headers)
Ted Kremenek339b9c22008-04-17 22:31:54 +00001124 : InFile(infile), Diags(diags), LangInfo(opts), Target(target),
1125 SourceMgr(SM), HeaderInfo(Headers), InitializeSourceMgr(true) {}
1126
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001127
1128 virtual ~DriverPreprocessorFactory() {}
1129
1130 virtual Preprocessor* CreatePreprocessor() {
Ted Kremenek339b9c22008-04-17 22:31:54 +00001131 Preprocessor* PP = new Preprocessor(Diags, LangInfo, Target,
1132 SourceMgr, HeaderInfo);
1133
Chris Lattner51574ea2008-04-19 23:25:44 +00001134 if (InitializePreprocessor(*PP, InitializeSourceMgr, InFile)) {
Ted Kremenek339b9c22008-04-17 22:31:54 +00001135 delete PP;
1136 return NULL;
1137 }
1138
Daniel Dunbar750c3582008-10-24 22:12:41 +00001139 /// FIXME: PP can only handle one callback
1140 if (ProgAction != PrintPreprocessedInput) {
1141 const char* ErrStr;
1142 bool DFG = CreateDependencyFileGen(PP, OutputFile, InFile, ErrStr);
1143 if (!DFG && ErrStr) {
Ted Kremenek9a30c242008-10-25 20:19:34 +00001144 fprintf(stderr, "%s", ErrStr);
Daniel Dunbar750c3582008-10-24 22:12:41 +00001145 return NULL;
1146 }
1147 }
1148
Ted Kremenek339b9c22008-04-17 22:31:54 +00001149 InitializeSourceMgr = false;
Ted Kremenek339b9c22008-04-17 22:31:54 +00001150 return PP;
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001151 }
1152};
1153}
Reid Spencer5f016e22007-07-11 17:01:13 +00001154
Reid Spencer5f016e22007-07-11 17:01:13 +00001155//===----------------------------------------------------------------------===//
1156// Basic Parser driver
1157//===----------------------------------------------------------------------===//
1158
Chris Lattner51574ea2008-04-19 23:25:44 +00001159static void ParseFile(Preprocessor &PP, MinimalAction *PA) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001160 Parser P(PP, *PA);
Ted Kremenek95041a22007-12-19 22:51:13 +00001161 PP.EnterMainSourceFile();
Reid Spencer5f016e22007-07-11 17:01:13 +00001162
1163 // Parsing the specified input file.
1164 P.ParseTranslationUnit();
1165 delete PA;
1166}
1167
1168//===----------------------------------------------------------------------===//
Daniel Dunbar70f92432008-10-23 05:50:47 +00001169// Code generation options
1170//===----------------------------------------------------------------------===//
1171
1172static llvm::cl::opt<bool>
1173OptSize("Os",
1174 llvm::cl::desc("Optimize for size"));
1175
1176// It might be nice to add bounds to the CommandLine library directly.
1177struct OptLevelParser : public llvm::cl::parser<unsigned> {
1178 bool parse(llvm::cl::Option &O, const char *ArgName,
1179 const std::string &Arg, unsigned &Val) {
1180 if (llvm::cl::parser<unsigned>::parse(O, ArgName, Arg, Val))
1181 return true;
1182 // FIXME: Support -O4.
1183 if (Val > 3)
1184 return O.error(": '" + Arg + "' invalid optimization level!");
1185 return false;
1186 }
1187};
1188static llvm::cl::opt<unsigned, false, OptLevelParser>
1189OptLevel("O", llvm::cl::Prefix,
1190 llvm::cl::desc("Optimization level"),
1191 llvm::cl::init(0));
1192
1193static void InitializeCompileOptions(CompileOptions &Opts) {
Daniel Dunbar70f92432008-10-23 05:50:47 +00001194 Opts.OptimizeSize = OptSize;
Daniel Dunbarac7ffe02008-10-29 07:56:11 +00001195 if (OptSize) {
1196 // -Os implies -O2
1197 // FIXME: Diagnose conflicting options.
1198 Opts.OptimizationLevel = 2;
1199 } else {
1200 Opts.OptimizationLevel = OptLevel;
1201 }
Daniel Dunbar8e8f3b72008-10-29 03:42:18 +00001202
1203 // FIXME: There are llvm-gcc options to control these selectively.
1204 Opts.InlineFunctions = (Opts.OptimizationLevel > 1);
1205 Opts.UnrollLoops = (Opts.OptimizationLevel > 1 && !OptSize);
1206 Opts.SimplifyLibCalls = 1;
Daniel Dunbardd913e52008-10-31 09:34:21 +00001207
1208#ifdef NDEBUG
1209 Opts.VerifyModule = 0;
1210#endif
Daniel Dunbar70f92432008-10-23 05:50:47 +00001211}
1212
1213//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +00001214// Main driver
1215//===----------------------------------------------------------------------===//
1216
Ted Kremenekdb094a22007-12-05 18:27:04 +00001217/// CreateASTConsumer - Create the ASTConsumer for the corresponding program
1218/// action. These consumers can operate on both ASTs that are freshly
1219/// parsed from source files as well as those deserialized from Bitcode.
Ted Kremenekfdfc1982007-12-19 22:24:34 +00001220static ASTConsumer* CreateASTConsumer(const std::string& InFile,
Ted Kremeneka1fa3a12007-12-13 00:37:31 +00001221 Diagnostic& Diag, FileManager& FileMgr,
Chris Lattnere66b65c2008-02-06 01:42:25 +00001222 const LangOptions& LangOpts,
Chris Lattner3245a0a2008-04-16 06:11:58 +00001223 Preprocessor *PP,
Ted Kremenek815c78f2008-08-05 18:50:11 +00001224 PreprocessorFactory *PPF) {
Ted Kremenekdb094a22007-12-05 18:27:04 +00001225 switch (ProgAction) {
1226 default:
1227 return NULL;
1228
1229 case ASTPrint:
1230 return CreateASTPrinter();
1231
1232 case ASTDump:
1233 return CreateASTDumper();
1234
1235 case ASTView:
Ted Kremenek6a340832008-03-18 21:19:49 +00001236 return CreateASTViewer();
1237
1238 case EmitHTML:
Ted Kremenek339b9c22008-04-17 22:31:54 +00001239 return CreateHTMLPrinter(OutputFile, Diag, PP, PPF);
Ted Kremenek902141f2008-07-02 18:23:21 +00001240
Ted Kremenek7cae2f62008-10-23 23:36:29 +00001241 case InheritanceView:
1242 return CreateInheritanceViewer(InheritanceViewCls);
1243
Ted Kremenekdb094a22007-12-05 18:27:04 +00001244 case TestSerialization:
Ted Kremeneke7d07d12008-06-04 15:55:15 +00001245 return CreateSerializationTest(Diag, FileMgr);
Ted Kremenekdb094a22007-12-05 18:27:04 +00001246
Daniel Dunbard69bacc2008-10-21 23:49:24 +00001247 case EmitAssembly:
Ted Kremenekdb094a22007-12-05 18:27:04 +00001248 case EmitLLVM:
Daniel Dunbar70f92432008-10-23 05:50:47 +00001249 case EmitBC: {
1250 BackendAction Act;
1251 if (ProgAction == EmitAssembly) {
1252 Act = Backend_EmitAssembly;
1253 } else if (ProgAction == EmitLLVM) {
1254 Act = Backend_EmitLL;
1255 } else {
1256 Act = Backend_EmitBC;
1257 }
1258 CompileOptions Opts;
1259 InitializeCompileOptions(Opts);
1260 return CreateBackendConsumer(Act, Diag, LangOpts, Opts,
Daniel Dunbard69bacc2008-10-21 23:49:24 +00001261 InFile, OutputFile, GenerateDebugInfo);
Daniel Dunbar70f92432008-10-23 05:50:47 +00001262 }
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +00001263
Ted Kremenek3910c7c2007-12-19 17:25:59 +00001264 case SerializeAST:
Ted Kremeneka1fa3a12007-12-13 00:37:31 +00001265 // FIXME: Allow user to tailor where the file is written.
Ted Kremeneke7d07d12008-06-04 15:55:15 +00001266 return CreateASTSerializer(InFile, OutputFile, Diag);
Ted Kremeneka1fa3a12007-12-13 00:37:31 +00001267
Steve Naroffb29b4272008-04-14 22:03:09 +00001268 case RewriteObjC:
Chris Lattnerc68ab772008-03-22 00:08:40 +00001269 return CreateCodeRewriterTest(InFile, OutputFile, Diag, LangOpts);
Steve Naroff13188952008-09-18 14:10:13 +00001270
1271 case RewriteBlocks:
1272 return CreateBlockRewriter(InFile, OutputFile, Diag, LangOpts);
Ted Kremenekf4381fd2008-07-02 00:03:09 +00001273
1274 case RunAnalysis:
1275 assert (!AnalysisList.empty());
1276 return CreateAnalysisConsumer(&AnalysisList[0],
1277 &AnalysisList[0]+AnalysisList.size(),
Ted Kremenek4fc82c82008-11-03 23:18:07 +00001278 AnalysisStoreOpt, AnalysisDiagOpt,
Ted Kremenekf4381fd2008-07-02 00:03:09 +00001279 Diag, PP, PPF, LangOpts,
1280 AnalyzeSpecificFunction,
Ted Kremenekf8ce6992008-08-27 22:31:43 +00001281 OutputFile, VisualizeEGDot, VisualizeEGUbi,
1282 TrimGraph, AnalyzeAll);
Ted Kremenekdb094a22007-12-05 18:27:04 +00001283 }
1284}
1285
Reid Spencer5f016e22007-07-11 17:01:13 +00001286/// ProcessInputFile - Process a single input file with the specified state.
1287///
Ted Kremenek339b9c22008-04-17 22:31:54 +00001288static void ProcessInputFile(Preprocessor &PP, PreprocessorFactory &PPF,
Ted Kremenek85888962008-10-21 00:54:44 +00001289 const std::string &InFile, ProgActions PA) {
Ted Kremenek7e7e6252008-08-08 02:46:37 +00001290 llvm::OwningPtr<ASTConsumer> Consumer;
Chris Lattnerbd247762007-07-22 06:05:44 +00001291 bool ClearSourceMgr = false;
Ted Kremenekd39bcd82007-09-26 18:39:29 +00001292
Ted Kremenek85888962008-10-21 00:54:44 +00001293 switch (PA) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001294 default:
Ted Kremenek7e7e6252008-08-08 02:46:37 +00001295 Consumer.reset(CreateASTConsumer(InFile, PP.getDiagnostics(),
1296 PP.getFileManager(), PP.getLangOptions(),
1297 &PP, &PPF));
Ted Kremenekdb094a22007-12-05 18:27:04 +00001298
1299 if (!Consumer) {
1300 fprintf(stderr, "Unexpected program action!\n");
Daniel Dunbarb0adbba2008-10-04 23:42:49 +00001301 HadErrors = true;
Ted Kremenekdb094a22007-12-05 18:27:04 +00001302 return;
1303 }
Ted Kremenekfdfc1982007-12-19 22:24:34 +00001304
Ted Kremenekdb094a22007-12-05 18:27:04 +00001305 break;
1306
Chris Lattnerc106c102008-10-12 05:03:36 +00001307 case DumpRawTokens: {
1308 SourceManager &SM = PP.getSourceManager();
1309 std::pair<const char*,const char*> File =
1310 SM.getBufferData(SM.getMainFileID());
1311 // Start lexing the specified input file.
1312 Lexer RawLex(SourceLocation::getFileLoc(SM.getMainFileID(), 0),
1313 PP.getLangOptions(), File.first, File.second);
1314 RawLex.SetKeepWhitespaceMode(true);
1315
1316 Token RawTok;
1317
1318 RawLex.LexFromRawLexer(RawTok);
1319 while (RawTok.isNot(tok::eof)) {
1320 PP.DumpToken(RawTok, true);
1321 fprintf(stderr, "\n");
1322 RawLex.LexFromRawLexer(RawTok);
1323 }
1324 ClearSourceMgr = true;
1325 break;
1326 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001327 case DumpTokens: { // Token dump mode.
Chris Lattnerd2177732007-07-20 16:59:19 +00001328 Token Tok;
Chris Lattnerc106c102008-10-12 05:03:36 +00001329 // Start preprocessing the specified input file.
Ted Kremenek95041a22007-12-19 22:51:13 +00001330 PP.EnterMainSourceFile();
Reid Spencer5f016e22007-07-11 17:01:13 +00001331 do {
1332 PP.Lex(Tok);
1333 PP.DumpToken(Tok, true);
1334 fprintf(stderr, "\n");
Chris Lattner057aaf62007-10-09 18:03:42 +00001335 } while (Tok.isNot(tok::eof));
Chris Lattnerbd247762007-07-22 06:05:44 +00001336 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001337 break;
1338 }
1339 case RunPreprocessorOnly: { // Just lex as fast as we can, no output.
Chris Lattnerd2177732007-07-20 16:59:19 +00001340 Token Tok;
Reid Spencer5f016e22007-07-11 17:01:13 +00001341 // Start parsing the specified input file.
Ted Kremenek95041a22007-12-19 22:51:13 +00001342 PP.EnterMainSourceFile();
Reid Spencer5f016e22007-07-11 17:01:13 +00001343 do {
1344 PP.Lex(Tok);
Chris Lattner057aaf62007-10-09 18:03:42 +00001345 } while (Tok.isNot(tok::eof));
Chris Lattnerbd247762007-07-22 06:05:44 +00001346 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001347 break;
1348 }
Ted Kremenek85888962008-10-21 00:54:44 +00001349
1350 case GeneratePCH: {
1351 CacheTokens(PP, OutputFile);
1352 ClearSourceMgr = true;
1353 break;
1354 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001355
1356 case PrintPreprocessedInput: // -E mode.
Chris Lattnere988bc22008-01-27 23:55:11 +00001357 DoPrintPreprocessedInput(PP, OutputFile);
Chris Lattnerbd247762007-07-22 06:05:44 +00001358 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001359 break;
Chris Lattnerb57e3d42008-05-08 06:52:13 +00001360
Reid Spencer5f016e22007-07-11 17:01:13 +00001361 case ParseNoop: // -parse-noop
Daniel Dunbare10b0f22008-10-31 08:56:51 +00001362 ParseFile(PP, new MinimalAction(PP));
Chris Lattnerbd247762007-07-22 06:05:44 +00001363 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001364 break;
1365
1366 case ParsePrintCallbacks:
Daniel Dunbare10b0f22008-10-31 08:56:51 +00001367 ParseFile(PP, CreatePrintParserActionsAction(PP));
Chris Lattnerbd247762007-07-22 06:05:44 +00001368 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001369 break;
Ted Kremenek44579782007-09-25 18:37:20 +00001370
Ted Kremenekd39bcd82007-09-26 18:39:29 +00001371 case ParseSyntaxOnly: // -fsyntax-only
Ted Kremenek7e7e6252008-08-08 02:46:37 +00001372 Consumer.reset(new ASTConsumer());
Ted Kremenek2bf55142007-09-17 20:49:30 +00001373 break;
Chris Lattnerb57e3d42008-05-08 06:52:13 +00001374
1375 case RewriteMacros:
Chris Lattner09510522008-05-09 22:43:24 +00001376 RewriteMacrosInInput(PP, InFile, OutputFile);
Chris Lattnerb57e3d42008-05-08 06:52:13 +00001377 ClearSourceMgr = true;
1378 break;
Chris Lattnerb13c5ee2008-10-12 05:29:20 +00001379
1380 case RewriteTest:
1381 DoRewriteTest(PP, InFile, OutputFile);
1382 ClearSourceMgr = true;
1383 break;
Chris Lattner580980b2007-09-16 19:46:59 +00001384 }
Ted Kremenekd39bcd82007-09-26 18:39:29 +00001385
Daniel Dunbar879c3ea2008-10-27 22:03:52 +00001386 if (Consumer)
Daniel Dunbard3db4012008-10-16 16:54:18 +00001387 ParseAST(PP, Consumer.get(), Stats, !DisableFree);
Daniel Dunbar879c3ea2008-10-27 22:03:52 +00001388
1389 if (VerifyDiagnostics)
Daniel Dunbar276373d2008-10-27 22:10:13 +00001390 if (CheckDiagnostics(PP))
1391 exit(1);
Chris Lattnere66b65c2008-02-06 01:42:25 +00001392
Reid Spencer5f016e22007-07-11 17:01:13 +00001393 if (Stats) {
Ted Kremenekfdfc1982007-12-19 22:24:34 +00001394 fprintf(stderr, "\nSTATISTICS FOR '%s':\n", InFile.c_str());
Reid Spencer5f016e22007-07-11 17:01:13 +00001395 PP.PrintStats();
1396 PP.getIdentifierTable().PrintStats();
Chris Lattnerdee73592007-12-15 20:48:40 +00001397 PP.getHeaderSearchInfo().PrintStats();
Chris Lattnerbd247762007-07-22 06:05:44 +00001398 if (ClearSourceMgr)
Chris Lattnerdee73592007-12-15 20:48:40 +00001399 PP.getSourceManager().PrintStats();
Reid Spencer5f016e22007-07-11 17:01:13 +00001400 fprintf(stderr, "\n");
1401 }
Chris Lattnerbd247762007-07-22 06:05:44 +00001402
1403 // For a multi-file compilation, some things are ok with nuking the source
1404 // manager tables, other require stable fileid/macroid's across multiple
1405 // files.
Chris Lattnerdee73592007-12-15 20:48:40 +00001406 if (ClearSourceMgr)
1407 PP.getSourceManager().clearIDTables();
Daniel Dunbard68ba0e2008-11-11 06:35:39 +00001408
1409 if (DisableFree)
1410 Consumer.take();
Reid Spencer5f016e22007-07-11 17:01:13 +00001411}
1412
Ted Kremenek20e97482007-12-12 23:41:08 +00001413static void ProcessSerializedFile(const std::string& InFile, Diagnostic& Diag,
1414 FileManager& FileMgr) {
1415
1416 if (VerifyDiagnostics) {
1417 fprintf(stderr, "-verify does not yet work with serialized ASTs.\n");
1418 exit (1);
1419 }
1420
1421 llvm::sys::Path Filename(InFile);
1422
1423 if (!Filename.isValid()) {
1424 fprintf(stderr, "serialized file '%s' not available.\n",InFile.c_str());
1425 exit (1);
1426 }
1427
Ted Kremenekc1e9dea2008-04-23 16:25:39 +00001428 llvm::OwningPtr<TranslationUnit> TU(ReadASTBitcodeFile(Filename, FileMgr));
Ted Kremenekfe4e0152007-12-13 18:11:11 +00001429
1430 if (!TU) {
1431 fprintf(stderr, "error: file '%s' could not be deserialized\n",
1432 InFile.c_str());
1433 exit (1);
1434 }
1435
Ted Kremenek63ea8632007-12-19 19:27:38 +00001436 // Observe that we use the source file name stored in the deserialized
1437 // translation unit, rather than InFile.
Ted Kremenekee533642007-12-20 19:47:16 +00001438 llvm::OwningPtr<ASTConsumer>
Ted Kremeneke7d07d12008-06-04 15:55:15 +00001439 Consumer(CreateASTConsumer(InFile, Diag, FileMgr, TU->getLangOptions(),
Ted Kremenek815c78f2008-08-05 18:50:11 +00001440 0, 0));
Nico Weber7bfaaae2008-08-10 19:59:06 +00001441
Ted Kremenek20e97482007-12-12 23:41:08 +00001442 if (!Consumer) {
1443 fprintf(stderr, "Unsupported program action with serialized ASTs!\n");
1444 exit (1);
1445 }
Nico Weber7bfaaae2008-08-10 19:59:06 +00001446
Ted Kremenekc1e9dea2008-04-23 16:25:39 +00001447 Consumer->Initialize(TU->getContext());
Nico Weber7bfaaae2008-08-10 19:59:06 +00001448
Chris Lattnere66b65c2008-02-06 01:42:25 +00001449 // FIXME: We need to inform Consumer about completed TagDecls as well.
Ted Kremenek20e97482007-12-12 23:41:08 +00001450 for (TranslationUnit::iterator I=TU->begin(), E=TU->end(); I!=E; ++I)
1451 Consumer->HandleTopLevelDecl(*I);
Ted Kremenek20e97482007-12-12 23:41:08 +00001452}
1453
1454
Reid Spencer5f016e22007-07-11 17:01:13 +00001455static llvm::cl::list<std::string>
1456InputFilenames(llvm::cl::Positional, llvm::cl::desc("<input files>"));
1457
Ted Kremenek20e97482007-12-12 23:41:08 +00001458static bool isSerializedFile(const std::string& InFile) {
1459 if (InFile.size() < 4)
1460 return false;
1461
1462 const char* s = InFile.c_str()+InFile.size()-4;
1463
1464 return s[0] == '.' &&
1465 s[1] == 'a' &&
1466 s[2] == 's' &&
1467 s[3] == 't';
1468}
1469
Reid Spencer5f016e22007-07-11 17:01:13 +00001470
1471int main(int argc, char **argv) {
Chris Lattnerdcaa0962008-03-03 03:16:03 +00001472 llvm::cl::ParseCommandLineOptions(argc, argv, " llvm clang cfe\n");
Reid Spencer5f016e22007-07-11 17:01:13 +00001473 llvm::sys::PrintStackTraceOnErrorSignal();
1474
1475 // If no input was specified, read from stdin.
1476 if (InputFilenames.empty())
1477 InputFilenames.push_back("-");
Ted Kremenek31e703b2007-12-11 23:28:38 +00001478
Reid Spencer5f016e22007-07-11 17:01:13 +00001479 // Create a file manager object to provide access to and cache the filesystem.
1480 FileManager FileMgr;
1481
Ted Kremenek31e703b2007-12-11 23:28:38 +00001482 // Create the diagnostic client for reporting errors or for
1483 // implementing -verify.
Nico Weber7bfaaae2008-08-10 19:59:06 +00001484 DiagnosticClient* TextDiagClient = 0;
Ted Kremenek88f5cde2008-03-27 06:17:42 +00001485
Ted Kremenekb4398aa2008-08-07 17:49:57 +00001486 if (!VerifyDiagnostics) {
1487 // Print diagnostics to stderr by default.
Chris Lattnera03a5b52008-11-19 06:56:25 +00001488 TextDiagClient = new TextDiagnosticPrinter(llvm::errs(),
1489 !NoShowColumn,
Ted Kremenekb4398aa2008-08-07 17:49:57 +00001490 !NoCaretDiagnostics);
1491 } else {
1492 // When checking diagnostics, just buffer them up.
1493 TextDiagClient = new TextDiagnosticBuffer();
1494
1495 if (InputFilenames.size() != 1) {
1496 fprintf(stderr,
1497 "-verify only works on single input files for now.\n");
1498 return 1;
Reid Spencer5f016e22007-07-11 17:01:13 +00001499 }
1500 }
Ted Kremenekb4398aa2008-08-07 17:49:57 +00001501
Reid Spencer5f016e22007-07-11 17:01:13 +00001502 // Configure our handling of diagnostics.
Ted Kremenekb4398aa2008-08-07 17:49:57 +00001503 llvm::OwningPtr<DiagnosticClient> DiagClient(TextDiagClient);
1504 Diagnostic Diags(DiagClient.get());
Ted Kremenek31e703b2007-12-11 23:28:38 +00001505 InitializeDiagnostics(Diags);
1506
Chris Lattner4f037832007-12-05 23:24:17 +00001507 // -I- is a deprecated GCC feature, scan for it and reject it.
1508 for (unsigned i = 0, e = I_dirs.size(); i != e; ++i) {
1509 if (I_dirs[i] == "-") {
Chris Lattner5917fe12008-11-18 05:05:28 +00001510 Diags.Report(FullSourceLoc(), diag::err_pp_I_dash_not_supported);
Chris Lattner4f037832007-12-05 23:24:17 +00001511 I_dirs.erase(I_dirs.begin()+i);
1512 --i;
1513 }
1514 }
Chris Lattner11215192008-03-14 06:12:05 +00001515
1516 // Get information about the target being compiled for.
1517 std::string Triple = CreateTargetTriple();
Ted Kremenek7a08e282008-08-07 18:13:12 +00001518 llvm::OwningPtr<TargetInfo> Target(TargetInfo::CreateTargetInfo(Triple));
1519
Chris Lattner11215192008-03-14 06:12:05 +00001520 if (Target == 0) {
1521 fprintf(stderr, "Sorry, I don't know what target this is: %s\n",
1522 Triple.c_str());
1523 fprintf(stderr, "Please use -triple or -arch.\n");
1524 exit(1);
1525 }
Chris Lattner4f037832007-12-05 23:24:17 +00001526
Ted Kremenekf4381fd2008-07-02 00:03:09 +00001527 // Are we invoking one or more source analyses?
1528 if (!AnalysisList.empty() && ProgAction == ParseSyntaxOnly)
1529 ProgAction = RunAnalysis;
Ted Kremenek7cae2f62008-10-23 23:36:29 +00001530 else if (!InheritanceViewCls.empty()) // C++ visualization?
1531 ProgAction = InheritanceView;
Ted Kremenekb4398aa2008-08-07 17:49:57 +00001532
Ted Kremenekc0c03bc2008-06-06 22:42:39 +00001533 llvm::OwningPtr<SourceManager> SourceMgr;
1534
Reid Spencer5f016e22007-07-11 17:01:13 +00001535 for (unsigned i = 0, e = InputFilenames.size(); i != e; ++i) {
Ted Kremenek31e703b2007-12-11 23:28:38 +00001536 const std::string &InFile = InputFilenames[i];
Ted Kremenek31e703b2007-12-11 23:28:38 +00001537
Ted Kremenekb4398aa2008-08-07 17:49:57 +00001538 if (isSerializedFile(InFile)) {
1539 Diags.setClient(TextDiagClient);
Ted Kremenek20e97482007-12-12 23:41:08 +00001540 ProcessSerializedFile(InFile,Diags,FileMgr);
Ted Kremenekb4398aa2008-08-07 17:49:57 +00001541 }
Ted Kremenek20e97482007-12-12 23:41:08 +00001542 else {
1543 /// Create a SourceManager object. This tracks and owns all the file
1544 /// buffers allocated to a translation unit.
Ted Kremenekc0c03bc2008-06-06 22:42:39 +00001545 if (!SourceMgr)
1546 SourceMgr.reset(new SourceManager());
1547 else
1548 SourceMgr->clearIDTables();
Ted Kremenek31e703b2007-12-11 23:28:38 +00001549
Ted Kremenek20e97482007-12-12 23:41:08 +00001550 // Initialize language options, inferring file types from input filenames.
1551 LangOptions LangInfo;
1552 InitializeBaseLanguage();
1553 LangKind LK = GetLanguage(InFile);
Ted Kremenek85888962008-10-21 00:54:44 +00001554 bool PCH = InitializeLangOptions(LangInfo, LK);
Ted Kremenek01d9dbf2008-04-29 04:37:03 +00001555 InitializeGCMode(LangInfo);
Chris Lattner8fc4dfb2008-12-04 22:54:33 +00001556 InitializeLanguageStandard(LangInfo, LK, Target.get());
Ted Kremenek85888962008-10-21 00:54:44 +00001557
Ted Kremenek20e97482007-12-12 23:41:08 +00001558 // Process the -I options and set them in the HeaderInfo.
1559 HeaderSearch HeaderInfo(FileMgr);
Ted Kremenekc68ecb52008-06-06 01:47:30 +00001560
Chris Lattnerdcaa0962008-03-03 03:16:03 +00001561 InitializeIncludePaths(argv[0], HeaderInfo, FileMgr, LangInfo);
Ted Kremenek20e97482007-12-12 23:41:08 +00001562
Ted Kremenek20e97482007-12-12 23:41:08 +00001563 // Set up the preprocessor with these options.
Ted Kremenek339b9c22008-04-17 22:31:54 +00001564 DriverPreprocessorFactory PPFactory(InFile, Diags, LangInfo, *Target,
Ted Kremenekc0c03bc2008-06-06 22:42:39 +00001565 *SourceMgr.get(), HeaderInfo);
Ted Kremenek20e97482007-12-12 23:41:08 +00001566
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001567 llvm::OwningPtr<Preprocessor> PP(PPFactory.CreatePreprocessor());
1568
Ted Kremenek339b9c22008-04-17 22:31:54 +00001569 if (!PP)
Ted Kremenek76edd0e2007-12-19 22:29:55 +00001570 continue;
Ted Kremenekb4398aa2008-08-07 17:49:57 +00001571
1572 // Create the HTMLDiagnosticsClient if we are using one. Otherwise,
1573 // always reset to using TextDiagClient.
1574 llvm::OwningPtr<DiagnosticClient> TmpClient;
Ted Kremenek76edd0e2007-12-19 22:29:55 +00001575
Ted Kremenekb4398aa2008-08-07 17:49:57 +00001576 if (!HTMLDiag.empty()) {
1577 TmpClient.reset(CreateHTMLDiagnosticClient(HTMLDiag, PP.get(),
1578 &PPFactory));
1579 Diags.setClient(TmpClient.get());
1580 }
1581 else
1582 Diags.setClient(TextDiagClient);
1583
1584 // Process the source file.
Ted Kremenek85888962008-10-21 00:54:44 +00001585 ProcessInputFile(*PP, PPFactory, InFile, PCH ? GeneratePCH : ProgAction);
1586
Ted Kremenekc0c03bc2008-06-06 22:42:39 +00001587 HeaderInfo.ClearFileInfo();
Ted Kremenek20e97482007-12-12 23:41:08 +00001588 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001589 }
Chris Lattner11215192008-03-14 06:12:05 +00001590
Ted Kremenek7a08e282008-08-07 18:13:12 +00001591 if (unsigned NumDiagnostics = Diags.getNumDiagnostics())
Reid Spencer5f016e22007-07-11 17:01:13 +00001592 fprintf(stderr, "%d diagnostic%s generated.\n", NumDiagnostics,
1593 (NumDiagnostics == 1 ? "" : "s"));
1594
1595 if (Stats) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001596 FileMgr.PrintStats();
1597 fprintf(stderr, "\n");
1598 }
1599
Daniel Dunbar276373d2008-10-27 22:10:13 +00001600 // If verifying diagnostics and we reached here, all is well.
1601 if (VerifyDiagnostics)
1602 return 0;
1603
Daniel Dunbar524b86f2008-10-28 00:38:08 +00001604 // Managed static deconstruction. Useful for making things like
1605 // -time-passes usable.
1606 llvm::llvm_shutdown();
1607
Daniel Dunbarb0adbba2008-10-04 23:42:49 +00001608 return HadErrors || (Diags.getNumErrors() != 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00001609}