blob: 333ac6096aaf484febc4c872bee29fdc168a172a [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"
Reid Spencer5f016e22007-07-11 17:01:13 +000027#include "TextDiagnosticBuffer.h"
28#include "TextDiagnosticPrinter.h"
Ted Kremenek77cda502007-12-18 21:34:28 +000029#include "clang/AST/TranslationUnit.h"
Chris Lattner8ee3c032008-02-06 02:01:47 +000030#include "clang/CodeGen/ModuleBuilder.h"
Chris Lattnere91c1342008-02-06 00:23:21 +000031#include "clang/Sema/ParseAST.h"
Chris Lattner556beb72007-09-15 22:56:56 +000032#include "clang/AST/ASTConsumer.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000033#include "clang/Parse/Parser.h"
34#include "clang/Lex/HeaderSearch.h"
35#include "clang/Basic/FileManager.h"
36#include "clang/Basic/SourceManager.h"
37#include "clang/Basic/TargetInfo.h"
Chris Lattnere66b65c2008-02-06 01:42:25 +000038#include "llvm/Module.h"
Chris Lattner8f3dab82007-12-15 23:20:07 +000039#include "llvm/ADT/SmallPtrSet.h"
Chris Lattnere66b65c2008-02-06 01:42:25 +000040#include "llvm/Bitcode/ReaderWriter.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000041#include "llvm/Support/CommandLine.h"
42#include "llvm/Support/MemoryBuffer.h"
43#include "llvm/System/Signals.h"
Ted Kremenekae360762007-12-03 22:06:55 +000044#include "llvm/Config/config.h"
Ted Kremenekee533642007-12-20 19:47:16 +000045#include "llvm/ADT/OwningPtr.h"
Chris Lattnerdcaa0962008-03-03 03:16:03 +000046#include "llvm/System/Path.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000047#include <memory>
Chris Lattnere66b65c2008-02-06 01:42:25 +000048#include <fstream>
Reid Spencer5f016e22007-07-11 17:01:13 +000049using namespace clang;
50
51//===----------------------------------------------------------------------===//
52// Global options.
53//===----------------------------------------------------------------------===//
54
55static llvm::cl::opt<bool>
56Verbose("v", llvm::cl::desc("Enable verbose output"));
57static llvm::cl::opt<bool>
Nate Begemanaabbb122007-12-30 01:38:50 +000058Stats("print-stats",
59 llvm::cl::desc("Print performance metrics and statistics"));
Reid Spencer5f016e22007-07-11 17:01:13 +000060
61enum ProgActions {
Chris Lattner77cd2a02007-10-11 00:43:27 +000062 RewriteTest, // Rewriter testing stuff.
Reid Spencer5f016e22007-07-11 17:01:13 +000063 EmitLLVM, // Emit a .ll file.
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +000064 EmitBC, // Emit a .bc file.
Ted Kremeneka1fa3a12007-12-13 00:37:31 +000065 SerializeAST, // Emit a .ast file.
Ted Kremenek6a340832008-03-18 21:19:49 +000066 EmitHTML, // Translate input source into HTML.
Chris Lattner3b427b32007-10-11 00:18:28 +000067 ASTPrint, // Parse ASTs and print them.
68 ASTDump, // Parse ASTs and dump them.
69 ASTView, // Parse ASTs and view them in Graphviz.
Ted Kremenekfddd5182007-08-21 21:42:03 +000070 ParseCFGDump, // Parse ASTS. Build CFGs. Print CFGs.
Ted Kremenek055c2752007-09-06 23:00:42 +000071 ParseCFGView, // Parse ASTS. Build CFGs. View CFGs.
Ted Kremeneke4e63342007-09-06 00:17:54 +000072 AnalysisLiveVariables, // Print results of live-variable analysis.
Ted Kremenekd55fe522008-02-15 00:35:38 +000073 AnalysisGRSimpleVals, // Perform graph-reachability constant prop.
74 AnalysisGRSimpleValsView, // Visualize results of path-sens. analysis.
Ted Kremenek2fff37e2008-03-06 00:08:09 +000075 CheckerCFRef, // Run the Core Foundation Ref. Count Checker.
Ted Kremenek055c2752007-09-06 23:00:42 +000076 WarnDeadStores, // Run DeadStores checker on parsed ASTs.
Ted Kremenek44579782007-09-25 18:37:20 +000077 WarnDeadStoresCheck, // Check diagnostics for "DeadStores".
Ted Kremenek2bf55142007-09-17 20:49:30 +000078 WarnUninitVals, // Run UnitializedVariables checker.
Ted Kremenekbfa82c42007-10-16 23:37:27 +000079 TestSerialization, // Run experimental serialization code.
Reid Spencer5f016e22007-07-11 17:01:13 +000080 ParsePrintCallbacks, // Parse and print each callback.
81 ParseSyntaxOnly, // Parse and perform semantic analysis.
82 ParseNoop, // Parse with noop callbacks.
83 RunPreprocessorOnly, // Just lex, no output.
84 PrintPreprocessedInput, // -E mode.
85 DumpTokens // Token dump mode.
86};
87
88static llvm::cl::opt<ProgActions>
89ProgAction(llvm::cl::desc("Choose output type:"), llvm::cl::ZeroOrMore,
90 llvm::cl::init(ParseSyntaxOnly),
91 llvm::cl::values(
92 clEnumValN(RunPreprocessorOnly, "Eonly",
93 "Just run preprocessor, no output (for timings)"),
94 clEnumValN(PrintPreprocessedInput, "E",
95 "Run preprocessor, emit preprocessed file"),
96 clEnumValN(DumpTokens, "dumptokens",
97 "Run preprocessor, dump internal rep of tokens"),
98 clEnumValN(ParseNoop, "parse-noop",
99 "Run parser with noop callbacks (for timings)"),
100 clEnumValN(ParseSyntaxOnly, "fsyntax-only",
101 "Run parser and perform semantic analysis"),
102 clEnumValN(ParsePrintCallbacks, "parse-print-callbacks",
103 "Run parser and print each callback invoked"),
Ted Kremenek6a340832008-03-18 21:19:49 +0000104 clEnumValN(EmitHTML, "emit-html",
105 "Output input source as HTML"),
Chris Lattner3b427b32007-10-11 00:18:28 +0000106 clEnumValN(ASTPrint, "ast-print",
107 "Build ASTs and then pretty-print them"),
108 clEnumValN(ASTDump, "ast-dump",
109 "Build ASTs and then debug dump them"),
Chris Lattnerea254db2007-10-11 00:37:43 +0000110 clEnumValN(ASTView, "ast-view",
Chris Lattner3b427b32007-10-11 00:18:28 +0000111 "Build ASTs and view them with GraphViz."),
Ted Kremenekfddd5182007-08-21 21:42:03 +0000112 clEnumValN(ParseCFGDump, "dump-cfg",
Ted Kremenek7dba8602007-08-29 21:56:09 +0000113 "Run parser, then build and print CFGs."),
114 clEnumValN(ParseCFGView, "view-cfg",
Ted Kremeneke4e63342007-09-06 00:17:54 +0000115 "Run parser, then build and view CFGs with Graphviz."),
116 clEnumValN(AnalysisLiveVariables, "dump-live-variables",
Ted Kremenek27b07c52007-09-06 21:26:58 +0000117 "Print results of live variable analysis."),
Ted Kremenek786d3372007-09-25 18:05:45 +0000118 clEnumValN(WarnDeadStores, "warn-dead-stores",
Ted Kremenek055c2752007-09-06 23:00:42 +0000119 "Flag warnings of stores to dead variables."),
Ted Kremenek786d3372007-09-25 18:05:45 +0000120 clEnumValN(WarnUninitVals, "warn-uninit-values",
Ted Kremenek2bf55142007-09-17 20:49:30 +0000121 "Flag warnings of uses of unitialized variables."),
Ted Kremeneke01c9872008-02-14 22:36:46 +0000122 clEnumValN(AnalysisGRSimpleVals, "grsimple",
Chris Lattner3a2781c2008-01-10 01:41:55 +0000123 "Perform path-sensitive constant propagation."),
Ted Kremenekd55fe522008-02-15 00:35:38 +0000124 clEnumValN(AnalysisGRSimpleValsView, "grsimple-view",
125 "View results of path-sensitive constant propagation."),
Ted Kremenek2fff37e2008-03-06 00:08:09 +0000126 clEnumValN(CheckerCFRef, "check-cfref",
127 "Run the Core Foundation reference count checker."),
Ted Kremenekbfa82c42007-10-16 23:37:27 +0000128 clEnumValN(TestSerialization, "test-pickling",
Chris Lattnerf3dabbd2008-03-09 05:25:01 +0000129 "Run prototype serialization code."),
Reid Spencer5f016e22007-07-11 17:01:13 +0000130 clEnumValN(EmitLLVM, "emit-llvm",
Ted Kremenek27b07c52007-09-06 21:26:58 +0000131 "Build ASTs then convert to LLVM, emit .ll file"),
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +0000132 clEnumValN(EmitBC, "emit-llvm-bc",
133 "Build ASTs then convert to LLVM, emit .bc file"),
Ted Kremenekccc76472007-12-19 19:47:59 +0000134 clEnumValN(SerializeAST, "serialize",
Ted Kremeneka1fa3a12007-12-13 00:37:31 +0000135 "Build ASTs and emit .ast file"),
Chris Lattner77cd2a02007-10-11 00:43:27 +0000136 clEnumValN(RewriteTest, "rewrite-test",
137 "Playground for the code rewriter"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000138 clEnumValEnd));
139
Ted Kremenekccc76472007-12-19 19:47:59 +0000140
141static llvm::cl::opt<std::string>
142OutputFile("o",
Ted Kremenek50b56412007-12-19 19:50:41 +0000143 llvm::cl::value_desc("path"),
Ted Kremenekccc76472007-12-19 19:47:59 +0000144 llvm::cl::desc("Specify output file (for --serialize, this is a directory)"));
145
Ted Kremenek41193e42007-09-26 19:42:19 +0000146static llvm::cl::opt<bool>
147VerifyDiagnostics("verify",
148 llvm::cl::desc("Verify emitted diagnostics and warnings."));
149
Reid Spencer5f016e22007-07-11 17:01:13 +0000150//===----------------------------------------------------------------------===//
151// Language Options
152//===----------------------------------------------------------------------===//
153
154enum LangKind {
155 langkind_unspecified,
156 langkind_c,
157 langkind_c_cpp,
158 langkind_cxx,
159 langkind_cxx_cpp,
160 langkind_objc,
161 langkind_objc_cpp,
162 langkind_objcxx,
163 langkind_objcxx_cpp
164};
165
166/* TODO: GCC also accepts:
167 c-header c++-header objective-c-header objective-c++-header
168 assembler assembler-with-cpp
169 ada, f77*, ratfor (!), f95, java, treelang
170 */
171static llvm::cl::opt<LangKind>
172BaseLang("x", llvm::cl::desc("Base language to compile"),
173 llvm::cl::init(langkind_unspecified),
174 llvm::cl::values(clEnumValN(langkind_c, "c", "C"),
175 clEnumValN(langkind_cxx, "c++", "C++"),
176 clEnumValN(langkind_objc, "objective-c", "Objective C"),
177 clEnumValN(langkind_objcxx,"objective-c++","Objective C++"),
178 clEnumValN(langkind_c_cpp, "c-cpp-output",
179 "Preprocessed C"),
180 clEnumValN(langkind_cxx_cpp, "c++-cpp-output",
181 "Preprocessed C++"),
182 clEnumValN(langkind_objc_cpp, "objective-c-cpp-output",
183 "Preprocessed Objective C"),
184 clEnumValN(langkind_objcxx_cpp,"objective-c++-cpp-output",
185 "Preprocessed Objective C++"),
186 clEnumValEnd));
187
188static llvm::cl::opt<bool>
189LangObjC("ObjC", llvm::cl::desc("Set base language to Objective-C"),
190 llvm::cl::Hidden);
191static llvm::cl::opt<bool>
192LangObjCXX("ObjC++", llvm::cl::desc("Set base language to Objective-C++"),
193 llvm::cl::Hidden);
194
Ted Kremenek8904f152007-12-05 23:49:08 +0000195/// InitializeBaseLanguage - Handle the -x foo options.
196static void InitializeBaseLanguage() {
197 if (LangObjC)
198 BaseLang = langkind_objc;
199 else if (LangObjCXX)
200 BaseLang = langkind_objcxx;
201}
202
203static LangKind GetLanguage(const std::string &Filename) {
204 if (BaseLang != langkind_unspecified)
205 return BaseLang;
206
207 std::string::size_type DotPos = Filename.rfind('.');
208
209 if (DotPos == std::string::npos) {
210 BaseLang = langkind_c; // Default to C if no extension.
Chris Lattner9b2f6c42008-01-04 19:12:28 +0000211 return langkind_c;
Reid Spencer5f016e22007-07-11 17:01:13 +0000212 }
213
Ted Kremenek8904f152007-12-05 23:49:08 +0000214 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
215 // C header: .h
216 // C++ header: .hh or .H;
217 // assembler no preprocessing: .s
218 // assembler: .S
219 if (Ext == "c")
220 return langkind_c;
221 else if (Ext == "i")
222 return langkind_c_cpp;
223 else if (Ext == "ii")
224 return langkind_cxx_cpp;
225 else if (Ext == "m")
226 return langkind_objc;
227 else if (Ext == "mi")
228 return langkind_objc_cpp;
229 else if (Ext == "mm" || Ext == "M")
230 return langkind_objcxx;
231 else if (Ext == "mii")
232 return langkind_objcxx_cpp;
233 else if (Ext == "C" || Ext == "cc" || Ext == "cpp" || Ext == "CPP" ||
234 Ext == "c++" || Ext == "cp" || Ext == "cxx")
235 return langkind_cxx;
236 else
237 return langkind_c;
238}
239
240
241static void InitializeLangOptions(LangOptions &Options, LangKind LK) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000242 // FIXME: implement -fpreprocessed mode.
243 bool NoPreprocess = false;
244
Ted Kremenek8904f152007-12-05 23:49:08 +0000245 switch (LK) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000246 default: assert(0 && "Unknown language kind!");
247 case langkind_c_cpp:
248 NoPreprocess = true;
249 // FALLTHROUGH
250 case langkind_c:
251 break;
252 case langkind_cxx_cpp:
253 NoPreprocess = true;
254 // FALLTHROUGH
255 case langkind_cxx:
256 Options.CPlusPlus = 1;
257 break;
258 case langkind_objc_cpp:
259 NoPreprocess = true;
260 // FALLTHROUGH
261 case langkind_objc:
262 Options.ObjC1 = Options.ObjC2 = 1;
263 break;
264 case langkind_objcxx_cpp:
265 NoPreprocess = true;
266 // FALLTHROUGH
267 case langkind_objcxx:
268 Options.ObjC1 = Options.ObjC2 = 1;
269 Options.CPlusPlus = 1;
270 break;
271 }
272}
273
274/// LangStds - Language standards we support.
275enum LangStds {
276 lang_unspecified,
277 lang_c89, lang_c94, lang_c99,
278 lang_gnu89, lang_gnu99,
Chris Lattnerd4b80f12007-07-16 04:18:29 +0000279 lang_cxx98, lang_gnucxx98,
280 lang_cxx0x, lang_gnucxx0x
Reid Spencer5f016e22007-07-11 17:01:13 +0000281};
282
283static llvm::cl::opt<LangStds>
284LangStd("std", llvm::cl::desc("Language standard to compile for"),
285 llvm::cl::init(lang_unspecified),
286 llvm::cl::values(clEnumValN(lang_c89, "c89", "ISO C 1990"),
287 clEnumValN(lang_c89, "c90", "ISO C 1990"),
288 clEnumValN(lang_c89, "iso9899:1990", "ISO C 1990"),
289 clEnumValN(lang_c94, "iso9899:199409",
290 "ISO C 1990 with amendment 1"),
291 clEnumValN(lang_c99, "c99", "ISO C 1999"),
292// clEnumValN(lang_c99, "c9x", "ISO C 1999"),
293 clEnumValN(lang_c99, "iso9899:1999", "ISO C 1999"),
294// clEnumValN(lang_c99, "iso9899:199x", "ISO C 1999"),
295 clEnumValN(lang_gnu89, "gnu89",
296 "ISO C 1990 with GNU extensions (default for C)"),
297 clEnumValN(lang_gnu99, "gnu99",
298 "ISO C 1999 with GNU extensions"),
299 clEnumValN(lang_gnu99, "gnu9x",
300 "ISO C 1999 with GNU extensions"),
301 clEnumValN(lang_cxx98, "c++98",
302 "ISO C++ 1998 with amendments"),
303 clEnumValN(lang_gnucxx98, "gnu++98",
304 "ISO C++ 1998 with amendments and GNU "
305 "extensions (default for C++)"),
Chris Lattnerd4b80f12007-07-16 04:18:29 +0000306 clEnumValN(lang_cxx0x, "c++0x",
307 "Upcoming ISO C++ 200x with amendments"),
308 clEnumValN(lang_gnucxx0x, "gnu++0x",
309 "Upcoming ISO C++ 200x with amendments and GNU "
310 "extensions (default for C++)"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000311 clEnumValEnd));
312
313static llvm::cl::opt<bool>
314NoOperatorNames("fno-operator-names",
315 llvm::cl::desc("Do not treat C++ operator name keywords as "
316 "synonyms for operators"));
317
Anders Carlssonee98ac52007-10-15 02:50:23 +0000318static llvm::cl::opt<bool>
319PascalStrings("fpascal-strings",
320 llvm::cl::desc("Recognize and construct Pascal-style "
321 "string literals"));
Steve Naroffd62701b2008-02-07 03:50:06 +0000322
323static llvm::cl::opt<bool>
324MSExtensions("fms-extensions",
325 llvm::cl::desc("Accept some non-standard constructs used in "
326 "Microsoft header files. "));
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000327
328static llvm::cl::opt<bool>
329WritableStrings("fwritable-strings",
330 llvm::cl::desc("Store string literals as writable data."));
Anders Carlsson695dbb62007-11-30 04:21:22 +0000331
332static llvm::cl::opt<bool>
333LaxVectorConversions("flax-vector-conversions",
334 llvm::cl::desc("Allow implicit conversions between vectors"
335 " with a different number of elements or "
336 "different element types."));
Reid Spencer5f016e22007-07-11 17:01:13 +0000337// FIXME: add:
338// -ansi
339// -trigraphs
340// -fdollars-in-identifiers
Anders Carlssonee98ac52007-10-15 02:50:23 +0000341// -fpascal-strings
Ted Kremenek8904f152007-12-05 23:49:08 +0000342static void InitializeLanguageStandard(LangOptions &Options, LangKind LK) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000343 if (LangStd == lang_unspecified) {
344 // Based on the base language, pick one.
Ted Kremenek8904f152007-12-05 23:49:08 +0000345 switch (LK) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000346 default: assert(0 && "Unknown base language");
347 case langkind_c:
348 case langkind_c_cpp:
349 case langkind_objc:
350 case langkind_objc_cpp:
351 LangStd = lang_gnu99;
352 break;
353 case langkind_cxx:
354 case langkind_cxx_cpp:
355 case langkind_objcxx:
356 case langkind_objcxx_cpp:
357 LangStd = lang_gnucxx98;
358 break;
359 }
360 }
361
362 switch (LangStd) {
363 default: assert(0 && "Unknown language standard!");
364
365 // Fall through from newer standards to older ones. This isn't really right.
366 // FIXME: Enable specifically the right features based on the language stds.
Chris Lattnerd4b80f12007-07-16 04:18:29 +0000367 case lang_gnucxx0x:
368 case lang_cxx0x:
369 Options.CPlusPlus0x = 1;
370 // FALL THROUGH
Reid Spencer5f016e22007-07-11 17:01:13 +0000371 case lang_gnucxx98:
372 case lang_cxx98:
373 Options.CPlusPlus = 1;
374 Options.CXXOperatorNames = !NoOperatorNames;
Nate Begeman8aebcb72007-11-15 07:30:50 +0000375 Options.Boolean = 1;
Reid Spencer5f016e22007-07-11 17:01:13 +0000376 // FALL THROUGH.
377 case lang_gnu99:
378 case lang_c99:
Reid Spencer5f016e22007-07-11 17:01:13 +0000379 Options.C99 = 1;
380 Options.HexFloats = 1;
381 // FALL THROUGH.
382 case lang_gnu89:
383 Options.BCPLComment = 1; // Only for C99/C++.
384 // FALL THROUGH.
385 case lang_c94:
Chris Lattner3426b9b2008-02-25 04:01:39 +0000386 Options.Digraphs = 1; // C94, C99, C++.
387 // FALL THROUGH.
Reid Spencer5f016e22007-07-11 17:01:13 +0000388 case lang_c89:
389 break;
390 }
391
392 Options.Trigraphs = 1; // -trigraphs or -ansi
393 Options.DollarIdents = 1; // FIXME: Really a target property.
Anders Carlssonee98ac52007-10-15 02:50:23 +0000394 Options.PascalStrings = PascalStrings;
Steve Naroffd62701b2008-02-07 03:50:06 +0000395 Options.Microsoft = MSExtensions;
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000396 Options.WritableStrings = WritableStrings;
Anders Carlsson695dbb62007-11-30 04:21:22 +0000397 Options.LaxVectorConversions = LaxVectorConversions;
Reid Spencer5f016e22007-07-11 17:01:13 +0000398}
399
400//===----------------------------------------------------------------------===//
401// Our DiagnosticClient implementation
402//===----------------------------------------------------------------------===//
403
404// FIXME: Werror should take a list of things, -Werror=foo,bar
405static llvm::cl::opt<bool>
406WarningsAsErrors("Werror", llvm::cl::desc("Treat all warnings as errors"));
407
408static llvm::cl::opt<bool>
409WarnOnExtensions("pedantic", llvm::cl::init(false),
410 llvm::cl::desc("Issue a warning on uses of GCC extensions"));
411
412static llvm::cl::opt<bool>
413ErrorOnExtensions("pedantic-errors",
414 llvm::cl::desc("Issue an error on uses of GCC extensions"));
415
416static llvm::cl::opt<bool>
417WarnUnusedMacros("Wunused_macros",
418 llvm::cl::desc("Warn for unused macros in the main translation unit"));
419
Ted Kremenekdb87bca2007-11-13 18:37:02 +0000420static llvm::cl::opt<bool>
421WarnFloatEqual("Wfloat-equal",
422 llvm::cl::desc("Warn about equality comparisons of floating point values."));
423
Ted Kremenek73da5902007-12-17 17:50:07 +0000424static llvm::cl::opt<bool>
425WarnNoFormatNonLiteral("Wno-format-nonliteral",
426 llvm::cl::desc("Do not warn about non-literal format strings."));
427
Chris Lattner116a4b12008-01-23 17:19:46 +0000428static llvm::cl::opt<bool>
429WarnUndefMacros("Wundef",
430 llvm::cl::desc("Warn on use of undefined macros in #if's"));
431
432
Reid Spencer5f016e22007-07-11 17:01:13 +0000433/// InitializeDiagnostics - Initialize the diagnostic object, based on the
434/// current command line option settings.
435static void InitializeDiagnostics(Diagnostic &Diags) {
436 Diags.setWarningsAsErrors(WarningsAsErrors);
437 Diags.setWarnOnExtensions(WarnOnExtensions);
438 Diags.setErrorOnExtensions(ErrorOnExtensions);
439
440 // Silence the "macro is not used" warning unless requested.
441 if (!WarnUnusedMacros)
442 Diags.setDiagnosticMapping(diag::pp_macro_not_used, diag::MAP_IGNORE);
Ted Kremenekdb87bca2007-11-13 18:37:02 +0000443
444 // Silence "floating point comparison" warnings unless requested.
445 if (!WarnFloatEqual)
446 Diags.setDiagnosticMapping(diag::warn_floatingpoint_eq, diag::MAP_IGNORE);
Ted Kremenek73da5902007-12-17 17:50:07 +0000447
448 // Silence "format string is not a string literal" warnings if requested
449 if (WarnNoFormatNonLiteral)
Ted Kremenek7c1d3df2007-12-17 17:50:39 +0000450 Diags.setDiagnosticMapping(diag::warn_printf_not_string_constant,
451 diag::MAP_IGNORE);
Chris Lattner116a4b12008-01-23 17:19:46 +0000452 if (!WarnUndefMacros)
453 Diags.setDiagnosticMapping(diag::warn_pp_undef_identifier,diag::MAP_IGNORE);
Steve Naroffe7a37302008-02-11 22:40:08 +0000454
455 if (MSExtensions) // MS allows unnamed struct/union fields.
456 Diags.setDiagnosticMapping(diag::w_no_declarators, diag::MAP_IGNORE);
Reid Spencer5f016e22007-07-11 17:01:13 +0000457}
458
459//===----------------------------------------------------------------------===//
Ted Kremenekcb330932008-02-18 21:21:23 +0000460// Analysis-specific options.
461//===----------------------------------------------------------------------===//
462
463static llvm::cl::opt<std::string>
464AnalyzeSpecificFunction("analyze-function",
465 llvm::cl::desc("Run analysis on specific function."));
466
Ted Kremenekffe0f432008-03-07 22:58:01 +0000467static llvm::cl::opt<bool>
468TrimGraph("trim-path-graph",
469 llvm::cl::desc("Only show error-related paths in the analysis graph."));
470
471
Ted Kremenekcb330932008-02-18 21:21:23 +0000472//===----------------------------------------------------------------------===//
Ted Kremenekae360762007-12-03 22:06:55 +0000473// Target Triple Processing.
474//===----------------------------------------------------------------------===//
475
476static llvm::cl::opt<std::string>
477TargetTriple("triple",
478 llvm::cl::desc("Specify target triple (e.g. i686-apple-darwin9)."));
479
Chris Lattner42e67372008-03-05 01:18:20 +0000480static llvm::cl::opt<std::string>
Chris Lattner6fd9fa12008-03-09 01:35:13 +0000481Arch("arch", llvm::cl::desc("Specify target architecture (e.g. i686)."));
Ted Kremenekae360762007-12-03 22:06:55 +0000482
Chris Lattner6fd9fa12008-03-09 01:35:13 +0000483static std::string CreateTargetTriple() {
Ted Kremenekae360762007-12-03 22:06:55 +0000484 // Initialize base triple. If a -triple option has been specified, use
485 // that triple. Otherwise, default to the host triple.
Chris Lattner6590d212007-12-12 05:01:48 +0000486 std::string Triple = TargetTriple;
487 if (Triple.empty()) Triple = LLVM_HOSTTRIPLE;
Ted Kremenekae360762007-12-03 22:06:55 +0000488
Chris Lattner6fd9fa12008-03-09 01:35:13 +0000489 // If -arch foo was specified, remove the architecture from the triple we have
490 // so far and replace it with the specified one.
491 if (Arch.empty())
492 return Triple;
493
Ted Kremenekae360762007-12-03 22:06:55 +0000494 // Decompose the base triple into "arch" and suffix.
Chris Lattner6fd9fa12008-03-09 01:35:13 +0000495 std::string::size_type FirstDashIdx = Triple.find("-");
Ted Kremenekae360762007-12-03 22:06:55 +0000496
Chris Lattner6fd9fa12008-03-09 01:35:13 +0000497 if (FirstDashIdx == std::string::npos) {
Ted Kremenek9b4ebc22007-12-03 22:11:31 +0000498 fprintf(stderr,
499 "Malformed target triple: \"%s\" ('-' could not be found).\n",
Chris Lattner6590d212007-12-12 05:01:48 +0000500 Triple.c_str());
501 exit(1);
Ted Kremenek9b4ebc22007-12-03 22:11:31 +0000502 }
Ted Kremenekae360762007-12-03 22:06:55 +0000503
Chris Lattner6fd9fa12008-03-09 01:35:13 +0000504 return Arch + std::string(Triple.begin()+FirstDashIdx, Triple.end());
Ted Kremenekae360762007-12-03 22:06:55 +0000505}
506
507//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +0000508// Preprocessor Initialization
509//===----------------------------------------------------------------------===//
510
511// FIXME: Preprocessor builtins to support.
512// -A... - Play with #assertions
513// -undef - Undefine all predefined macros
514
515static llvm::cl::list<std::string>
516D_macros("D", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
517 llvm::cl::desc("Predefine the specified macro"));
518static llvm::cl::list<std::string>
519U_macros("U", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
520 llvm::cl::desc("Undefine the specified macro"));
521
Chris Lattner64299f82008-01-10 01:53:41 +0000522static llvm::cl::list<std::string>
523ImplicitIncludes("include", llvm::cl::value_desc("file"),
524 llvm::cl::desc("Include file before parsing"));
525
526
Reid Spencer5f016e22007-07-11 17:01:13 +0000527// Append a #define line to Buf for Macro. Macro should be of the form XXX,
528// in which case we emit "#define XXX 1" or "XXX=Y z W" in which case we emit
529// "#define XXX Y z W". To get a #define with no value, use "XXX=".
530static void DefineBuiltinMacro(std::vector<char> &Buf, const char *Macro,
531 const char *Command = "#define ") {
532 Buf.insert(Buf.end(), Command, Command+strlen(Command));
533 if (const char *Equal = strchr(Macro, '=')) {
534 // Turn the = into ' '.
535 Buf.insert(Buf.end(), Macro, Equal);
536 Buf.push_back(' ');
537 Buf.insert(Buf.end(), Equal+1, Equal+strlen(Equal));
538 } else {
539 // Push "macroname 1".
540 Buf.insert(Buf.end(), Macro, Macro+strlen(Macro));
541 Buf.push_back(' ');
542 Buf.push_back('1');
543 }
544 Buf.push_back('\n');
545}
546
Chris Lattner64299f82008-01-10 01:53:41 +0000547/// AddImplicitInclude - Add an implicit #include of the specified file to the
548/// predefines buffer.
549static void AddImplicitInclude(std::vector<char> &Buf, const std::string &File){
550 const char *Inc = "#include \"";
551 Buf.insert(Buf.end(), Inc, Inc+strlen(Inc));
552 Buf.insert(Buf.end(), File.begin(), File.end());
553 Buf.push_back('"');
554 Buf.push_back('\n');
555}
556
Reid Spencer5f016e22007-07-11 17:01:13 +0000557
Chris Lattner53b0dab2007-10-09 22:10:18 +0000558/// InitializePreprocessor - Initialize the preprocessor getting it and the
559/// environment ready to process a single file. This returns the file ID for the
560/// input file. If a failure happens, it returns 0.
561///
562static unsigned InitializePreprocessor(Preprocessor &PP,
563 const std::string &InFile,
Chris Lattner53b0dab2007-10-09 22:10:18 +0000564 std::vector<char> &PredefineBuffer) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000565
Chris Lattnerdee73592007-12-15 20:48:40 +0000566 FileManager &FileMgr = PP.getFileManager();
Reid Spencer5f016e22007-07-11 17:01:13 +0000567
Chris Lattner53b0dab2007-10-09 22:10:18 +0000568 // Figure out where to get and map in the main file.
Chris Lattnerdee73592007-12-15 20:48:40 +0000569 SourceManager &SourceMgr = PP.getSourceManager();
Chris Lattner53b0dab2007-10-09 22:10:18 +0000570 if (InFile != "-") {
571 const FileEntry *File = FileMgr.getFile(InFile);
Ted Kremenek1036b682007-12-19 23:48:45 +0000572 if (File) SourceMgr.createMainFileID(File, SourceLocation());
573 if (SourceMgr.getMainFileID() == 0) {
Chris Lattner53b0dab2007-10-09 22:10:18 +0000574 fprintf(stderr, "Error reading '%s'!\n",InFile.c_str());
575 return 0;
576 }
577 } else {
578 llvm::MemoryBuffer *SB = llvm::MemoryBuffer::getSTDIN();
Ted Kremenek1036b682007-12-19 23:48:45 +0000579 if (SB) SourceMgr.createMainFileIDForMemBuffer(SB);
580 if (SourceMgr.getMainFileID() == 0) {
Chris Lattner53b0dab2007-10-09 22:10:18 +0000581 fprintf(stderr, "Error reading standard input! Empty?\n");
582 return 0;
583 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000584 }
585
Reid Spencer5f016e22007-07-11 17:01:13 +0000586 // Add macros from the command line.
587 // FIXME: Should traverse the #define/#undef lists in parallel.
588 for (unsigned i = 0, e = D_macros.size(); i != e; ++i)
Chris Lattner53b0dab2007-10-09 22:10:18 +0000589 DefineBuiltinMacro(PredefineBuffer, D_macros[i].c_str());
Reid Spencer5f016e22007-07-11 17:01:13 +0000590 for (unsigned i = 0, e = U_macros.size(); i != e; ++i)
Chris Lattner53b0dab2007-10-09 22:10:18 +0000591 DefineBuiltinMacro(PredefineBuffer, U_macros[i].c_str(), "#undef ");
592
Chris Lattner64299f82008-01-10 01:53:41 +0000593 // FIXME: Read any files specified by -imacros.
594
595 // Add implicit #includes from -include.
596 for (unsigned i = 0, e = ImplicitIncludes.size(); i != e; ++i)
597 AddImplicitInclude(PredefineBuffer, ImplicitIncludes[i]);
Chris Lattner53b0dab2007-10-09 22:10:18 +0000598
599 // Null terminate PredefinedBuffer and add it.
600 PredefineBuffer.push_back(0);
601 PP.setPredefines(&PredefineBuffer[0]);
602
603 // Once we've read this, we're done.
Ted Kremenek1036b682007-12-19 23:48:45 +0000604 return SourceMgr.getMainFileID();
Reid Spencer5f016e22007-07-11 17:01:13 +0000605}
606
607//===----------------------------------------------------------------------===//
608// Preprocessor include path information.
609//===----------------------------------------------------------------------===//
610
611// This tool exports a large number of command line options to control how the
612// preprocessor searches for header files. At root, however, the Preprocessor
613// object takes a very simple interface: a list of directories to search for
614//
615// FIXME: -nostdinc,-nostdinc++
Chris Lattner0c946412007-08-26 17:47:35 +0000616// FIXME: -imultilib
Reid Spencer5f016e22007-07-11 17:01:13 +0000617//
Chris Lattner64299f82008-01-10 01:53:41 +0000618// FIXME: -imacros
Reid Spencer5f016e22007-07-11 17:01:13 +0000619
620static llvm::cl::opt<bool>
621nostdinc("nostdinc", llvm::cl::desc("Disable standard #include directories"));
622
623// Various command line options. These four add directories to each chain.
624static llvm::cl::list<std::string>
625F_dirs("F", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
626 llvm::cl::desc("Add directory to framework include search path"));
627static llvm::cl::list<std::string>
628I_dirs("I", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
629 llvm::cl::desc("Add directory to include search path"));
630static llvm::cl::list<std::string>
631idirafter_dirs("idirafter", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
632 llvm::cl::desc("Add directory to AFTER include search path"));
633static llvm::cl::list<std::string>
634iquote_dirs("iquote", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
635 llvm::cl::desc("Add directory to QUOTE include search path"));
636static llvm::cl::list<std::string>
637isystem_dirs("isystem", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
638 llvm::cl::desc("Add directory to SYSTEM include search path"));
639
640// These handle -iprefix/-iwithprefix/-iwithprefixbefore.
641static llvm::cl::list<std::string>
642iprefix_vals("iprefix", llvm::cl::value_desc("prefix"), llvm::cl::Prefix,
643 llvm::cl::desc("Set the -iwithprefix/-iwithprefixbefore prefix"));
644static llvm::cl::list<std::string>
645iwithprefix_vals("iwithprefix", llvm::cl::value_desc("dir"), llvm::cl::Prefix,
646 llvm::cl::desc("Set directory to SYSTEM include search path with prefix"));
647static llvm::cl::list<std::string>
648iwithprefixbefore_vals("iwithprefixbefore", llvm::cl::value_desc("dir"),
649 llvm::cl::Prefix,
650 llvm::cl::desc("Set directory to include search path with prefix"));
651
Chris Lattner0c946412007-08-26 17:47:35 +0000652static llvm::cl::opt<std::string>
653isysroot("isysroot", llvm::cl::value_desc("dir"), llvm::cl::init("/"),
654 llvm::cl::desc("Set the system root directory (usually /)"));
655
Reid Spencer5f016e22007-07-11 17:01:13 +0000656// Finally, implement the code that groks the options above.
657enum IncludeDirGroup {
658 Quoted = 0,
659 Angled,
660 System,
661 After
662};
663
664static std::vector<DirectoryLookup> IncludeGroup[4];
665
666/// AddPath - Add the specified path to the specified group list.
667///
668static void AddPath(const std::string &Path, IncludeDirGroup Group,
669 bool isCXXAware, bool isUserSupplied,
Chris Lattner822da612007-12-17 06:36:45 +0000670 bool isFramework, HeaderSearch &HS) {
Chris Lattnerb3de9e72007-12-09 00:39:55 +0000671 assert(!Path.empty() && "can't handle empty path here");
Chris Lattner822da612007-12-17 06:36:45 +0000672 FileManager &FM = HS.getFileMgr();
Chris Lattnerb3de9e72007-12-09 00:39:55 +0000673
Chris Lattnerd6655272007-12-17 05:59:27 +0000674 // Compute the actual path, taking into consideration -isysroot.
675 llvm::SmallString<256> MappedPath;
Chris Lattner0c946412007-08-26 17:47:35 +0000676
Chris Lattnerd6655272007-12-17 05:59:27 +0000677 // Handle isysroot.
678 if (Group == System) {
Chris Lattner60e4e2b2007-12-17 06:51:34 +0000679 // FIXME: Portability. This should be a sys::Path interface, this doesn't
680 // handle things like C:\ right, nor win32 \\network\device\blah.
Chris Lattnerd6655272007-12-17 05:59:27 +0000681 if (isysroot.size() != 1 || isysroot[0] != '/') // Add isysroot if present.
682 MappedPath.append(isysroot.begin(), isysroot.end());
Reid Spencer5f016e22007-07-11 17:01:13 +0000683 }
684
Chris Lattnerd6655272007-12-17 05:59:27 +0000685 MappedPath.append(Path.begin(), Path.end());
686
687 // Compute the DirectoryLookup type.
Reid Spencer5f016e22007-07-11 17:01:13 +0000688 DirectoryLookup::DirType Type;
689 if (Group == Quoted || Group == Angled)
690 Type = DirectoryLookup::NormalHeaderDir;
691 else if (isCXXAware)
692 Type = DirectoryLookup::SystemHeaderDir;
693 else
694 Type = DirectoryLookup::ExternCSystemHeaderDir;
695
Chris Lattnerd6655272007-12-17 05:59:27 +0000696
697 // If the directory exists, add it.
698 if (const DirectoryEntry *DE = FM.getDirectory(&MappedPath[0],
699 &MappedPath[0]+
700 MappedPath.size())) {
701 IncludeGroup[Group].push_back(DirectoryLookup(DE, Type, isUserSupplied,
702 isFramework));
703 return;
704 }
705
Chris Lattnerdf772332007-12-17 07:52:39 +0000706 // Check to see if this is an apple-style headermap (which are not allowed to
707 // be frameworks).
708 if (!isFramework) {
709 if (const FileEntry *FE = FM.getFile(&MappedPath[0],
710 &MappedPath[0]+MappedPath.size())) {
Chris Lattner1bfd4a62007-12-17 18:34:53 +0000711 if (const HeaderMap *HM = HS.CreateHeaderMap(FE)) {
712 // It is a headermap, add it to the search path.
Chris Lattnerdf772332007-12-17 07:52:39 +0000713 IncludeGroup[Group].push_back(DirectoryLookup(HM, Type,isUserSupplied));
714 return;
715 }
Chris Lattner822da612007-12-17 06:36:45 +0000716 }
717 }
718
Chris Lattnerd6655272007-12-17 05:59:27 +0000719 if (Verbose)
720 fprintf(stderr, "ignoring nonexistent directory \"%s\"\n", Path.c_str());
Reid Spencer5f016e22007-07-11 17:01:13 +0000721}
722
723/// RemoveDuplicates - If there are duplicate directory entries in the specified
724/// search list, remove the later (dead) ones.
725static void RemoveDuplicates(std::vector<DirectoryLookup> &SearchList) {
Chris Lattner8f3dab82007-12-15 23:20:07 +0000726 llvm::SmallPtrSet<const DirectoryEntry *, 8> SeenDirs;
Chris Lattnerdf772332007-12-17 07:52:39 +0000727 llvm::SmallPtrSet<const DirectoryEntry *, 8> SeenFrameworkDirs;
Chris Lattnerb94c7072007-12-17 06:44:29 +0000728 llvm::SmallPtrSet<const HeaderMap *, 8> SeenHeaderMaps;
Reid Spencer5f016e22007-07-11 17:01:13 +0000729 for (unsigned i = 0; i != SearchList.size(); ++i) {
Chris Lattnerb94c7072007-12-17 06:44:29 +0000730 if (SearchList[i].isNormalDir()) {
731 // If this isn't the first time we've seen this dir, remove it.
732 if (SeenDirs.insert(SearchList[i].getDir()))
733 continue;
734
Reid Spencer5f016e22007-07-11 17:01:13 +0000735 if (Verbose)
736 fprintf(stderr, "ignoring duplicate directory \"%s\"\n",
737 SearchList[i].getDir()->getName());
Chris Lattnerdf772332007-12-17 07:52:39 +0000738 } else if (SearchList[i].isFramework()) {
739 // If this isn't the first time we've seen this framework dir, remove it.
740 if (SeenFrameworkDirs.insert(SearchList[i].getFrameworkDir()))
741 continue;
742
743 if (Verbose)
744 fprintf(stderr, "ignoring duplicate framework \"%s\"\n",
745 SearchList[i].getFrameworkDir()->getName());
746
Chris Lattnerb94c7072007-12-17 06:44:29 +0000747 } else {
748 assert(SearchList[i].isHeaderMap() && "Not a headermap or normal dir?");
749 // If this isn't the first time we've seen this headermap, remove it.
750 if (SeenHeaderMaps.insert(SearchList[i].getHeaderMap()))
751 continue;
752
753 if (Verbose)
754 fprintf(stderr, "ignoring duplicate directory \"%s\"\n",
755 SearchList[i].getDir()->getName());
Reid Spencer5f016e22007-07-11 17:01:13 +0000756 }
Chris Lattnerb94c7072007-12-17 06:44:29 +0000757
758 // This is reached if the current entry is a duplicate.
759 SearchList.erase(SearchList.begin()+i);
760 --i;
Reid Spencer5f016e22007-07-11 17:01:13 +0000761 }
762}
763
Chris Lattner5f9eae52008-03-01 08:07:28 +0000764// AddEnvVarPaths - Add a list of paths from an environment variable to a
765// header search list.
766//
767static void AddEnvVarPaths(const char *Name, HeaderSearch &Headers) {
768 const char* at = getenv(Name);
769 if (!at)
770 return;
771
772 const char* delim = strchr(at, llvm::sys::PathSeparator);
773 while (delim != 0) {
774 if (delim-at == 0)
775 AddPath(".", Angled, false, true, false, Headers);
776 else
777 AddPath(std::string(at, std::string::size_type(delim-at)), Angled, false,
778 true, false, Headers);
779 at = delim + 1;
780 delim = strchr(at, llvm::sys::PathSeparator);
781 }
782 if (*at == 0)
783 AddPath(".", Angled, false, true, false, Headers);
784 else
785 AddPath(at, Angled, false, true, false, Headers);
786}
787
Reid Spencer5f016e22007-07-11 17:01:13 +0000788/// InitializeIncludePaths - Process the -I options and set them in the
789/// HeaderSearch object.
Chris Lattnerdcaa0962008-03-03 03:16:03 +0000790static void InitializeIncludePaths(const char *Argv0, HeaderSearch &Headers,
791 FileManager &FM, const LangOptions &Lang) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000792 // Handle -F... options.
793 for (unsigned i = 0, e = F_dirs.size(); i != e; ++i)
Chris Lattner822da612007-12-17 06:36:45 +0000794 AddPath(F_dirs[i], Angled, false, true, true, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000795
796 // Handle -I... options.
Chris Lattner4f037832007-12-05 23:24:17 +0000797 for (unsigned i = 0, e = I_dirs.size(); i != e; ++i)
Chris Lattner822da612007-12-17 06:36:45 +0000798 AddPath(I_dirs[i], Angled, false, true, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000799
800 // Handle -idirafter... options.
801 for (unsigned i = 0, e = idirafter_dirs.size(); i != e; ++i)
Chris Lattner822da612007-12-17 06:36:45 +0000802 AddPath(idirafter_dirs[i], After, false, true, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000803
804 // Handle -iquote... options.
805 for (unsigned i = 0, e = iquote_dirs.size(); i != e; ++i)
Chris Lattner822da612007-12-17 06:36:45 +0000806 AddPath(iquote_dirs[i], Quoted, false, true, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000807
808 // Handle -isystem... options.
809 for (unsigned i = 0, e = isystem_dirs.size(); i != e; ++i)
Chris Lattner822da612007-12-17 06:36:45 +0000810 AddPath(isystem_dirs[i], System, false, true, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000811
812 // Walk the -iprefix/-iwithprefix/-iwithprefixbefore argument lists in
813 // parallel, processing the values in order of occurance to get the right
814 // prefixes.
815 {
816 std::string Prefix = ""; // FIXME: this isn't the correct default prefix.
817 unsigned iprefix_idx = 0;
818 unsigned iwithprefix_idx = 0;
819 unsigned iwithprefixbefore_idx = 0;
820 bool iprefix_done = iprefix_vals.empty();
821 bool iwithprefix_done = iwithprefix_vals.empty();
822 bool iwithprefixbefore_done = iwithprefixbefore_vals.empty();
823 while (!iprefix_done || !iwithprefix_done || !iwithprefixbefore_done) {
824 if (!iprefix_done &&
825 (iwithprefix_done ||
826 iprefix_vals.getPosition(iprefix_idx) <
827 iwithprefix_vals.getPosition(iwithprefix_idx)) &&
828 (iwithprefixbefore_done ||
829 iprefix_vals.getPosition(iprefix_idx) <
830 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
831 Prefix = iprefix_vals[iprefix_idx];
832 ++iprefix_idx;
833 iprefix_done = iprefix_idx == iprefix_vals.size();
834 } else if (!iwithprefix_done &&
835 (iwithprefixbefore_done ||
836 iwithprefix_vals.getPosition(iwithprefix_idx) <
837 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
838 AddPath(Prefix+iwithprefix_vals[iwithprefix_idx],
Chris Lattner822da612007-12-17 06:36:45 +0000839 System, false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000840 ++iwithprefix_idx;
841 iwithprefix_done = iwithprefix_idx == iwithprefix_vals.size();
842 } else {
843 AddPath(Prefix+iwithprefixbefore_vals[iwithprefixbefore_idx],
Chris Lattner822da612007-12-17 06:36:45 +0000844 Angled, false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000845 ++iwithprefixbefore_idx;
846 iwithprefixbefore_done =
847 iwithprefixbefore_idx == iwithprefixbefore_vals.size();
848 }
849 }
850 }
Chris Lattner5f9eae52008-03-01 08:07:28 +0000851
852 AddEnvVarPaths("CPATH", Headers);
853 if (Lang.CPlusPlus && Lang.ObjC1)
854 AddEnvVarPaths("OBJCPLUS_INCLUDE_PATH", Headers);
855 else if (Lang.CPlusPlus)
856 AddEnvVarPaths("CPLUS_INCLUDE_PATH", Headers);
857 else if (Lang.ObjC1)
858 AddEnvVarPaths("OBJC_INCLUDE_PATH", Headers);
859 else
860 AddEnvVarPaths("C_INCLUDE_PATH", Headers);
861
Chris Lattnerdcaa0962008-03-03 03:16:03 +0000862 // Add the clang headers, which are relative to the clang driver.
863 llvm::sys::Path MainExecutablePath =
Chris Lattner985e1822008-03-03 05:57:43 +0000864 llvm::sys::Path::GetMainExecutable(Argv0,
865 (void*)(intptr_t)InitializeIncludePaths);
Chris Lattnerdcaa0962008-03-03 03:16:03 +0000866 if (!MainExecutablePath.isEmpty()) {
867 MainExecutablePath.eraseComponent(); // Remove /clang from foo/bin/clang
868 MainExecutablePath.eraseComponent(); // Remove /bin from foo/bin
869 MainExecutablePath.appendComponent("Headers"); // Get foo/Headers
870 AddPath(MainExecutablePath.c_str(), System, false, false, false, Headers);
871 }
872
Reid Spencer5f016e22007-07-11 17:01:13 +0000873 // FIXME: temporary hack: hard-coded paths.
874 // FIXME: get these from the target?
875 if (!nostdinc) {
876 if (Lang.CPlusPlus) {
Chris Lattner822da612007-12-17 06:36:45 +0000877 AddPath("/usr/include/c++/4.0.0", System, true, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000878 AddPath("/usr/include/c++/4.0.0/i686-apple-darwin8", System, true, false,
Chris Lattner822da612007-12-17 06:36:45 +0000879 false, Headers);
880 AddPath("/usr/include/c++/4.0.0/backward", System, true, false, false,
881 Headers);
Lauro Ramos Venancioa6743492008-02-15 22:36:38 +0000882
883 // Ubuntu 7.10 - Gutsy Gibbon
884 AddPath("/usr/include/c++/4.1.3", System, true, false, false, Headers);
885 AddPath("/usr/include/c++/4.1.3/i486-linux-gnu", System, true, false,
886 false, Headers);
887 AddPath("/usr/include/c++/4.1.3/backward", System, true, false, false,
888 Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000889 }
890
Chris Lattner822da612007-12-17 06:36:45 +0000891 AddPath("/usr/local/include", System, false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000892 // leopard
893 AddPath("/usr/lib/gcc/i686-apple-darwin9/4.0.1/include", System,
Chris Lattner822da612007-12-17 06:36:45 +0000894 false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000895 AddPath("/usr/lib/gcc/powerpc-apple-darwin9/4.0.1/include",
Chris Lattner822da612007-12-17 06:36:45 +0000896 System, false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000897 AddPath("/usr/lib/gcc/powerpc-apple-darwin9/"
898 "4.0.1/../../../../powerpc-apple-darwin0/include",
Chris Lattner822da612007-12-17 06:36:45 +0000899 System, false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000900
901 // tiger
902 AddPath("/usr/lib/gcc/i686-apple-darwin8/4.0.1/include", System,
Chris Lattner822da612007-12-17 06:36:45 +0000903 false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000904 AddPath("/usr/lib/gcc/powerpc-apple-darwin8/4.0.1/include",
Chris Lattner822da612007-12-17 06:36:45 +0000905 System, false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000906 AddPath("/usr/lib/gcc/powerpc-apple-darwin8/"
907 "4.0.1/../../../../powerpc-apple-darwin8/include",
Chris Lattner822da612007-12-17 06:36:45 +0000908 System, false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000909
Lauro Ramos Venancio397cbf22008-01-21 23:08:35 +0000910 // Ubuntu 7.10 - Gutsy Gibbon
911 AddPath("/usr/lib/gcc/i486-linux-gnu/4.1.3/include", System,
Chris Lattnerc81c8142008-02-25 21:04:36 +0000912 false, false, false, Headers);
Lauro Ramos Venancio397cbf22008-01-21 23:08:35 +0000913
Chris Lattner822da612007-12-17 06:36:45 +0000914 AddPath("/usr/include", System, false, false, false, Headers);
915 AddPath("/System/Library/Frameworks", System, true, false, true, Headers);
916 AddPath("/Library/Frameworks", System, true, false, true, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000917 }
918
919 // Now that we have collected all of the include paths, merge them all
920 // together and tell the preprocessor about them.
921
922 // Concatenate ANGLE+SYSTEM+AFTER chains together into SearchList.
923 std::vector<DirectoryLookup> SearchList;
924 SearchList = IncludeGroup[Angled];
925 SearchList.insert(SearchList.end(), IncludeGroup[System].begin(),
926 IncludeGroup[System].end());
927 SearchList.insert(SearchList.end(), IncludeGroup[After].begin(),
928 IncludeGroup[After].end());
929 RemoveDuplicates(SearchList);
930 RemoveDuplicates(IncludeGroup[Quoted]);
931
932 // Prepend QUOTED list on the search list.
933 SearchList.insert(SearchList.begin(), IncludeGroup[Quoted].begin(),
934 IncludeGroup[Quoted].end());
935
936
937 bool DontSearchCurDir = false; // TODO: set to true if -I- is set?
938 Headers.SetSearchPaths(SearchList, IncludeGroup[Quoted].size(),
939 DontSearchCurDir);
940
941 // If verbose, print the list of directories that will be searched.
942 if (Verbose) {
943 fprintf(stderr, "#include \"...\" search starts here:\n");
944 unsigned QuotedIdx = IncludeGroup[Quoted].size();
945 for (unsigned i = 0, e = SearchList.size(); i != e; ++i) {
946 if (i == QuotedIdx)
947 fprintf(stderr, "#include <...> search starts here:\n");
Chris Lattner3af66a92007-12-17 17:57:27 +0000948 const char *Name = SearchList[i].getName();
949 const char *Suffix;
Chris Lattner0048b512007-12-17 17:42:26 +0000950 if (SearchList[i].isNormalDir())
Chris Lattner3af66a92007-12-17 17:57:27 +0000951 Suffix = "";
Chris Lattner0048b512007-12-17 17:42:26 +0000952 else if (SearchList[i].isFramework())
Chris Lattner3af66a92007-12-17 17:57:27 +0000953 Suffix = " (framework directory)";
Chris Lattner0048b512007-12-17 17:42:26 +0000954 else {
955 assert(SearchList[i].isHeaderMap() && "Unknown DirectoryLookup");
Chris Lattner3af66a92007-12-17 17:57:27 +0000956 Suffix = " (headermap)";
Chris Lattner0048b512007-12-17 17:42:26 +0000957 }
Chris Lattner3af66a92007-12-17 17:57:27 +0000958 fprintf(stderr, " %s%s\n", Name, Suffix);
Reid Spencer5f016e22007-07-11 17:01:13 +0000959 }
Chris Lattner80e17152007-12-15 23:11:06 +0000960 fprintf(stderr, "End of search list.\n");
Reid Spencer5f016e22007-07-11 17:01:13 +0000961 }
962}
963
964
Reid Spencer5f016e22007-07-11 17:01:13 +0000965//===----------------------------------------------------------------------===//
966// Basic Parser driver
967//===----------------------------------------------------------------------===//
968
Ted Kremenek95041a22007-12-19 22:51:13 +0000969static void ParseFile(Preprocessor &PP, MinimalAction *PA){
Reid Spencer5f016e22007-07-11 17:01:13 +0000970 Parser P(PP, *PA);
Ted Kremenek95041a22007-12-19 22:51:13 +0000971 PP.EnterMainSourceFile();
Reid Spencer5f016e22007-07-11 17:01:13 +0000972
973 // Parsing the specified input file.
974 P.ParseTranslationUnit();
975 delete PA;
976}
977
978//===----------------------------------------------------------------------===//
979// Main driver
980//===----------------------------------------------------------------------===//
981
Ted Kremenekdb094a22007-12-05 18:27:04 +0000982/// CreateASTConsumer - Create the ASTConsumer for the corresponding program
983/// action. These consumers can operate on both ASTs that are freshly
984/// parsed from source files as well as those deserialized from Bitcode.
Ted Kremenekfdfc1982007-12-19 22:24:34 +0000985static ASTConsumer* CreateASTConsumer(const std::string& InFile,
Ted Kremeneka1fa3a12007-12-13 00:37:31 +0000986 Diagnostic& Diag, FileManager& FileMgr,
Chris Lattnere66b65c2008-02-06 01:42:25 +0000987 const LangOptions& LangOpts,
988 llvm::Module *&DestModule) {
Ted Kremenekdb094a22007-12-05 18:27:04 +0000989 switch (ProgAction) {
990 default:
991 return NULL;
992
993 case ASTPrint:
994 return CreateASTPrinter();
995
996 case ASTDump:
997 return CreateASTDumper();
998
999 case ASTView:
Ted Kremenek6a340832008-03-18 21:19:49 +00001000 return CreateASTViewer();
1001
1002 case EmitHTML:
1003 return CreateHTMLPrinter();
Ted Kremenekdb094a22007-12-05 18:27:04 +00001004
1005 case ParseCFGDump:
1006 case ParseCFGView:
Ted Kremenek5f39c2d2008-02-22 20:00:31 +00001007 return CreateCFGDumper(ProgAction == ParseCFGView,
1008 AnalyzeSpecificFunction);
Ted Kremenekdb094a22007-12-05 18:27:04 +00001009
1010 case AnalysisLiveVariables:
Ted Kremenekbfc10c92008-02-22 20:13:09 +00001011 return CreateLiveVarAnalyzer(AnalyzeSpecificFunction);
Ted Kremenekdb094a22007-12-05 18:27:04 +00001012
1013 case WarnDeadStores:
1014 return CreateDeadStoreChecker(Diag);
1015
1016 case WarnUninitVals:
1017 return CreateUnitValsChecker(Diag);
1018
Ted Kremeneke01c9872008-02-14 22:36:46 +00001019 case AnalysisGRSimpleVals:
Ted Kremenekcb330932008-02-18 21:21:23 +00001020 return CreateGRSimpleVals(Diag, AnalyzeSpecificFunction);
Ted Kremeneke603df42008-01-08 18:04:06 +00001021
Ted Kremenekd55fe522008-02-15 00:35:38 +00001022 case AnalysisGRSimpleValsView:
Ted Kremenekffe0f432008-03-07 22:58:01 +00001023 return CreateGRSimpleVals(Diag, AnalyzeSpecificFunction, true, TrimGraph);
Ted Kremenekd55fe522008-02-15 00:35:38 +00001024
Ted Kremenek2fff37e2008-03-06 00:08:09 +00001025 case CheckerCFRef:
1026 return CreateCFRefChecker(Diag, AnalyzeSpecificFunction);
1027
Ted Kremenekdb094a22007-12-05 18:27:04 +00001028 case TestSerialization:
Ted Kremenekfdfc1982007-12-19 22:24:34 +00001029 return CreateSerializationTest(Diag, FileMgr, LangOpts);
Ted Kremenekdb094a22007-12-05 18:27:04 +00001030
1031 case EmitLLVM:
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +00001032 case EmitBC:
Chris Lattnere66b65c2008-02-06 01:42:25 +00001033 DestModule = new llvm::Module(InFile);
1034 return CreateLLVMCodeGen(Diag, LangOpts, DestModule);
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +00001035
Ted Kremenek3910c7c2007-12-19 17:25:59 +00001036 case SerializeAST:
Ted Kremeneka1fa3a12007-12-13 00:37:31 +00001037 // FIXME: Allow user to tailor where the file is written.
Ted Kremenek1036b682007-12-19 23:48:45 +00001038 return CreateASTSerializer(InFile, OutputFile, Diag, LangOpts);
Ted Kremeneka1fa3a12007-12-13 00:37:31 +00001039
Ted Kremenekdb094a22007-12-05 18:27:04 +00001040 case RewriteTest:
Steve Naroff4f943c22008-03-10 20:43:59 +00001041 return CreateCodeRewriterTest(InFile, Diag, LangOpts);
Ted Kremenekdb094a22007-12-05 18:27:04 +00001042 }
1043}
1044
Reid Spencer5f016e22007-07-11 17:01:13 +00001045/// ProcessInputFile - Process a single input file with the specified state.
1046///
Ted Kremenek7dcc9682007-12-19 22:32:34 +00001047static void ProcessInputFile(Preprocessor &PP, const std::string &InFile,
Chris Lattnerdee73592007-12-15 20:48:40 +00001048 TextDiagnostics &OurDiagnosticClient) {
Ted Kremenekd39bcd82007-09-26 18:39:29 +00001049
1050 ASTConsumer* Consumer = NULL;
Chris Lattnerbd247762007-07-22 06:05:44 +00001051 bool ClearSourceMgr = false;
Chris Lattnere66b65c2008-02-06 01:42:25 +00001052 llvm::Module *CodeGenModule = 0;
Ted Kremenekd39bcd82007-09-26 18:39:29 +00001053
Reid Spencer5f016e22007-07-11 17:01:13 +00001054 switch (ProgAction) {
1055 default:
Ted Kremenekfdfc1982007-12-19 22:24:34 +00001056 Consumer = CreateASTConsumer(InFile,
1057 PP.getDiagnostics(),
Chris Lattnerdee73592007-12-15 20:48:40 +00001058 PP.getFileManager(),
Chris Lattnere66b65c2008-02-06 01:42:25 +00001059 PP.getLangOptions(),
1060 CodeGenModule);
Ted Kremenekdb094a22007-12-05 18:27:04 +00001061
1062 if (!Consumer) {
1063 fprintf(stderr, "Unexpected program action!\n");
1064 return;
1065 }
Ted Kremenekfdfc1982007-12-19 22:24:34 +00001066
Ted Kremenekdb094a22007-12-05 18:27:04 +00001067 break;
1068
Reid Spencer5f016e22007-07-11 17:01:13 +00001069 case DumpTokens: { // Token dump mode.
Chris Lattnerd2177732007-07-20 16:59:19 +00001070 Token Tok;
Reid Spencer5f016e22007-07-11 17:01:13 +00001071 // Start parsing the specified input file.
Ted Kremenek95041a22007-12-19 22:51:13 +00001072 PP.EnterMainSourceFile();
Reid Spencer5f016e22007-07-11 17:01:13 +00001073 do {
1074 PP.Lex(Tok);
1075 PP.DumpToken(Tok, true);
1076 fprintf(stderr, "\n");
Chris Lattner057aaf62007-10-09 18:03:42 +00001077 } while (Tok.isNot(tok::eof));
Chris Lattnerbd247762007-07-22 06:05:44 +00001078 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001079 break;
1080 }
1081 case RunPreprocessorOnly: { // Just lex as fast as we can, no output.
Chris Lattnerd2177732007-07-20 16:59:19 +00001082 Token Tok;
Reid Spencer5f016e22007-07-11 17:01:13 +00001083 // Start parsing the specified input file.
Ted Kremenek95041a22007-12-19 22:51:13 +00001084 PP.EnterMainSourceFile();
Reid Spencer5f016e22007-07-11 17:01:13 +00001085 do {
1086 PP.Lex(Tok);
Chris Lattner057aaf62007-10-09 18:03:42 +00001087 } while (Tok.isNot(tok::eof));
Chris Lattnerbd247762007-07-22 06:05:44 +00001088 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001089 break;
1090 }
1091
1092 case PrintPreprocessedInput: // -E mode.
Chris Lattnere988bc22008-01-27 23:55:11 +00001093 DoPrintPreprocessedInput(PP, OutputFile);
Chris Lattnerbd247762007-07-22 06:05:44 +00001094 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001095 break;
1096
1097 case ParseNoop: // -parse-noop
Ted Kremenek95041a22007-12-19 22:51:13 +00001098 ParseFile(PP, new MinimalAction(PP.getIdentifierTable()));
Chris Lattnerbd247762007-07-22 06:05:44 +00001099 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001100 break;
1101
1102 case ParsePrintCallbacks:
Ted Kremenek95041a22007-12-19 22:51:13 +00001103 ParseFile(PP, CreatePrintParserActionsAction(PP.getIdentifierTable()));
Chris Lattnerbd247762007-07-22 06:05:44 +00001104 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001105 break;
Ted Kremenek44579782007-09-25 18:37:20 +00001106
Ted Kremenekd39bcd82007-09-26 18:39:29 +00001107 case ParseSyntaxOnly: // -fsyntax-only
Ted Kremenekd39bcd82007-09-26 18:39:29 +00001108 Consumer = new ASTConsumer();
Ted Kremenek2bf55142007-09-17 20:49:30 +00001109 break;
Chris Lattner580980b2007-09-16 19:46:59 +00001110 }
Ted Kremenekd39bcd82007-09-26 18:39:29 +00001111
1112 if (Consumer) {
Ted Kremenek9f3d9422007-09-26 20:14:22 +00001113 if (VerifyDiagnostics)
Ted Kremenek95041a22007-12-19 22:51:13 +00001114 exit(CheckASTConsumer(PP, Consumer));
Chris Lattner31e6c7d2007-11-03 06:24:16 +00001115
1116 // This deletes Consumer.
Ted Kremenek95041a22007-12-19 22:51:13 +00001117 ParseAST(PP, Consumer, Stats);
Reid Spencer5f016e22007-07-11 17:01:13 +00001118 }
Chris Lattnere66b65c2008-02-06 01:42:25 +00001119
1120 // If running the code generator, finish up now.
1121 if (CodeGenModule) {
1122 std::ostream *Out;
1123 if (OutputFile == "-") {
1124 Out = llvm::cout.stream();
1125 } else if (!OutputFile.empty()) {
1126 Out = new std::ofstream(OutputFile.c_str(),
1127 std::ios_base::binary|std::ios_base::out);
1128 } else if (InFile == "-") {
1129 Out = llvm::cout.stream();
1130 } else {
1131 llvm::sys::Path Path(InFile);
1132 Path.eraseSuffix();
1133 if (ProgAction == EmitLLVM)
1134 Path.appendSuffix("ll");
1135 else if (ProgAction == EmitBC)
1136 Path.appendSuffix("bc");
1137 else
1138 assert(0 && "Unknown action");
1139 Out = new std::ofstream(Path.toString().c_str(),
1140 std::ios_base::binary|std::ios_base::out);
1141 }
1142
1143 if (ProgAction == EmitLLVM) {
1144 CodeGenModule->print(*Out);
1145 } else {
1146 assert(ProgAction == EmitBC);
1147 llvm::WriteBitcodeToFile(CodeGenModule, *Out);
1148 }
1149
1150 if (Out != llvm::cout.stream())
1151 delete Out;
1152 delete CodeGenModule;
1153 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001154
1155 if (Stats) {
Ted Kremenekfdfc1982007-12-19 22:24:34 +00001156 fprintf(stderr, "\nSTATISTICS FOR '%s':\n", InFile.c_str());
Reid Spencer5f016e22007-07-11 17:01:13 +00001157 PP.PrintStats();
1158 PP.getIdentifierTable().PrintStats();
Chris Lattnerdee73592007-12-15 20:48:40 +00001159 PP.getHeaderSearchInfo().PrintStats();
Chris Lattnerbd247762007-07-22 06:05:44 +00001160 if (ClearSourceMgr)
Chris Lattnerdee73592007-12-15 20:48:40 +00001161 PP.getSourceManager().PrintStats();
Reid Spencer5f016e22007-07-11 17:01:13 +00001162 fprintf(stderr, "\n");
1163 }
Chris Lattnerbd247762007-07-22 06:05:44 +00001164
1165 // For a multi-file compilation, some things are ok with nuking the source
1166 // manager tables, other require stable fileid/macroid's across multiple
1167 // files.
Chris Lattnerdee73592007-12-15 20:48:40 +00001168 if (ClearSourceMgr)
1169 PP.getSourceManager().clearIDTables();
Reid Spencer5f016e22007-07-11 17:01:13 +00001170}
1171
Ted Kremenek20e97482007-12-12 23:41:08 +00001172static void ProcessSerializedFile(const std::string& InFile, Diagnostic& Diag,
1173 FileManager& FileMgr) {
1174
1175 if (VerifyDiagnostics) {
1176 fprintf(stderr, "-verify does not yet work with serialized ASTs.\n");
1177 exit (1);
1178 }
1179
1180 llvm::sys::Path Filename(InFile);
1181
1182 if (!Filename.isValid()) {
1183 fprintf(stderr, "serialized file '%s' not available.\n",InFile.c_str());
1184 exit (1);
1185 }
1186
Ted Kremenekee533642007-12-20 19:47:16 +00001187 llvm::OwningPtr<TranslationUnit> TU(ReadASTBitcodeFile(Filename,FileMgr));
Ted Kremenekfe4e0152007-12-13 18:11:11 +00001188
1189 if (!TU) {
1190 fprintf(stderr, "error: file '%s' could not be deserialized\n",
1191 InFile.c_str());
1192 exit (1);
1193 }
1194
Ted Kremenek63ea8632007-12-19 19:27:38 +00001195 // Observe that we use the source file name stored in the deserialized
1196 // translation unit, rather than InFile.
Chris Lattnere66b65c2008-02-06 01:42:25 +00001197 llvm::Module *DestModule;
Ted Kremenekee533642007-12-20 19:47:16 +00001198 llvm::OwningPtr<ASTConsumer>
Chris Lattnere66b65c2008-02-06 01:42:25 +00001199 Consumer(CreateASTConsumer(InFile, Diag, FileMgr, TU->getLangOpts(),
1200 DestModule));
Ted Kremenek20e97482007-12-12 23:41:08 +00001201
1202 if (!Consumer) {
1203 fprintf(stderr, "Unsupported program action with serialized ASTs!\n");
1204 exit (1);
1205 }
1206
Ted Kremenek95041a22007-12-19 22:51:13 +00001207 Consumer->Initialize(*TU->getContext());
Ted Kremenek20e97482007-12-12 23:41:08 +00001208
Chris Lattnere66b65c2008-02-06 01:42:25 +00001209 // FIXME: We need to inform Consumer about completed TagDecls as well.
Ted Kremenek20e97482007-12-12 23:41:08 +00001210 for (TranslationUnit::iterator I=TU->begin(), E=TU->end(); I!=E; ++I)
1211 Consumer->HandleTopLevelDecl(*I);
Ted Kremenek20e97482007-12-12 23:41:08 +00001212}
1213
1214
Reid Spencer5f016e22007-07-11 17:01:13 +00001215static llvm::cl::list<std::string>
1216InputFilenames(llvm::cl::Positional, llvm::cl::desc("<input files>"));
1217
Ted Kremenek20e97482007-12-12 23:41:08 +00001218static bool isSerializedFile(const std::string& InFile) {
1219 if (InFile.size() < 4)
1220 return false;
1221
1222 const char* s = InFile.c_str()+InFile.size()-4;
1223
1224 return s[0] == '.' &&
1225 s[1] == 'a' &&
1226 s[2] == 's' &&
1227 s[3] == 't';
1228}
1229
Reid Spencer5f016e22007-07-11 17:01:13 +00001230
1231int main(int argc, char **argv) {
Chris Lattnerdcaa0962008-03-03 03:16:03 +00001232 llvm::cl::ParseCommandLineOptions(argc, argv, " llvm clang cfe\n");
Reid Spencer5f016e22007-07-11 17:01:13 +00001233 llvm::sys::PrintStackTraceOnErrorSignal();
1234
1235 // If no input was specified, read from stdin.
1236 if (InputFilenames.empty())
1237 InputFilenames.push_back("-");
Ted Kremenek31e703b2007-12-11 23:28:38 +00001238
Reid Spencer5f016e22007-07-11 17:01:13 +00001239 // Create a file manager object to provide access to and cache the filesystem.
1240 FileManager FileMgr;
1241
Ted Kremenek31e703b2007-12-11 23:28:38 +00001242 // Create the diagnostic client for reporting errors or for
1243 // implementing -verify.
Reid Spencer5f016e22007-07-11 17:01:13 +00001244 std::auto_ptr<TextDiagnostics> DiagClient;
Ted Kremenek9f3d9422007-09-26 20:14:22 +00001245 if (!VerifyDiagnostics) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001246 // Print diagnostics to stderr by default.
Ted Kremenek7a9d49f2007-12-11 21:27:55 +00001247 DiagClient.reset(new TextDiagnosticPrinter());
Reid Spencer5f016e22007-07-11 17:01:13 +00001248 } else {
1249 // When checking diagnostics, just buffer them up.
Ted Kremenek7a9d49f2007-12-11 21:27:55 +00001250 DiagClient.reset(new TextDiagnosticBuffer());
Reid Spencer5f016e22007-07-11 17:01:13 +00001251
1252 if (InputFilenames.size() != 1) {
1253 fprintf(stderr,
Ted Kremenek9f3d9422007-09-26 20:14:22 +00001254 "-verify only works on single input files for now.\n");
Reid Spencer5f016e22007-07-11 17:01:13 +00001255 return 1;
1256 }
1257 }
1258
1259 // Configure our handling of diagnostics.
1260 Diagnostic Diags(*DiagClient);
Ted Kremenek31e703b2007-12-11 23:28:38 +00001261 InitializeDiagnostics(Diags);
1262
Chris Lattner4f037832007-12-05 23:24:17 +00001263 // -I- is a deprecated GCC feature, scan for it and reject it.
1264 for (unsigned i = 0, e = I_dirs.size(); i != e; ++i) {
1265 if (I_dirs[i] == "-") {
Ted Kremenek2eefd862007-12-11 22:57:35 +00001266 Diags.Report(diag::err_pp_I_dash_not_supported);
Chris Lattner4f037832007-12-05 23:24:17 +00001267 I_dirs.erase(I_dirs.begin()+i);
1268 --i;
1269 }
1270 }
Chris Lattner11215192008-03-14 06:12:05 +00001271
1272 // Get information about the target being compiled for.
1273 std::string Triple = CreateTargetTriple();
1274 TargetInfo *Target = TargetInfo::CreateTargetInfo(Triple);
1275 if (Target == 0) {
1276 fprintf(stderr, "Sorry, I don't know what target this is: %s\n",
1277 Triple.c_str());
1278 fprintf(stderr, "Please use -triple or -arch.\n");
1279 exit(1);
1280 }
Chris Lattner4f037832007-12-05 23:24:17 +00001281
Reid Spencer5f016e22007-07-11 17:01:13 +00001282 for (unsigned i = 0, e = InputFilenames.size(); i != e; ++i) {
Ted Kremenek31e703b2007-12-11 23:28:38 +00001283 const std::string &InFile = InputFilenames[i];
Ted Kremenek31e703b2007-12-11 23:28:38 +00001284
Ted Kremenek20e97482007-12-12 23:41:08 +00001285 if (isSerializedFile(InFile))
1286 ProcessSerializedFile(InFile,Diags,FileMgr);
1287 else {
1288 /// Create a SourceManager object. This tracks and owns all the file
1289 /// buffers allocated to a translation unit.
1290 SourceManager SourceMgr;
Ted Kremenek31e703b2007-12-11 23:28:38 +00001291
Ted Kremenek20e97482007-12-12 23:41:08 +00001292 // Initialize language options, inferring file types from input filenames.
1293 LangOptions LangInfo;
1294 InitializeBaseLanguage();
1295 LangKind LK = GetLanguage(InFile);
1296 InitializeLangOptions(LangInfo, LK);
1297 InitializeLanguageStandard(LangInfo, LK);
1298
1299 // Process the -I options and set them in the HeaderInfo.
1300 HeaderSearch HeaderInfo(FileMgr);
1301 DiagClient->setHeaderSearch(HeaderInfo);
Chris Lattnerdcaa0962008-03-03 03:16:03 +00001302 InitializeIncludePaths(argv[0], HeaderInfo, FileMgr, LangInfo);
Ted Kremenek20e97482007-12-12 23:41:08 +00001303
Ted Kremenek20e97482007-12-12 23:41:08 +00001304 // Set up the preprocessor with these options.
1305 Preprocessor PP(Diags, LangInfo, *Target, SourceMgr, HeaderInfo);
1306
1307 std::vector<char> PredefineBuffer;
Ted Kremenek1036b682007-12-19 23:48:45 +00001308 if (!InitializePreprocessor(PP, InFile, PredefineBuffer))
Ted Kremenek76edd0e2007-12-19 22:29:55 +00001309 continue;
1310
Ted Kremenek1036b682007-12-19 23:48:45 +00001311 ProcessInputFile(PP, InFile, *DiagClient);
Ted Kremenek20e97482007-12-12 23:41:08 +00001312 HeaderInfo.ClearFileInfo();
1313
1314 if (Stats)
1315 SourceMgr.PrintStats();
1316 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001317 }
1318
Chris Lattner11215192008-03-14 06:12:05 +00001319 delete Target;
1320
Reid Spencer5f016e22007-07-11 17:01:13 +00001321 unsigned NumDiagnostics = Diags.getNumDiagnostics();
1322
1323 if (NumDiagnostics)
1324 fprintf(stderr, "%d diagnostic%s generated.\n", NumDiagnostics,
1325 (NumDiagnostics == 1 ? "" : "s"));
1326
1327 if (Stats) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001328 FileMgr.PrintStats();
1329 fprintf(stderr, "\n");
1330 }
1331
Chris Lattner96f1a642007-07-21 05:40:53 +00001332 return Diags.getNumErrors() != 0;
Reid Spencer5f016e22007-07-11 17:01:13 +00001333}