blob: 6efab7486420aa77773f8ae483796ee2de19f706 [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 Kremenek88f5cde2008-03-27 06:17:42 +000029#include "HTMLDiagnostics.h"
30#include "clang/Analysis/PathDiagnostic.h"
Ted Kremenek77cda502007-12-18 21:34:28 +000031#include "clang/AST/TranslationUnit.h"
Chris Lattner8ee3c032008-02-06 02:01:47 +000032#include "clang/CodeGen/ModuleBuilder.h"
Chris Lattnere91c1342008-02-06 00:23:21 +000033#include "clang/Sema/ParseAST.h"
Chris Lattner556beb72007-09-15 22:56:56 +000034#include "clang/AST/ASTConsumer.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000035#include "clang/Parse/Parser.h"
36#include "clang/Lex/HeaderSearch.h"
37#include "clang/Basic/FileManager.h"
38#include "clang/Basic/SourceManager.h"
39#include "clang/Basic/TargetInfo.h"
Chris Lattnere66b65c2008-02-06 01:42:25 +000040#include "llvm/Module.h"
Chris Lattner8f3dab82007-12-15 23:20:07 +000041#include "llvm/ADT/SmallPtrSet.h"
Chris Lattnere66b65c2008-02-06 01:42:25 +000042#include "llvm/Bitcode/ReaderWriter.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000043#include "llvm/Support/CommandLine.h"
44#include "llvm/Support/MemoryBuffer.h"
45#include "llvm/System/Signals.h"
Ted Kremenekae360762007-12-03 22:06:55 +000046#include "llvm/Config/config.h"
Ted Kremenekee533642007-12-20 19:47:16 +000047#include "llvm/ADT/OwningPtr.h"
Chris Lattnerdcaa0962008-03-03 03:16:03 +000048#include "llvm/System/Path.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000049#include <memory>
Chris Lattnere66b65c2008-02-06 01:42:25 +000050#include <fstream>
Ted Kremenek339b9c22008-04-17 22:31:54 +000051#include <algorithm>
Reid Spencer5f016e22007-07-11 17:01:13 +000052using namespace clang;
53
54//===----------------------------------------------------------------------===//
55// Global options.
56//===----------------------------------------------------------------------===//
57
58static llvm::cl::opt<bool>
59Verbose("v", llvm::cl::desc("Enable verbose output"));
60static llvm::cl::opt<bool>
Nate Begemanaabbb122007-12-30 01:38:50 +000061Stats("print-stats",
62 llvm::cl::desc("Print performance metrics and statistics"));
Reid Spencer5f016e22007-07-11 17:01:13 +000063
64enum ProgActions {
Steve Naroffb29b4272008-04-14 22:03:09 +000065 RewriteObjC, // ObjC->C Rewriter.
Chris Lattnerb57e3d42008-05-08 06:52:13 +000066 RewriteMacros, // Expand macros but not #includes.
Ted Kremenek13e479b2008-03-19 07:53:42 +000067 HTMLTest, // HTML displayer testing stuff.
Reid Spencer5f016e22007-07-11 17:01:13 +000068 EmitLLVM, // Emit a .ll file.
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +000069 EmitBC, // Emit a .bc file.
Ted Kremeneka1fa3a12007-12-13 00:37:31 +000070 SerializeAST, // Emit a .ast file.
Ted Kremenek6a340832008-03-18 21:19:49 +000071 EmitHTML, // Translate input source into HTML.
Chris Lattner3b427b32007-10-11 00:18:28 +000072 ASTPrint, // Parse ASTs and print them.
73 ASTDump, // Parse ASTs and dump them.
74 ASTView, // Parse ASTs and view them in Graphviz.
Ted Kremenekbfa82c42007-10-16 23:37:27 +000075 TestSerialization, // Run experimental serialization code.
Reid Spencer5f016e22007-07-11 17:01:13 +000076 ParsePrintCallbacks, // Parse and print each callback.
77 ParseSyntaxOnly, // Parse and perform semantic analysis.
78 ParseNoop, // Parse with noop callbacks.
79 RunPreprocessorOnly, // Just lex, no output.
80 PrintPreprocessedInput, // -E mode.
Ted Kremenekf4381fd2008-07-02 00:03:09 +000081 DumpTokens, // Token dump mode.
82 RunAnalysis // Run one or more source code analyses.
Reid Spencer5f016e22007-07-11 17:01:13 +000083};
84
85static llvm::cl::opt<ProgActions>
86ProgAction(llvm::cl::desc("Choose output type:"), llvm::cl::ZeroOrMore,
87 llvm::cl::init(ParseSyntaxOnly),
88 llvm::cl::values(
89 clEnumValN(RunPreprocessorOnly, "Eonly",
90 "Just run preprocessor, no output (for timings)"),
91 clEnumValN(PrintPreprocessedInput, "E",
92 "Run preprocessor, emit preprocessed file"),
93 clEnumValN(DumpTokens, "dumptokens",
94 "Run preprocessor, dump internal rep of tokens"),
95 clEnumValN(ParseNoop, "parse-noop",
96 "Run parser with noop callbacks (for timings)"),
97 clEnumValN(ParseSyntaxOnly, "fsyntax-only",
98 "Run parser and perform semantic analysis"),
99 clEnumValN(ParsePrintCallbacks, "parse-print-callbacks",
100 "Run parser and print each callback invoked"),
Ted Kremenek6a340832008-03-18 21:19:49 +0000101 clEnumValN(EmitHTML, "emit-html",
102 "Output input source as HTML"),
Chris Lattner3b427b32007-10-11 00:18:28 +0000103 clEnumValN(ASTPrint, "ast-print",
104 "Build ASTs and then pretty-print them"),
105 clEnumValN(ASTDump, "ast-dump",
106 "Build ASTs and then debug dump them"),
Chris Lattnerea254db2007-10-11 00:37:43 +0000107 clEnumValN(ASTView, "ast-view",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000108 "Build ASTs and view them with GraphViz"),
Ted Kremenekbfa82c42007-10-16 23:37:27 +0000109 clEnumValN(TestSerialization, "test-pickling",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000110 "Run prototype serialization code"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000111 clEnumValN(EmitLLVM, "emit-llvm",
Ted Kremenek27b07c52007-09-06 21:26:58 +0000112 "Build ASTs then convert to LLVM, emit .ll file"),
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +0000113 clEnumValN(EmitBC, "emit-llvm-bc",
114 "Build ASTs then convert to LLVM, emit .bc file"),
Ted Kremenekccc76472007-12-19 19:47:59 +0000115 clEnumValN(SerializeAST, "serialize",
Ted Kremeneka1fa3a12007-12-13 00:37:31 +0000116 "Build ASTs and emit .ast file"),
Steve Naroffb29b4272008-04-14 22:03:09 +0000117 clEnumValN(RewriteObjC, "rewrite-objc",
Chris Lattnerb57e3d42008-05-08 06:52:13 +0000118 "Rewrite ObjC into C (code rewriter example)"),
119 clEnumValN(RewriteMacros, "rewrite-macros",
120 "Expand macros without full preprocessing"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000121 clEnumValEnd));
122
Ted Kremenekccc76472007-12-19 19:47:59 +0000123
124static llvm::cl::opt<std::string>
125OutputFile("o",
Ted Kremenek50b56412007-12-19 19:50:41 +0000126 llvm::cl::value_desc("path"),
Ted Kremenekccc76472007-12-19 19:47:59 +0000127 llvm::cl::desc("Specify output file (for --serialize, this is a directory)"));
Ted Kremenek55af98c2008-04-14 18:40:58 +0000128
129//===----------------------------------------------------------------------===//
Sanjiv Guptae8b9f5b2008-05-08 08:54:20 +0000130// Code Generator Options
131//===----------------------------------------------------------------------===//
132static llvm::cl::opt<bool>
133GenerateDebugInfo("g",
134 llvm::cl::desc("Generate source level debug information"));
135
136//===----------------------------------------------------------------------===//
Ted Kremenek55af98c2008-04-14 18:40:58 +0000137// Diagnostic Options
138//===----------------------------------------------------------------------===//
139
Ted Kremenek41193e42007-09-26 19:42:19 +0000140static llvm::cl::opt<bool>
141VerifyDiagnostics("verify",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000142 llvm::cl::desc("Verify emitted diagnostics and warnings"));
Ted Kremenek41193e42007-09-26 19:42:19 +0000143
Ted Kremenek88f5cde2008-03-27 06:17:42 +0000144static llvm::cl::opt<std::string>
145HTMLDiag("html-diags",
146 llvm::cl::desc("Generate HTML to report diagnostics"),
147 llvm::cl::value_desc("HTML directory"));
148
Reid Spencer5f016e22007-07-11 17:01:13 +0000149//===----------------------------------------------------------------------===//
Ted Kremenek55af98c2008-04-14 18:40:58 +0000150// Analyzer Options
151//===----------------------------------------------------------------------===//
152
153static llvm::cl::opt<bool>
154VisualizeEG("visualize-egraph",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000155 llvm::cl::desc("Display static analysis Exploded Graph"));
Ted Kremenek55af98c2008-04-14 18:40:58 +0000156
157static llvm::cl::opt<bool>
158AnalyzeAll("checker-opt-analyze-headers",
159 llvm::cl::desc("Force the static analyzer to analyze "
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000160 "functions defined in header files"));
Ted Kremenek55af98c2008-04-14 18:40:58 +0000161
Ted Kremenekf4381fd2008-07-02 00:03:09 +0000162static llvm::cl::list<Analyses>
163AnalysisList(llvm::cl::desc("Available Source Code Analyses:"),
164llvm::cl::values(
Ted Kremenek902141f2008-07-02 18:23:21 +0000165clEnumValN(CFGDump, "cfg-dump", "Display Control-Flow Graphs"),
166clEnumValN(CFGView, "cfg-view", "View Control-Flow Graphs using GraphViz"),
Ted Kremenek235e0312008-07-02 18:11:29 +0000167clEnumValN(DisplayLiveVariables, "dump-live-variables",
168 "Print results of live variable analysis"),
Ted Kremenekf4381fd2008-07-02 00:03:09 +0000169clEnumValN(WarnDeadStores, "warn-dead-stores",
170 "Flag warnings of stores to dead variables"),
171clEnumValN(WarnUninitVals, "warn-uninit-values",
172 "Flag warnings of uses of unitialized variables"),
Ted Kremenekbc46f342008-07-02 16:35:50 +0000173clEnumValN(CheckerSimple, "checker-simple",
174 "Perform simple path-sensitive checks."),
Ted Kremenekb35a74a2008-07-02 00:44:58 +0000175clEnumValN(CheckerCFRef, "checker-cfref",
Ted Kremenekbc46f342008-07-02 16:35:50 +0000176 "Run the [Core] Foundation reference count checker"),
Ted Kremenekf4381fd2008-07-02 00:03:09 +0000177clEnumValEnd));
178
Ted Kremenek55af98c2008-04-14 18:40:58 +0000179//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +0000180// Language Options
181//===----------------------------------------------------------------------===//
182
183enum LangKind {
184 langkind_unspecified,
185 langkind_c,
186 langkind_c_cpp,
187 langkind_cxx,
188 langkind_cxx_cpp,
189 langkind_objc,
190 langkind_objc_cpp,
191 langkind_objcxx,
192 langkind_objcxx_cpp
193};
194
195/* TODO: GCC also accepts:
196 c-header c++-header objective-c-header objective-c++-header
197 assembler assembler-with-cpp
198 ada, f77*, ratfor (!), f95, java, treelang
199 */
200static llvm::cl::opt<LangKind>
201BaseLang("x", llvm::cl::desc("Base language to compile"),
202 llvm::cl::init(langkind_unspecified),
203 llvm::cl::values(clEnumValN(langkind_c, "c", "C"),
204 clEnumValN(langkind_cxx, "c++", "C++"),
205 clEnumValN(langkind_objc, "objective-c", "Objective C"),
206 clEnumValN(langkind_objcxx,"objective-c++","Objective C++"),
207 clEnumValN(langkind_c_cpp, "c-cpp-output",
208 "Preprocessed C"),
209 clEnumValN(langkind_cxx_cpp, "c++-cpp-output",
210 "Preprocessed C++"),
211 clEnumValN(langkind_objc_cpp, "objective-c-cpp-output",
212 "Preprocessed Objective C"),
213 clEnumValN(langkind_objcxx_cpp,"objective-c++-cpp-output",
214 "Preprocessed Objective C++"),
215 clEnumValEnd));
216
217static llvm::cl::opt<bool>
218LangObjC("ObjC", llvm::cl::desc("Set base language to Objective-C"),
219 llvm::cl::Hidden);
220static llvm::cl::opt<bool>
221LangObjCXX("ObjC++", llvm::cl::desc("Set base language to Objective-C++"),
222 llvm::cl::Hidden);
223
Ted Kremenek8904f152007-12-05 23:49:08 +0000224/// InitializeBaseLanguage - Handle the -x foo options.
225static void InitializeBaseLanguage() {
226 if (LangObjC)
227 BaseLang = langkind_objc;
228 else if (LangObjCXX)
229 BaseLang = langkind_objcxx;
230}
231
232static LangKind GetLanguage(const std::string &Filename) {
233 if (BaseLang != langkind_unspecified)
234 return BaseLang;
235
236 std::string::size_type DotPos = Filename.rfind('.');
237
238 if (DotPos == std::string::npos) {
239 BaseLang = langkind_c; // Default to C if no extension.
Chris Lattner9b2f6c42008-01-04 19:12:28 +0000240 return langkind_c;
Reid Spencer5f016e22007-07-11 17:01:13 +0000241 }
242
Ted Kremenek8904f152007-12-05 23:49:08 +0000243 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
244 // C header: .h
245 // C++ header: .hh or .H;
246 // assembler no preprocessing: .s
247 // assembler: .S
248 if (Ext == "c")
249 return langkind_c;
250 else if (Ext == "i")
251 return langkind_c_cpp;
252 else if (Ext == "ii")
253 return langkind_cxx_cpp;
254 else if (Ext == "m")
255 return langkind_objc;
256 else if (Ext == "mi")
257 return langkind_objc_cpp;
258 else if (Ext == "mm" || Ext == "M")
259 return langkind_objcxx;
260 else if (Ext == "mii")
261 return langkind_objcxx_cpp;
262 else if (Ext == "C" || Ext == "cc" || Ext == "cpp" || Ext == "CPP" ||
263 Ext == "c++" || Ext == "cp" || Ext == "cxx")
264 return langkind_cxx;
265 else
266 return langkind_c;
267}
268
269
270static void InitializeLangOptions(LangOptions &Options, LangKind LK) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000271 // FIXME: implement -fpreprocessed mode.
272 bool NoPreprocess = false;
273
Ted Kremenek8904f152007-12-05 23:49:08 +0000274 switch (LK) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000275 default: assert(0 && "Unknown language kind!");
276 case langkind_c_cpp:
277 NoPreprocess = true;
278 // FALLTHROUGH
279 case langkind_c:
280 break;
281 case langkind_cxx_cpp:
282 NoPreprocess = true;
283 // FALLTHROUGH
284 case langkind_cxx:
285 Options.CPlusPlus = 1;
286 break;
287 case langkind_objc_cpp:
288 NoPreprocess = true;
289 // FALLTHROUGH
290 case langkind_objc:
Ted Kremenek01d9dbf2008-04-29 04:37:03 +0000291 Options.ObjC1 = Options.ObjC2 = 1;
Reid Spencer5f016e22007-07-11 17:01:13 +0000292 break;
293 case langkind_objcxx_cpp:
294 NoPreprocess = true;
295 // FALLTHROUGH
296 case langkind_objcxx:
297 Options.ObjC1 = Options.ObjC2 = 1;
298 Options.CPlusPlus = 1;
299 break;
300 }
301}
302
303/// LangStds - Language standards we support.
304enum LangStds {
305 lang_unspecified,
306 lang_c89, lang_c94, lang_c99,
307 lang_gnu89, lang_gnu99,
Chris Lattnerd4b80f12007-07-16 04:18:29 +0000308 lang_cxx98, lang_gnucxx98,
309 lang_cxx0x, lang_gnucxx0x
Reid Spencer5f016e22007-07-11 17:01:13 +0000310};
311
312static llvm::cl::opt<LangStds>
313LangStd("std", llvm::cl::desc("Language standard to compile for"),
314 llvm::cl::init(lang_unspecified),
315 llvm::cl::values(clEnumValN(lang_c89, "c89", "ISO C 1990"),
316 clEnumValN(lang_c89, "c90", "ISO C 1990"),
317 clEnumValN(lang_c89, "iso9899:1990", "ISO C 1990"),
318 clEnumValN(lang_c94, "iso9899:199409",
319 "ISO C 1990 with amendment 1"),
320 clEnumValN(lang_c99, "c99", "ISO C 1999"),
321// clEnumValN(lang_c99, "c9x", "ISO C 1999"),
322 clEnumValN(lang_c99, "iso9899:1999", "ISO C 1999"),
323// clEnumValN(lang_c99, "iso9899:199x", "ISO C 1999"),
324 clEnumValN(lang_gnu89, "gnu89",
325 "ISO C 1990 with GNU extensions (default for C)"),
326 clEnumValN(lang_gnu99, "gnu99",
327 "ISO C 1999 with GNU extensions"),
328 clEnumValN(lang_gnu99, "gnu9x",
329 "ISO C 1999 with GNU extensions"),
330 clEnumValN(lang_cxx98, "c++98",
331 "ISO C++ 1998 with amendments"),
332 clEnumValN(lang_gnucxx98, "gnu++98",
333 "ISO C++ 1998 with amendments and GNU "
334 "extensions (default for C++)"),
Chris Lattnerd4b80f12007-07-16 04:18:29 +0000335 clEnumValN(lang_cxx0x, "c++0x",
336 "Upcoming ISO C++ 200x with amendments"),
337 clEnumValN(lang_gnucxx0x, "gnu++0x",
338 "Upcoming ISO C++ 200x with amendments and GNU "
339 "extensions (default for C++)"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000340 clEnumValEnd));
341
342static llvm::cl::opt<bool>
343NoOperatorNames("fno-operator-names",
344 llvm::cl::desc("Do not treat C++ operator name keywords as "
345 "synonyms for operators"));
346
Anders Carlssonee98ac52007-10-15 02:50:23 +0000347static llvm::cl::opt<bool>
348PascalStrings("fpascal-strings",
349 llvm::cl::desc("Recognize and construct Pascal-style "
350 "string literals"));
Steve Naroffd62701b2008-02-07 03:50:06 +0000351
352static llvm::cl::opt<bool>
353MSExtensions("fms-extensions",
354 llvm::cl::desc("Accept some non-standard constructs used in "
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000355 "Microsoft header files "));
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000356
357static llvm::cl::opt<bool>
358WritableStrings("fwritable-strings",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000359 llvm::cl::desc("Store string literals as writable data"));
Anders Carlsson695dbb62007-11-30 04:21:22 +0000360
361static llvm::cl::opt<bool>
362LaxVectorConversions("flax-vector-conversions",
363 llvm::cl::desc("Allow implicit conversions between vectors"
364 " with a different number of elements or "
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000365 "different element types"));
Ted Kremenek01d9dbf2008-04-29 04:37:03 +0000366
Reid Spencer5f016e22007-07-11 17:01:13 +0000367// FIXME: add:
368// -ansi
369// -trigraphs
370// -fdollars-in-identifiers
Anders Carlssonee98ac52007-10-15 02:50:23 +0000371// -fpascal-strings
Ted Kremenek8904f152007-12-05 23:49:08 +0000372static void InitializeLanguageStandard(LangOptions &Options, LangKind LK) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000373 if (LangStd == lang_unspecified) {
374 // Based on the base language, pick one.
Ted Kremenek8904f152007-12-05 23:49:08 +0000375 switch (LK) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000376 default: assert(0 && "Unknown base language");
377 case langkind_c:
378 case langkind_c_cpp:
379 case langkind_objc:
380 case langkind_objc_cpp:
381 LangStd = lang_gnu99;
382 break;
383 case langkind_cxx:
384 case langkind_cxx_cpp:
385 case langkind_objcxx:
386 case langkind_objcxx_cpp:
387 LangStd = lang_gnucxx98;
388 break;
389 }
390 }
391
392 switch (LangStd) {
393 default: assert(0 && "Unknown language standard!");
394
395 // Fall through from newer standards to older ones. This isn't really right.
396 // FIXME: Enable specifically the right features based on the language stds.
Chris Lattnerd4b80f12007-07-16 04:18:29 +0000397 case lang_gnucxx0x:
398 case lang_cxx0x:
399 Options.CPlusPlus0x = 1;
400 // FALL THROUGH
Reid Spencer5f016e22007-07-11 17:01:13 +0000401 case lang_gnucxx98:
402 case lang_cxx98:
403 Options.CPlusPlus = 1;
404 Options.CXXOperatorNames = !NoOperatorNames;
Nate Begeman8aebcb72007-11-15 07:30:50 +0000405 Options.Boolean = 1;
Reid Spencer5f016e22007-07-11 17:01:13 +0000406 // FALL THROUGH.
407 case lang_gnu99:
408 case lang_c99:
Reid Spencer5f016e22007-07-11 17:01:13 +0000409 Options.C99 = 1;
410 Options.HexFloats = 1;
411 // FALL THROUGH.
412 case lang_gnu89:
413 Options.BCPLComment = 1; // Only for C99/C++.
414 // FALL THROUGH.
415 case lang_c94:
Chris Lattner3426b9b2008-02-25 04:01:39 +0000416 Options.Digraphs = 1; // C94, C99, C++.
417 // FALL THROUGH.
Reid Spencer5f016e22007-07-11 17:01:13 +0000418 case lang_c89:
419 break;
420 }
421
Chris Lattnerd658b562008-04-05 06:32:51 +0000422 if (LangStd == lang_c89 || LangStd == lang_c94 || LangStd == lang_gnu89)
423 Options.ImplicitInt = 1;
424 else
425 Options.ImplicitInt = 0;
Reid Spencer5f016e22007-07-11 17:01:13 +0000426 Options.Trigraphs = 1; // -trigraphs or -ansi
427 Options.DollarIdents = 1; // FIXME: Really a target property.
Anders Carlssonee98ac52007-10-15 02:50:23 +0000428 Options.PascalStrings = PascalStrings;
Steve Naroffd62701b2008-02-07 03:50:06 +0000429 Options.Microsoft = MSExtensions;
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000430 Options.WritableStrings = WritableStrings;
Anders Carlsson695dbb62007-11-30 04:21:22 +0000431 Options.LaxVectorConversions = LaxVectorConversions;
Reid Spencer5f016e22007-07-11 17:01:13 +0000432}
433
Ted Kremenek01d9dbf2008-04-29 04:37:03 +0000434static llvm::cl::opt<bool>
435ObjCExclusiveGC("fobjc-gc-only",
436 llvm::cl::desc("Use GC exclusively for Objective-C related "
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000437 "memory management"));
Ted Kremenek01d9dbf2008-04-29 04:37:03 +0000438
439static llvm::cl::opt<bool>
440ObjCEnableGC("fobjc-gc",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000441 llvm::cl::desc("Enable Objective-C garbage collection"));
Ted Kremenek01d9dbf2008-04-29 04:37:03 +0000442
443void InitializeGCMode(LangOptions &Options) {
444 if (ObjCExclusiveGC)
445 Options.setGCMode(LangOptions::GCOnly);
446 else if (ObjCEnableGC)
447 Options.setGCMode(LangOptions::HybridGC);
448}
449
450
Reid Spencer5f016e22007-07-11 17:01:13 +0000451//===----------------------------------------------------------------------===//
452// Our DiagnosticClient implementation
453//===----------------------------------------------------------------------===//
454
455// FIXME: Werror should take a list of things, -Werror=foo,bar
456static llvm::cl::opt<bool>
457WarningsAsErrors("Werror", llvm::cl::desc("Treat all warnings as errors"));
458
459static llvm::cl::opt<bool>
Chris Lattner5b4681c2008-05-29 15:36:45 +0000460SilenceWarnings("w", llvm::cl::desc("Do not emit any warnings"));
461
462static llvm::cl::opt<bool>
Reid Spencer5f016e22007-07-11 17:01:13 +0000463WarnOnExtensions("pedantic", llvm::cl::init(false),
464 llvm::cl::desc("Issue a warning on uses of GCC extensions"));
465
466static llvm::cl::opt<bool>
467ErrorOnExtensions("pedantic-errors",
468 llvm::cl::desc("Issue an error on uses of GCC extensions"));
469
470static llvm::cl::opt<bool>
471WarnUnusedMacros("Wunused_macros",
472 llvm::cl::desc("Warn for unused macros in the main translation unit"));
473
Ted Kremenekdb87bca2007-11-13 18:37:02 +0000474static llvm::cl::opt<bool>
475WarnFloatEqual("Wfloat-equal",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000476 llvm::cl::desc("Warn about equality comparisons of floating point values"));
Ted Kremenekdb87bca2007-11-13 18:37:02 +0000477
Ted Kremenek73da5902007-12-17 17:50:07 +0000478static llvm::cl::opt<bool>
479WarnNoFormatNonLiteral("Wno-format-nonliteral",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000480 llvm::cl::desc("Do not warn about non-literal format strings"));
Ted Kremenek73da5902007-12-17 17:50:07 +0000481
Chris Lattner116a4b12008-01-23 17:19:46 +0000482static llvm::cl::opt<bool>
483WarnUndefMacros("Wundef",
484 llvm::cl::desc("Warn on use of undefined macros in #if's"));
485
Chris Lattner37d10842008-05-05 21:18:06 +0000486static llvm::cl::opt<bool>
Ted Kremenek358256d2008-05-30 16:42:02 +0000487WarnImplicitFunctionDeclaration("Wimplicit-function-declaration",
488 llvm::cl::desc("Warn about uses of implicitly defined functions"));
Chris Lattner116a4b12008-01-23 17:19:46 +0000489
Reid Spencer5f016e22007-07-11 17:01:13 +0000490/// InitializeDiagnostics - Initialize the diagnostic object, based on the
491/// current command line option settings.
492static void InitializeDiagnostics(Diagnostic &Diags) {
Chris Lattner5b4681c2008-05-29 15:36:45 +0000493 Diags.setIgnoreAllWarnings(SilenceWarnings);
Reid Spencer5f016e22007-07-11 17:01:13 +0000494 Diags.setWarningsAsErrors(WarningsAsErrors);
495 Diags.setWarnOnExtensions(WarnOnExtensions);
496 Diags.setErrorOnExtensions(ErrorOnExtensions);
497
498 // Silence the "macro is not used" warning unless requested.
499 if (!WarnUnusedMacros)
500 Diags.setDiagnosticMapping(diag::pp_macro_not_used, diag::MAP_IGNORE);
Ted Kremenekdb87bca2007-11-13 18:37:02 +0000501
502 // Silence "floating point comparison" warnings unless requested.
503 if (!WarnFloatEqual)
504 Diags.setDiagnosticMapping(diag::warn_floatingpoint_eq, diag::MAP_IGNORE);
Ted Kremenek73da5902007-12-17 17:50:07 +0000505
506 // Silence "format string is not a string literal" warnings if requested
507 if (WarnNoFormatNonLiteral)
Ted Kremenek7c1d3df2007-12-17 17:50:39 +0000508 Diags.setDiagnosticMapping(diag::warn_printf_not_string_constant,
509 diag::MAP_IGNORE);
Chris Lattner116a4b12008-01-23 17:19:46 +0000510 if (!WarnUndefMacros)
511 Diags.setDiagnosticMapping(diag::warn_pp_undef_identifier,diag::MAP_IGNORE);
Steve Naroffe7a37302008-02-11 22:40:08 +0000512
Chris Lattner37d10842008-05-05 21:18:06 +0000513 if (!WarnImplicitFunctionDeclaration)
514 Diags.setDiagnosticMapping(diag::warn_implicit_function_decl,
515 diag::MAP_IGNORE);
516
Steve Naroffe7a37302008-02-11 22:40:08 +0000517 if (MSExtensions) // MS allows unnamed struct/union fields.
518 Diags.setDiagnosticMapping(diag::w_no_declarators, diag::MAP_IGNORE);
Chris Lattner8aedf192008-05-04 23:52:02 +0000519
520 // If -pedantic-errors is set, turn extensions that warn by default into
521 // errors.
522 if (ErrorOnExtensions) {
523 Diags.setDiagnosticMapping(diag::warn_hex_escape_too_large,
524 diag::MAP_ERROR);
525 Diags.setDiagnosticMapping(diag::warn_octal_escape_too_large,
526 diag::MAP_ERROR);
527 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000528}
529
530//===----------------------------------------------------------------------===//
Ted Kremenekcb330932008-02-18 21:21:23 +0000531// Analysis-specific options.
532//===----------------------------------------------------------------------===//
533
534static llvm::cl::opt<std::string>
535AnalyzeSpecificFunction("analyze-function",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000536 llvm::cl::desc("Run analysis on specific function"));
Ted Kremenekcb330932008-02-18 21:21:23 +0000537
Ted Kremenekffe0f432008-03-07 22:58:01 +0000538static llvm::cl::opt<bool>
Ted Kremenekd71ed262008-04-10 22:16:52 +0000539TrimGraph("trim-egraph",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000540 llvm::cl::desc("Only show error-related paths in the analysis graph"));
Ted Kremenekffe0f432008-03-07 22:58:01 +0000541
Ted Kremenekcb330932008-02-18 21:21:23 +0000542//===----------------------------------------------------------------------===//
Ted Kremenekae360762007-12-03 22:06:55 +0000543// Target Triple Processing.
544//===----------------------------------------------------------------------===//
545
546static llvm::cl::opt<std::string>
547TargetTriple("triple",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000548 llvm::cl::desc("Specify target triple (e.g. i686-apple-darwin9)"));
Ted Kremenekae360762007-12-03 22:06:55 +0000549
Chris Lattner42e67372008-03-05 01:18:20 +0000550static llvm::cl::opt<std::string>
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000551Arch("arch", llvm::cl::desc("Specify target architecture (e.g. i686)"));
Ted Kremenekae360762007-12-03 22:06:55 +0000552
Chris Lattner6fd9fa12008-03-09 01:35:13 +0000553static std::string CreateTargetTriple() {
Ted Kremenekae360762007-12-03 22:06:55 +0000554 // Initialize base triple. If a -triple option has been specified, use
555 // that triple. Otherwise, default to the host triple.
Chris Lattner6590d212007-12-12 05:01:48 +0000556 std::string Triple = TargetTriple;
557 if (Triple.empty()) Triple = LLVM_HOSTTRIPLE;
Ted Kremenekae360762007-12-03 22:06:55 +0000558
Chris Lattner6fd9fa12008-03-09 01:35:13 +0000559 // If -arch foo was specified, remove the architecture from the triple we have
560 // so far and replace it with the specified one.
561 if (Arch.empty())
562 return Triple;
563
Ted Kremenekae360762007-12-03 22:06:55 +0000564 // Decompose the base triple into "arch" and suffix.
Chris Lattner6fd9fa12008-03-09 01:35:13 +0000565 std::string::size_type FirstDashIdx = Triple.find("-");
Ted Kremenekae360762007-12-03 22:06:55 +0000566
Chris Lattner6fd9fa12008-03-09 01:35:13 +0000567 if (FirstDashIdx == std::string::npos) {
Ted Kremenek9b4ebc22007-12-03 22:11:31 +0000568 fprintf(stderr,
569 "Malformed target triple: \"%s\" ('-' could not be found).\n",
Chris Lattner6590d212007-12-12 05:01:48 +0000570 Triple.c_str());
571 exit(1);
Ted Kremenek9b4ebc22007-12-03 22:11:31 +0000572 }
Ted Kremenekae360762007-12-03 22:06:55 +0000573
Chris Lattner6fd9fa12008-03-09 01:35:13 +0000574 return Arch + std::string(Triple.begin()+FirstDashIdx, Triple.end());
Ted Kremenekae360762007-12-03 22:06:55 +0000575}
576
577//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +0000578// Preprocessor Initialization
579//===----------------------------------------------------------------------===//
580
581// FIXME: Preprocessor builtins to support.
582// -A... - Play with #assertions
583// -undef - Undefine all predefined macros
584
585static llvm::cl::list<std::string>
586D_macros("D", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
587 llvm::cl::desc("Predefine the specified macro"));
588static llvm::cl::list<std::string>
589U_macros("U", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
590 llvm::cl::desc("Undefine the specified macro"));
591
Chris Lattner64299f82008-01-10 01:53:41 +0000592static llvm::cl::list<std::string>
593ImplicitIncludes("include", llvm::cl::value_desc("file"),
594 llvm::cl::desc("Include file before parsing"));
595
596
Reid Spencer5f016e22007-07-11 17:01:13 +0000597// Append a #define line to Buf for Macro. Macro should be of the form XXX,
598// in which case we emit "#define XXX 1" or "XXX=Y z W" in which case we emit
599// "#define XXX Y z W". To get a #define with no value, use "XXX=".
600static void DefineBuiltinMacro(std::vector<char> &Buf, const char *Macro,
601 const char *Command = "#define ") {
602 Buf.insert(Buf.end(), Command, Command+strlen(Command));
603 if (const char *Equal = strchr(Macro, '=')) {
604 // Turn the = into ' '.
605 Buf.insert(Buf.end(), Macro, Equal);
606 Buf.push_back(' ');
607 Buf.insert(Buf.end(), Equal+1, Equal+strlen(Equal));
608 } else {
609 // Push "macroname 1".
610 Buf.insert(Buf.end(), Macro, Macro+strlen(Macro));
611 Buf.push_back(' ');
612 Buf.push_back('1');
613 }
614 Buf.push_back('\n');
615}
616
Chris Lattner64299f82008-01-10 01:53:41 +0000617/// AddImplicitInclude - Add an implicit #include of the specified file to the
618/// predefines buffer.
619static void AddImplicitInclude(std::vector<char> &Buf, const std::string &File){
620 const char *Inc = "#include \"";
621 Buf.insert(Buf.end(), Inc, Inc+strlen(Inc));
622 Buf.insert(Buf.end(), File.begin(), File.end());
623 Buf.push_back('"');
624 Buf.push_back('\n');
625}
626
Reid Spencer5f016e22007-07-11 17:01:13 +0000627
Chris Lattner53b0dab2007-10-09 22:10:18 +0000628/// InitializePreprocessor - Initialize the preprocessor getting it and the
Chris Lattner51574ea2008-04-19 23:25:44 +0000629/// environment ready to process a single file. This returns true on error.
Chris Lattner53b0dab2007-10-09 22:10:18 +0000630///
Chris Lattner51574ea2008-04-19 23:25:44 +0000631static bool InitializePreprocessor(Preprocessor &PP,
632 bool InitializeSourceMgr,
633 const std::string &InFile) {
Chris Lattnerdee73592007-12-15 20:48:40 +0000634 FileManager &FileMgr = PP.getFileManager();
Reid Spencer5f016e22007-07-11 17:01:13 +0000635
Chris Lattner53b0dab2007-10-09 22:10:18 +0000636 // Figure out where to get and map in the main file.
Chris Lattnerdee73592007-12-15 20:48:40 +0000637 SourceManager &SourceMgr = PP.getSourceManager();
Ted Kremenek339b9c22008-04-17 22:31:54 +0000638
639 if (InitializeSourceMgr) {
640 if (InFile != "-") {
641 const FileEntry *File = FileMgr.getFile(InFile);
642 if (File) SourceMgr.createMainFileID(File, SourceLocation());
643 if (SourceMgr.getMainFileID() == 0) {
644 fprintf(stderr, "Error reading '%s'!\n",InFile.c_str());
Chris Lattner51574ea2008-04-19 23:25:44 +0000645 return true;
Ted Kremenek339b9c22008-04-17 22:31:54 +0000646 }
647 } else {
648 llvm::MemoryBuffer *SB = llvm::MemoryBuffer::getSTDIN();
649 if (SB) SourceMgr.createMainFileIDForMemBuffer(SB);
650 if (SourceMgr.getMainFileID() == 0) {
651 fprintf(stderr, "Error reading standard input! Empty?\n");
Chris Lattner51574ea2008-04-19 23:25:44 +0000652 return true;
Ted Kremenek339b9c22008-04-17 22:31:54 +0000653 }
Chris Lattner53b0dab2007-10-09 22:10:18 +0000654 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000655 }
Sam Bishop1102d6b2008-04-14 14:41:57 +0000656
Chris Lattneraa391972008-04-19 23:09:31 +0000657 std::vector<char> PredefineBuffer;
658
Reid Spencer5f016e22007-07-11 17:01:13 +0000659 // Add macros from the command line.
Sam Bishop1102d6b2008-04-14 14:41:57 +0000660 unsigned d = 0, D = D_macros.size();
661 unsigned u = 0, U = U_macros.size();
662 while (d < D || u < U) {
663 if (u == U || (d < D && D_macros.getPosition(d) < U_macros.getPosition(u)))
664 DefineBuiltinMacro(PredefineBuffer, D_macros[d++].c_str());
665 else
666 DefineBuiltinMacro(PredefineBuffer, U_macros[u++].c_str(), "#undef ");
667 }
668
Chris Lattner64299f82008-01-10 01:53:41 +0000669 // FIXME: Read any files specified by -imacros.
670
671 // Add implicit #includes from -include.
672 for (unsigned i = 0, e = ImplicitIncludes.size(); i != e; ++i)
673 AddImplicitInclude(PredefineBuffer, ImplicitIncludes[i]);
Chris Lattner53b0dab2007-10-09 22:10:18 +0000674
Chris Lattneraa391972008-04-19 23:09:31 +0000675 // Null terminate PredefinedBuffer and add it.
Chris Lattner53b0dab2007-10-09 22:10:18 +0000676 PredefineBuffer.push_back(0);
Chris Lattneraa391972008-04-19 23:09:31 +0000677 PP.setPredefines(&PredefineBuffer[0]);
Chris Lattner53b0dab2007-10-09 22:10:18 +0000678
679 // Once we've read this, we're done.
Chris Lattner51574ea2008-04-19 23:25:44 +0000680 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000681}
682
683//===----------------------------------------------------------------------===//
684// Preprocessor include path information.
685//===----------------------------------------------------------------------===//
686
687// This tool exports a large number of command line options to control how the
688// preprocessor searches for header files. At root, however, the Preprocessor
689// object takes a very simple interface: a list of directories to search for
690//
691// FIXME: -nostdinc,-nostdinc++
Chris Lattner0c946412007-08-26 17:47:35 +0000692// FIXME: -imultilib
Reid Spencer5f016e22007-07-11 17:01:13 +0000693//
Chris Lattner64299f82008-01-10 01:53:41 +0000694// FIXME: -imacros
Reid Spencer5f016e22007-07-11 17:01:13 +0000695
696static llvm::cl::opt<bool>
697nostdinc("nostdinc", llvm::cl::desc("Disable standard #include directories"));
698
699// Various command line options. These four add directories to each chain.
700static llvm::cl::list<std::string>
701F_dirs("F", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
702 llvm::cl::desc("Add directory to framework include search path"));
703static llvm::cl::list<std::string>
704I_dirs("I", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
705 llvm::cl::desc("Add directory to include search path"));
706static llvm::cl::list<std::string>
707idirafter_dirs("idirafter", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
708 llvm::cl::desc("Add directory to AFTER include search path"));
709static llvm::cl::list<std::string>
710iquote_dirs("iquote", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
711 llvm::cl::desc("Add directory to QUOTE include search path"));
712static llvm::cl::list<std::string>
713isystem_dirs("isystem", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
714 llvm::cl::desc("Add directory to SYSTEM include search path"));
715
716// These handle -iprefix/-iwithprefix/-iwithprefixbefore.
717static llvm::cl::list<std::string>
718iprefix_vals("iprefix", llvm::cl::value_desc("prefix"), llvm::cl::Prefix,
719 llvm::cl::desc("Set the -iwithprefix/-iwithprefixbefore prefix"));
720static llvm::cl::list<std::string>
721iwithprefix_vals("iwithprefix", llvm::cl::value_desc("dir"), llvm::cl::Prefix,
722 llvm::cl::desc("Set directory to SYSTEM include search path with prefix"));
723static llvm::cl::list<std::string>
724iwithprefixbefore_vals("iwithprefixbefore", llvm::cl::value_desc("dir"),
725 llvm::cl::Prefix,
726 llvm::cl::desc("Set directory to include search path with prefix"));
727
Chris Lattner0c946412007-08-26 17:47:35 +0000728static llvm::cl::opt<std::string>
729isysroot("isysroot", llvm::cl::value_desc("dir"), llvm::cl::init("/"),
730 llvm::cl::desc("Set the system root directory (usually /)"));
731
Reid Spencer5f016e22007-07-11 17:01:13 +0000732// Finally, implement the code that groks the options above.
733enum IncludeDirGroup {
734 Quoted = 0,
735 Angled,
736 System,
737 After
738};
739
740static std::vector<DirectoryLookup> IncludeGroup[4];
741
742/// AddPath - Add the specified path to the specified group list.
743///
744static void AddPath(const std::string &Path, IncludeDirGroup Group,
745 bool isCXXAware, bool isUserSupplied,
Chris Lattner822da612007-12-17 06:36:45 +0000746 bool isFramework, HeaderSearch &HS) {
Chris Lattnerb3de9e72007-12-09 00:39:55 +0000747 assert(!Path.empty() && "can't handle empty path here");
Chris Lattner822da612007-12-17 06:36:45 +0000748 FileManager &FM = HS.getFileMgr();
Chris Lattnerb3de9e72007-12-09 00:39:55 +0000749
Chris Lattnerd6655272007-12-17 05:59:27 +0000750 // Compute the actual path, taking into consideration -isysroot.
751 llvm::SmallString<256> MappedPath;
Chris Lattner0c946412007-08-26 17:47:35 +0000752
Chris Lattnerd6655272007-12-17 05:59:27 +0000753 // Handle isysroot.
754 if (Group == System) {
Chris Lattner60e4e2b2007-12-17 06:51:34 +0000755 // FIXME: Portability. This should be a sys::Path interface, this doesn't
756 // handle things like C:\ right, nor win32 \\network\device\blah.
Chris Lattnerd6655272007-12-17 05:59:27 +0000757 if (isysroot.size() != 1 || isysroot[0] != '/') // Add isysroot if present.
758 MappedPath.append(isysroot.begin(), isysroot.end());
Reid Spencer5f016e22007-07-11 17:01:13 +0000759 }
760
Chris Lattnerd6655272007-12-17 05:59:27 +0000761 MappedPath.append(Path.begin(), Path.end());
762
763 // Compute the DirectoryLookup type.
Reid Spencer5f016e22007-07-11 17:01:13 +0000764 DirectoryLookup::DirType Type;
765 if (Group == Quoted || Group == Angled)
766 Type = DirectoryLookup::NormalHeaderDir;
767 else if (isCXXAware)
768 Type = DirectoryLookup::SystemHeaderDir;
769 else
770 Type = DirectoryLookup::ExternCSystemHeaderDir;
771
Chris Lattnerd6655272007-12-17 05:59:27 +0000772
773 // If the directory exists, add it.
774 if (const DirectoryEntry *DE = FM.getDirectory(&MappedPath[0],
775 &MappedPath[0]+
776 MappedPath.size())) {
777 IncludeGroup[Group].push_back(DirectoryLookup(DE, Type, isUserSupplied,
778 isFramework));
779 return;
780 }
781
Chris Lattnerdf772332007-12-17 07:52:39 +0000782 // Check to see if this is an apple-style headermap (which are not allowed to
783 // be frameworks).
784 if (!isFramework) {
785 if (const FileEntry *FE = FM.getFile(&MappedPath[0],
786 &MappedPath[0]+MappedPath.size())) {
Chris Lattner1bfd4a62007-12-17 18:34:53 +0000787 if (const HeaderMap *HM = HS.CreateHeaderMap(FE)) {
788 // It is a headermap, add it to the search path.
Chris Lattnerdf772332007-12-17 07:52:39 +0000789 IncludeGroup[Group].push_back(DirectoryLookup(HM, Type,isUserSupplied));
790 return;
791 }
Chris Lattner822da612007-12-17 06:36:45 +0000792 }
793 }
794
Chris Lattnerd6655272007-12-17 05:59:27 +0000795 if (Verbose)
796 fprintf(stderr, "ignoring nonexistent directory \"%s\"\n", Path.c_str());
Reid Spencer5f016e22007-07-11 17:01:13 +0000797}
798
799/// RemoveDuplicates - If there are duplicate directory entries in the specified
800/// search list, remove the later (dead) ones.
801static void RemoveDuplicates(std::vector<DirectoryLookup> &SearchList) {
Chris Lattner8f3dab82007-12-15 23:20:07 +0000802 llvm::SmallPtrSet<const DirectoryEntry *, 8> SeenDirs;
Chris Lattnerdf772332007-12-17 07:52:39 +0000803 llvm::SmallPtrSet<const DirectoryEntry *, 8> SeenFrameworkDirs;
Chris Lattnerb94c7072007-12-17 06:44:29 +0000804 llvm::SmallPtrSet<const HeaderMap *, 8> SeenHeaderMaps;
Reid Spencer5f016e22007-07-11 17:01:13 +0000805 for (unsigned i = 0; i != SearchList.size(); ++i) {
Chris Lattnerb94c7072007-12-17 06:44:29 +0000806 if (SearchList[i].isNormalDir()) {
807 // If this isn't the first time we've seen this dir, remove it.
808 if (SeenDirs.insert(SearchList[i].getDir()))
809 continue;
810
Reid Spencer5f016e22007-07-11 17:01:13 +0000811 if (Verbose)
812 fprintf(stderr, "ignoring duplicate directory \"%s\"\n",
813 SearchList[i].getDir()->getName());
Chris Lattnerdf772332007-12-17 07:52:39 +0000814 } else if (SearchList[i].isFramework()) {
815 // If this isn't the first time we've seen this framework dir, remove it.
816 if (SeenFrameworkDirs.insert(SearchList[i].getFrameworkDir()))
817 continue;
818
819 if (Verbose)
820 fprintf(stderr, "ignoring duplicate framework \"%s\"\n",
821 SearchList[i].getFrameworkDir()->getName());
822
Chris Lattnerb94c7072007-12-17 06:44:29 +0000823 } else {
824 assert(SearchList[i].isHeaderMap() && "Not a headermap or normal dir?");
825 // If this isn't the first time we've seen this headermap, remove it.
826 if (SeenHeaderMaps.insert(SearchList[i].getHeaderMap()))
827 continue;
828
829 if (Verbose)
830 fprintf(stderr, "ignoring duplicate directory \"%s\"\n",
831 SearchList[i].getDir()->getName());
Reid Spencer5f016e22007-07-11 17:01:13 +0000832 }
Chris Lattnerb94c7072007-12-17 06:44:29 +0000833
834 // This is reached if the current entry is a duplicate.
835 SearchList.erase(SearchList.begin()+i);
836 --i;
Reid Spencer5f016e22007-07-11 17:01:13 +0000837 }
838}
839
Chris Lattner5f9eae52008-03-01 08:07:28 +0000840// AddEnvVarPaths - Add a list of paths from an environment variable to a
841// header search list.
842//
843static void AddEnvVarPaths(const char *Name, HeaderSearch &Headers) {
844 const char* at = getenv(Name);
845 if (!at)
846 return;
847
848 const char* delim = strchr(at, llvm::sys::PathSeparator);
849 while (delim != 0) {
850 if (delim-at == 0)
851 AddPath(".", Angled, false, true, false, Headers);
852 else
853 AddPath(std::string(at, std::string::size_type(delim-at)), Angled, false,
854 true, false, Headers);
855 at = delim + 1;
856 delim = strchr(at, llvm::sys::PathSeparator);
857 }
858 if (*at == 0)
859 AddPath(".", Angled, false, true, false, Headers);
860 else
861 AddPath(at, Angled, false, true, false, Headers);
862}
863
Reid Spencer5f016e22007-07-11 17:01:13 +0000864/// InitializeIncludePaths - Process the -I options and set them in the
865/// HeaderSearch object.
Chris Lattnerdcaa0962008-03-03 03:16:03 +0000866static void InitializeIncludePaths(const char *Argv0, HeaderSearch &Headers,
867 FileManager &FM, const LangOptions &Lang) {
Ted Kremenekf3721112008-05-31 00:27:00 +0000868 // Handle -I... and -F... options, walking the lists in parallel.
869 unsigned Iidx = 0, Fidx = 0;
870 while (Iidx < I_dirs.size() && Fidx < F_dirs.size()) {
871 if (I_dirs.getPosition(Iidx) < F_dirs.getPosition(Fidx)) {
872 AddPath(I_dirs[Iidx], Angled, false, true, false, Headers);
873 ++Iidx;
874 } else {
875 AddPath(F_dirs[Fidx], Angled, false, true, true, Headers);
876 ++Fidx;
877 }
878 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000879
Ted Kremenekf3721112008-05-31 00:27:00 +0000880 // Consume what's left from whatever list was longer.
881 for (; Iidx != I_dirs.size(); ++Iidx)
882 AddPath(I_dirs[Iidx], Angled, false, true, false, Headers);
883 for (; Fidx != F_dirs.size(); ++Fidx)
884 AddPath(F_dirs[Fidx], Angled, false, true, true, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000885
886 // Handle -idirafter... options.
887 for (unsigned i = 0, e = idirafter_dirs.size(); i != e; ++i)
Chris Lattner822da612007-12-17 06:36:45 +0000888 AddPath(idirafter_dirs[i], After, false, true, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000889
890 // Handle -iquote... options.
891 for (unsigned i = 0, e = iquote_dirs.size(); i != e; ++i)
Chris Lattner822da612007-12-17 06:36:45 +0000892 AddPath(iquote_dirs[i], Quoted, false, true, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000893
894 // Handle -isystem... options.
895 for (unsigned i = 0, e = isystem_dirs.size(); i != e; ++i)
Chris Lattner822da612007-12-17 06:36:45 +0000896 AddPath(isystem_dirs[i], System, false, true, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000897
898 // Walk the -iprefix/-iwithprefix/-iwithprefixbefore argument lists in
899 // parallel, processing the values in order of occurance to get the right
900 // prefixes.
901 {
902 std::string Prefix = ""; // FIXME: this isn't the correct default prefix.
903 unsigned iprefix_idx = 0;
904 unsigned iwithprefix_idx = 0;
905 unsigned iwithprefixbefore_idx = 0;
906 bool iprefix_done = iprefix_vals.empty();
907 bool iwithprefix_done = iwithprefix_vals.empty();
908 bool iwithprefixbefore_done = iwithprefixbefore_vals.empty();
909 while (!iprefix_done || !iwithprefix_done || !iwithprefixbefore_done) {
910 if (!iprefix_done &&
911 (iwithprefix_done ||
912 iprefix_vals.getPosition(iprefix_idx) <
913 iwithprefix_vals.getPosition(iwithprefix_idx)) &&
914 (iwithprefixbefore_done ||
915 iprefix_vals.getPosition(iprefix_idx) <
916 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
917 Prefix = iprefix_vals[iprefix_idx];
918 ++iprefix_idx;
919 iprefix_done = iprefix_idx == iprefix_vals.size();
920 } else if (!iwithprefix_done &&
921 (iwithprefixbefore_done ||
922 iwithprefix_vals.getPosition(iwithprefix_idx) <
923 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
924 AddPath(Prefix+iwithprefix_vals[iwithprefix_idx],
Chris Lattner822da612007-12-17 06:36:45 +0000925 System, false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000926 ++iwithprefix_idx;
927 iwithprefix_done = iwithprefix_idx == iwithprefix_vals.size();
928 } else {
929 AddPath(Prefix+iwithprefixbefore_vals[iwithprefixbefore_idx],
Chris Lattner822da612007-12-17 06:36:45 +0000930 Angled, false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000931 ++iwithprefixbefore_idx;
932 iwithprefixbefore_done =
933 iwithprefixbefore_idx == iwithprefixbefore_vals.size();
934 }
935 }
936 }
Chris Lattner5f9eae52008-03-01 08:07:28 +0000937
938 AddEnvVarPaths("CPATH", Headers);
939 if (Lang.CPlusPlus && Lang.ObjC1)
940 AddEnvVarPaths("OBJCPLUS_INCLUDE_PATH", Headers);
941 else if (Lang.CPlusPlus)
942 AddEnvVarPaths("CPLUS_INCLUDE_PATH", Headers);
943 else if (Lang.ObjC1)
944 AddEnvVarPaths("OBJC_INCLUDE_PATH", Headers);
945 else
946 AddEnvVarPaths("C_INCLUDE_PATH", Headers);
947
Chris Lattnerdcaa0962008-03-03 03:16:03 +0000948 // Add the clang headers, which are relative to the clang driver.
949 llvm::sys::Path MainExecutablePath =
Chris Lattner985e1822008-03-03 05:57:43 +0000950 llvm::sys::Path::GetMainExecutable(Argv0,
951 (void*)(intptr_t)InitializeIncludePaths);
Chris Lattnerdcaa0962008-03-03 03:16:03 +0000952 if (!MainExecutablePath.isEmpty()) {
953 MainExecutablePath.eraseComponent(); // Remove /clang from foo/bin/clang
954 MainExecutablePath.eraseComponent(); // Remove /bin from foo/bin
955 MainExecutablePath.appendComponent("Headers"); // Get foo/Headers
956 AddPath(MainExecutablePath.c_str(), System, false, false, false, Headers);
957 }
958
Reid Spencer5f016e22007-07-11 17:01:13 +0000959 // FIXME: temporary hack: hard-coded paths.
960 // FIXME: get these from the target?
961 if (!nostdinc) {
962 if (Lang.CPlusPlus) {
Ted Kremenek1d3cce32008-05-22 15:26:22 +0000963 AddPath("/usr/include/c++/4.2.1", System, true, false, false, Headers);
964 AddPath("/usr/include/c++/4.2.1/i686-apple-darwin10", System, true, false,
965 false, Headers);
966 AddPath("/usr/include/c++/4.2.1/backward", System, true, false, false,
967 Headers);
968
Chris Lattner822da612007-12-17 06:36:45 +0000969 AddPath("/usr/include/c++/4.0.0", System, true, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000970 AddPath("/usr/include/c++/4.0.0/i686-apple-darwin8", System, true, false,
Chris Lattner822da612007-12-17 06:36:45 +0000971 false, Headers);
972 AddPath("/usr/include/c++/4.0.0/backward", System, true, false, false,
973 Headers);
Lauro Ramos Venancioa6743492008-02-15 22:36:38 +0000974
975 // Ubuntu 7.10 - Gutsy Gibbon
976 AddPath("/usr/include/c++/4.1.3", System, true, false, false, Headers);
977 AddPath("/usr/include/c++/4.1.3/i486-linux-gnu", System, true, false,
978 false, Headers);
979 AddPath("/usr/include/c++/4.1.3/backward", System, true, false, false,
980 Headers);
Chris Lattner04421082008-04-08 04:40:51 +0000981
982 // Fedora 8
983 AddPath("/usr/include/c++/4.1.2", System, true, false, false, Headers);
Chris Lattner8ac661c2008-04-16 05:21:09 +0000984 AddPath("/usr/include/c++/4.1.2/i386-redhat-linux", System, true, false,
985 false, Headers);
986 AddPath("/usr/include/c++/4.1.2/backward", System, true, false, false,
987 Headers);
Ted Kremenekd88fb6c2008-06-24 03:33:47 +0000988
989 // Arch Linux 2008-06-24
990 AddPath("/usr/include/c++/4.3.1", System, true, false, false, Headers);
991 AddPath("/usr/include/c++/4.3.1/i686-pc-linux-gnu", System, true, false,
992 false, Headers);
993 AddPath("/usr/include/c++/4.3.1/backward", System, true, false, false,
994 Headers);
995 AddPath("/usr/include/c++/4.3.1/x86_64-unknown-linux-gnu", System, true,
996 false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +0000997 }
998
Chris Lattner822da612007-12-17 06:36:45 +0000999 AddPath("/usr/local/include", System, false, false, false, Headers);
Ted Kremenek1d3cce32008-05-22 15:26:22 +00001000
1001 AddPath("/usr/lib/gcc/i686-apple-darwin10/4.2.1/include", System,
1002 false, false, false, Headers);
1003 AddPath("/usr/lib/gcc/powerpc-apple-darwin10/4.2.1/include",
1004 System, false, false, false, Headers);
1005
Reid Spencer5f016e22007-07-11 17:01:13 +00001006 // leopard
1007 AddPath("/usr/lib/gcc/i686-apple-darwin9/4.0.1/include", System,
Chris Lattner822da612007-12-17 06:36:45 +00001008 false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +00001009 AddPath("/usr/lib/gcc/powerpc-apple-darwin9/4.0.1/include",
Chris Lattner822da612007-12-17 06:36:45 +00001010 System, false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +00001011 AddPath("/usr/lib/gcc/powerpc-apple-darwin9/"
1012 "4.0.1/../../../../powerpc-apple-darwin0/include",
Chris Lattner822da612007-12-17 06:36:45 +00001013 System, false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +00001014
1015 // tiger
1016 AddPath("/usr/lib/gcc/i686-apple-darwin8/4.0.1/include", System,
Chris Lattner822da612007-12-17 06:36:45 +00001017 false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +00001018 AddPath("/usr/lib/gcc/powerpc-apple-darwin8/4.0.1/include",
Chris Lattner822da612007-12-17 06:36:45 +00001019 System, false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +00001020 AddPath("/usr/lib/gcc/powerpc-apple-darwin8/"
1021 "4.0.1/../../../../powerpc-apple-darwin8/include",
Chris Lattner822da612007-12-17 06:36:45 +00001022 System, false, false, false, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +00001023
Lauro Ramos Venancio397cbf22008-01-21 23:08:35 +00001024 // Ubuntu 7.10 - Gutsy Gibbon
1025 AddPath("/usr/lib/gcc/i486-linux-gnu/4.1.3/include", System,
Chris Lattnerc81c8142008-02-25 21:04:36 +00001026 false, false, false, Headers);
Lauro Ramos Venancio397cbf22008-01-21 23:08:35 +00001027
Chris Lattner04421082008-04-08 04:40:51 +00001028 // Fedora 8
1029 AddPath("/usr/lib/gcc/i386-redhat-linux/4.1.2/include", System,
1030 false, false, false, Headers);
1031
Andrew Lenharth92d56b72008-03-24 21:25:48 +00001032 //Debian testing/lenny x86
1033 AddPath("/usr/lib/gcc/i486-linux-gnu/4.2.3/include", System,
1034 false, false, false, Headers);
Andrew Lenharthf24964c2008-03-24 21:39:05 +00001035
1036 //Debian testing/lenny amd64
1037 AddPath("/usr/lib/gcc/x86_64-linux-gnu/4.2.3/include", System,
1038 false, false, false, Headers);
Andrew Lenharth92d56b72008-03-24 21:25:48 +00001039
Ted Kremenekd88fb6c2008-06-24 03:33:47 +00001040 // Arch Linux 2008-06-24
1041 AddPath("/usr/lib/gcc/i686-pc-linux-gnu/4.3.1/include", System,
1042 false, false, false, Headers);
1043 AddPath("/usr/lib/gcc/i686-pc-linux-gnu/4.3.1/include-fixed", System,
1044 false, false, false, Headers);
1045 AddPath("/usr/lib/gcc/x86_64-unknown-linux-gnu/4.3.1/include", System,
1046 false, false, false, Headers);
1047 AddPath("/usr/lib/gcc/x86_64-unknown-linux-gnu/4.3.1/include-fixed",
1048 System, false, false, false, Headers);
1049
Matthijs Kooijmane9484fc2008-06-26 08:39:30 +00001050 // Debian testing/lenny ppc32
1051 AddPath("/usr/lib/gcc/powerpc-linux-gnu/4.2.3/include", System,
1052 false, false, false, Headers);
1053
Nuno Lopes68bf3872008-07-05 17:15:18 +00001054 // Gentoo x86 stable
1055 AddPath("/usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include", System,
1056 false, false, false, Headers);
1057
Chris Lattner822da612007-12-17 06:36:45 +00001058 AddPath("/usr/include", System, false, false, false, Headers);
1059 AddPath("/System/Library/Frameworks", System, true, false, true, Headers);
1060 AddPath("/Library/Frameworks", System, true, false, true, Headers);
Reid Spencer5f016e22007-07-11 17:01:13 +00001061 }
1062
1063 // Now that we have collected all of the include paths, merge them all
1064 // together and tell the preprocessor about them.
1065
1066 // Concatenate ANGLE+SYSTEM+AFTER chains together into SearchList.
1067 std::vector<DirectoryLookup> SearchList;
1068 SearchList = IncludeGroup[Angled];
1069 SearchList.insert(SearchList.end(), IncludeGroup[System].begin(),
1070 IncludeGroup[System].end());
1071 SearchList.insert(SearchList.end(), IncludeGroup[After].begin(),
1072 IncludeGroup[After].end());
1073 RemoveDuplicates(SearchList);
1074 RemoveDuplicates(IncludeGroup[Quoted]);
1075
1076 // Prepend QUOTED list on the search list.
1077 SearchList.insert(SearchList.begin(), IncludeGroup[Quoted].begin(),
1078 IncludeGroup[Quoted].end());
1079
1080
1081 bool DontSearchCurDir = false; // TODO: set to true if -I- is set?
1082 Headers.SetSearchPaths(SearchList, IncludeGroup[Quoted].size(),
1083 DontSearchCurDir);
1084
1085 // If verbose, print the list of directories that will be searched.
1086 if (Verbose) {
1087 fprintf(stderr, "#include \"...\" search starts here:\n");
1088 unsigned QuotedIdx = IncludeGroup[Quoted].size();
1089 for (unsigned i = 0, e = SearchList.size(); i != e; ++i) {
1090 if (i == QuotedIdx)
1091 fprintf(stderr, "#include <...> search starts here:\n");
Chris Lattner3af66a92007-12-17 17:57:27 +00001092 const char *Name = SearchList[i].getName();
1093 const char *Suffix;
Chris Lattner0048b512007-12-17 17:42:26 +00001094 if (SearchList[i].isNormalDir())
Chris Lattner3af66a92007-12-17 17:57:27 +00001095 Suffix = "";
Chris Lattner0048b512007-12-17 17:42:26 +00001096 else if (SearchList[i].isFramework())
Chris Lattner3af66a92007-12-17 17:57:27 +00001097 Suffix = " (framework directory)";
Chris Lattner0048b512007-12-17 17:42:26 +00001098 else {
1099 assert(SearchList[i].isHeaderMap() && "Unknown DirectoryLookup");
Chris Lattner3af66a92007-12-17 17:57:27 +00001100 Suffix = " (headermap)";
Chris Lattner0048b512007-12-17 17:42:26 +00001101 }
Chris Lattner3af66a92007-12-17 17:57:27 +00001102 fprintf(stderr, " %s%s\n", Name, Suffix);
Reid Spencer5f016e22007-07-11 17:01:13 +00001103 }
Chris Lattner80e17152007-12-15 23:11:06 +00001104 fprintf(stderr, "End of search list.\n");
Reid Spencer5f016e22007-07-11 17:01:13 +00001105 }
1106}
1107
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001108//===----------------------------------------------------------------------===//
1109// Driver PreprocessorFactory - For lazily generating preprocessors ...
1110//===----------------------------------------------------------------------===//
1111
1112namespace {
1113class VISIBILITY_HIDDEN DriverPreprocessorFactory : public PreprocessorFactory {
Ted Kremenek339b9c22008-04-17 22:31:54 +00001114 const std::string &InFile;
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001115 Diagnostic &Diags;
1116 const LangOptions &LangInfo;
1117 TargetInfo &Target;
1118 SourceManager &SourceMgr;
1119 HeaderSearch &HeaderInfo;
Ted Kremenek339b9c22008-04-17 22:31:54 +00001120 bool InitializeSourceMgr;
1121
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001122public:
Ted Kremenek339b9c22008-04-17 22:31:54 +00001123 DriverPreprocessorFactory(const std::string &infile,
1124 Diagnostic &diags, const LangOptions &opts,
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001125 TargetInfo &target, SourceManager &SM,
1126 HeaderSearch &Headers)
Ted Kremenek339b9c22008-04-17 22:31:54 +00001127 : InFile(infile), Diags(diags), LangInfo(opts), Target(target),
1128 SourceMgr(SM), HeaderInfo(Headers), InitializeSourceMgr(true) {}
1129
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001130
1131 virtual ~DriverPreprocessorFactory() {}
1132
1133 virtual Preprocessor* CreatePreprocessor() {
Ted Kremenek339b9c22008-04-17 22:31:54 +00001134 Preprocessor* PP = new Preprocessor(Diags, LangInfo, Target,
1135 SourceMgr, HeaderInfo);
1136
Chris Lattner51574ea2008-04-19 23:25:44 +00001137 if (InitializePreprocessor(*PP, InitializeSourceMgr, InFile)) {
Ted Kremenek339b9c22008-04-17 22:31:54 +00001138 delete PP;
1139 return NULL;
1140 }
1141
1142 InitializeSourceMgr = false;
Ted Kremenek339b9c22008-04-17 22:31:54 +00001143 return PP;
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001144 }
1145};
1146}
Reid Spencer5f016e22007-07-11 17:01:13 +00001147
Reid Spencer5f016e22007-07-11 17:01:13 +00001148//===----------------------------------------------------------------------===//
1149// Basic Parser driver
1150//===----------------------------------------------------------------------===//
1151
Chris Lattner51574ea2008-04-19 23:25:44 +00001152static void ParseFile(Preprocessor &PP, MinimalAction *PA) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001153 Parser P(PP, *PA);
Ted Kremenek95041a22007-12-19 22:51:13 +00001154 PP.EnterMainSourceFile();
Reid Spencer5f016e22007-07-11 17:01:13 +00001155
1156 // Parsing the specified input file.
1157 P.ParseTranslationUnit();
1158 delete PA;
Argyrios Kyrtzidis14d41402008-06-13 12:15:34 +00001159
1160 if (VerifyDiagnostics)
1161 exit(CheckDiagnostics(PP));
Reid Spencer5f016e22007-07-11 17:01:13 +00001162}
1163
1164//===----------------------------------------------------------------------===//
1165// Main driver
1166//===----------------------------------------------------------------------===//
1167
Ted Kremenekdb094a22007-12-05 18:27:04 +00001168/// CreateASTConsumer - Create the ASTConsumer for the corresponding program
1169/// action. These consumers can operate on both ASTs that are freshly
1170/// parsed from source files as well as those deserialized from Bitcode.
Ted Kremenekfdfc1982007-12-19 22:24:34 +00001171static ASTConsumer* CreateASTConsumer(const std::string& InFile,
Ted Kremeneka1fa3a12007-12-13 00:37:31 +00001172 Diagnostic& Diag, FileManager& FileMgr,
Chris Lattnere66b65c2008-02-06 01:42:25 +00001173 const LangOptions& LangOpts,
Chris Lattner3245a0a2008-04-16 06:11:58 +00001174 Preprocessor *PP,
Ted Kremenek339b9c22008-04-17 22:31:54 +00001175 PreprocessorFactory *PPF,
Chris Lattnere66b65c2008-02-06 01:42:25 +00001176 llvm::Module *&DestModule) {
Ted Kremenekdb094a22007-12-05 18:27:04 +00001177 switch (ProgAction) {
1178 default:
1179 return NULL;
1180
1181 case ASTPrint:
1182 return CreateASTPrinter();
1183
1184 case ASTDump:
1185 return CreateASTDumper();
1186
1187 case ASTView:
Ted Kremenek6a340832008-03-18 21:19:49 +00001188 return CreateASTViewer();
1189
1190 case EmitHTML:
Ted Kremenek339b9c22008-04-17 22:31:54 +00001191 return CreateHTMLPrinter(OutputFile, Diag, PP, PPF);
Ted Kremenek902141f2008-07-02 18:23:21 +00001192
Ted Kremenekdb094a22007-12-05 18:27:04 +00001193 case TestSerialization:
Ted Kremeneke7d07d12008-06-04 15:55:15 +00001194 return CreateSerializationTest(Diag, FileMgr);
Ted Kremenekdb094a22007-12-05 18:27:04 +00001195
1196 case EmitLLVM:
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +00001197 case EmitBC:
Chris Lattnere66b65c2008-02-06 01:42:25 +00001198 DestModule = new llvm::Module(InFile);
Sanjiv Guptae8b9f5b2008-05-08 08:54:20 +00001199 return CreateLLVMCodeGen(Diag, LangOpts, DestModule, GenerateDebugInfo);
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +00001200
Ted Kremenek3910c7c2007-12-19 17:25:59 +00001201 case SerializeAST:
Ted Kremeneka1fa3a12007-12-13 00:37:31 +00001202 // FIXME: Allow user to tailor where the file is written.
Ted Kremeneke7d07d12008-06-04 15:55:15 +00001203 return CreateASTSerializer(InFile, OutputFile, Diag);
Ted Kremeneka1fa3a12007-12-13 00:37:31 +00001204
Steve Naroffb29b4272008-04-14 22:03:09 +00001205 case RewriteObjC:
Chris Lattnerc68ab772008-03-22 00:08:40 +00001206 return CreateCodeRewriterTest(InFile, OutputFile, Diag, LangOpts);
Ted Kremenekf4381fd2008-07-02 00:03:09 +00001207
1208 case RunAnalysis:
1209 assert (!AnalysisList.empty());
1210 return CreateAnalysisConsumer(&AnalysisList[0],
1211 &AnalysisList[0]+AnalysisList.size(),
1212 Diag, PP, PPF, LangOpts,
1213 AnalyzeSpecificFunction,
1214 OutputFile, VisualizeEG, TrimGraph,
1215 AnalyzeAll);
Ted Kremenekdb094a22007-12-05 18:27:04 +00001216 }
1217}
1218
Reid Spencer5f016e22007-07-11 17:01:13 +00001219/// ProcessInputFile - Process a single input file with the specified state.
1220///
Ted Kremenek339b9c22008-04-17 22:31:54 +00001221static void ProcessInputFile(Preprocessor &PP, PreprocessorFactory &PPF,
1222 const std::string &InFile) {
Ted Kremenekd39bcd82007-09-26 18:39:29 +00001223
1224 ASTConsumer* Consumer = NULL;
Chris Lattnerbd247762007-07-22 06:05:44 +00001225 bool ClearSourceMgr = false;
Chris Lattnere66b65c2008-02-06 01:42:25 +00001226 llvm::Module *CodeGenModule = 0;
Ted Kremenekd39bcd82007-09-26 18:39:29 +00001227
Reid Spencer5f016e22007-07-11 17:01:13 +00001228 switch (ProgAction) {
1229 default:
Chris Lattner3245a0a2008-04-16 06:11:58 +00001230 Consumer = CreateASTConsumer(InFile, PP.getDiagnostics(),
1231 PP.getFileManager(), PP.getLangOptions(), &PP,
Ted Kremenek339b9c22008-04-17 22:31:54 +00001232 &PPF, CodeGenModule);
Ted Kremenekdb094a22007-12-05 18:27:04 +00001233
1234 if (!Consumer) {
1235 fprintf(stderr, "Unexpected program action!\n");
1236 return;
1237 }
Ted Kremenekfdfc1982007-12-19 22:24:34 +00001238
Ted Kremenekdb094a22007-12-05 18:27:04 +00001239 break;
1240
Reid Spencer5f016e22007-07-11 17:01:13 +00001241 case DumpTokens: { // Token dump mode.
Chris Lattnerd2177732007-07-20 16:59:19 +00001242 Token Tok;
Reid Spencer5f016e22007-07-11 17:01:13 +00001243 // Start parsing the specified input file.
Ted Kremenek95041a22007-12-19 22:51:13 +00001244 PP.EnterMainSourceFile();
Reid Spencer5f016e22007-07-11 17:01:13 +00001245 do {
1246 PP.Lex(Tok);
1247 PP.DumpToken(Tok, true);
1248 fprintf(stderr, "\n");
Chris Lattner057aaf62007-10-09 18:03:42 +00001249 } while (Tok.isNot(tok::eof));
Chris Lattnerbd247762007-07-22 06:05:44 +00001250 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001251 break;
1252 }
1253 case RunPreprocessorOnly: { // Just lex as fast as we can, no output.
Chris Lattnerd2177732007-07-20 16:59:19 +00001254 Token Tok;
Reid Spencer5f016e22007-07-11 17:01:13 +00001255 // Start parsing the specified input file.
Ted Kremenek95041a22007-12-19 22:51:13 +00001256 PP.EnterMainSourceFile();
Reid Spencer5f016e22007-07-11 17:01:13 +00001257 do {
1258 PP.Lex(Tok);
Chris Lattner057aaf62007-10-09 18:03:42 +00001259 } while (Tok.isNot(tok::eof));
Chris Lattnerbd247762007-07-22 06:05:44 +00001260 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001261 break;
1262 }
1263
1264 case PrintPreprocessedInput: // -E mode.
Chris Lattnere988bc22008-01-27 23:55:11 +00001265 DoPrintPreprocessedInput(PP, OutputFile);
Chris Lattnerbd247762007-07-22 06:05:44 +00001266 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001267 break;
Chris Lattnerb57e3d42008-05-08 06:52:13 +00001268
Reid Spencer5f016e22007-07-11 17:01:13 +00001269 case ParseNoop: // -parse-noop
Ted Kremenek95041a22007-12-19 22:51:13 +00001270 ParseFile(PP, new MinimalAction(PP.getIdentifierTable()));
Chris Lattnerbd247762007-07-22 06:05:44 +00001271 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001272 break;
1273
1274 case ParsePrintCallbacks:
Ted Kremenek95041a22007-12-19 22:51:13 +00001275 ParseFile(PP, CreatePrintParserActionsAction(PP.getIdentifierTable()));
Chris Lattnerbd247762007-07-22 06:05:44 +00001276 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001277 break;
Ted Kremenek44579782007-09-25 18:37:20 +00001278
Ted Kremenekd39bcd82007-09-26 18:39:29 +00001279 case ParseSyntaxOnly: // -fsyntax-only
Ted Kremenekd39bcd82007-09-26 18:39:29 +00001280 Consumer = new ASTConsumer();
Ted Kremenek2bf55142007-09-17 20:49:30 +00001281 break;
Chris Lattnerb57e3d42008-05-08 06:52:13 +00001282
1283 case RewriteMacros:
Chris Lattner09510522008-05-09 22:43:24 +00001284 RewriteMacrosInInput(PP, InFile, OutputFile);
Chris Lattnerb57e3d42008-05-08 06:52:13 +00001285 ClearSourceMgr = true;
1286 break;
Chris Lattner580980b2007-09-16 19:46:59 +00001287 }
Ted Kremenekd39bcd82007-09-26 18:39:29 +00001288
1289 if (Consumer) {
Ted Kremenek9f3d9422007-09-26 20:14:22 +00001290 if (VerifyDiagnostics)
Ted Kremenek95041a22007-12-19 22:51:13 +00001291 exit(CheckASTConsumer(PP, Consumer));
Chris Lattner31e6c7d2007-11-03 06:24:16 +00001292
1293 // This deletes Consumer.
Ted Kremenek95041a22007-12-19 22:51:13 +00001294 ParseAST(PP, Consumer, Stats);
Reid Spencer5f016e22007-07-11 17:01:13 +00001295 }
Chris Lattnere66b65c2008-02-06 01:42:25 +00001296
1297 // If running the code generator, finish up now.
1298 if (CodeGenModule) {
1299 std::ostream *Out;
1300 if (OutputFile == "-") {
1301 Out = llvm::cout.stream();
1302 } else if (!OutputFile.empty()) {
1303 Out = new std::ofstream(OutputFile.c_str(),
1304 std::ios_base::binary|std::ios_base::out);
1305 } else if (InFile == "-") {
1306 Out = llvm::cout.stream();
1307 } else {
1308 llvm::sys::Path Path(InFile);
1309 Path.eraseSuffix();
1310 if (ProgAction == EmitLLVM)
1311 Path.appendSuffix("ll");
1312 else if (ProgAction == EmitBC)
1313 Path.appendSuffix("bc");
1314 else
1315 assert(0 && "Unknown action");
1316 Out = new std::ofstream(Path.toString().c_str(),
1317 std::ios_base::binary|std::ios_base::out);
1318 }
1319
1320 if (ProgAction == EmitLLVM) {
1321 CodeGenModule->print(*Out);
1322 } else {
1323 assert(ProgAction == EmitBC);
1324 llvm::WriteBitcodeToFile(CodeGenModule, *Out);
1325 }
1326
1327 if (Out != llvm::cout.stream())
1328 delete Out;
1329 delete CodeGenModule;
1330 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001331
1332 if (Stats) {
Ted Kremenekfdfc1982007-12-19 22:24:34 +00001333 fprintf(stderr, "\nSTATISTICS FOR '%s':\n", InFile.c_str());
Reid Spencer5f016e22007-07-11 17:01:13 +00001334 PP.PrintStats();
1335 PP.getIdentifierTable().PrintStats();
Chris Lattnerdee73592007-12-15 20:48:40 +00001336 PP.getHeaderSearchInfo().PrintStats();
Chris Lattnerbd247762007-07-22 06:05:44 +00001337 if (ClearSourceMgr)
Chris Lattnerdee73592007-12-15 20:48:40 +00001338 PP.getSourceManager().PrintStats();
Reid Spencer5f016e22007-07-11 17:01:13 +00001339 fprintf(stderr, "\n");
1340 }
Chris Lattnerbd247762007-07-22 06:05:44 +00001341
1342 // For a multi-file compilation, some things are ok with nuking the source
1343 // manager tables, other require stable fileid/macroid's across multiple
1344 // files.
Chris Lattnerdee73592007-12-15 20:48:40 +00001345 if (ClearSourceMgr)
1346 PP.getSourceManager().clearIDTables();
Reid Spencer5f016e22007-07-11 17:01:13 +00001347}
1348
Ted Kremenek20e97482007-12-12 23:41:08 +00001349static void ProcessSerializedFile(const std::string& InFile, Diagnostic& Diag,
1350 FileManager& FileMgr) {
1351
1352 if (VerifyDiagnostics) {
1353 fprintf(stderr, "-verify does not yet work with serialized ASTs.\n");
1354 exit (1);
1355 }
1356
1357 llvm::sys::Path Filename(InFile);
1358
1359 if (!Filename.isValid()) {
1360 fprintf(stderr, "serialized file '%s' not available.\n",InFile.c_str());
1361 exit (1);
1362 }
1363
Ted Kremenekc1e9dea2008-04-23 16:25:39 +00001364 llvm::OwningPtr<TranslationUnit> TU(ReadASTBitcodeFile(Filename, FileMgr));
Ted Kremenekfe4e0152007-12-13 18:11:11 +00001365
1366 if (!TU) {
1367 fprintf(stderr, "error: file '%s' could not be deserialized\n",
1368 InFile.c_str());
1369 exit (1);
1370 }
1371
Ted Kremenek63ea8632007-12-19 19:27:38 +00001372 // Observe that we use the source file name stored in the deserialized
1373 // translation unit, rather than InFile.
Chris Lattnere66b65c2008-02-06 01:42:25 +00001374 llvm::Module *DestModule;
Ted Kremenekee533642007-12-20 19:47:16 +00001375 llvm::OwningPtr<ASTConsumer>
Ted Kremeneke7d07d12008-06-04 15:55:15 +00001376 Consumer(CreateASTConsumer(InFile, Diag, FileMgr, TU->getLangOptions(),
1377 0, 0, DestModule));
Ted Kremenek20e97482007-12-12 23:41:08 +00001378
1379 if (!Consumer) {
1380 fprintf(stderr, "Unsupported program action with serialized ASTs!\n");
1381 exit (1);
1382 }
1383
Ted Kremenekc1e9dea2008-04-23 16:25:39 +00001384 Consumer->Initialize(TU->getContext());
Ted Kremenek20e97482007-12-12 23:41:08 +00001385
Chris Lattnere66b65c2008-02-06 01:42:25 +00001386 // FIXME: We need to inform Consumer about completed TagDecls as well.
Ted Kremenek20e97482007-12-12 23:41:08 +00001387 for (TranslationUnit::iterator I=TU->begin(), E=TU->end(); I!=E; ++I)
1388 Consumer->HandleTopLevelDecl(*I);
Ted Kremenek20e97482007-12-12 23:41:08 +00001389}
1390
1391
Reid Spencer5f016e22007-07-11 17:01:13 +00001392static llvm::cl::list<std::string>
1393InputFilenames(llvm::cl::Positional, llvm::cl::desc("<input files>"));
1394
Ted Kremenek20e97482007-12-12 23:41:08 +00001395static bool isSerializedFile(const std::string& InFile) {
1396 if (InFile.size() < 4)
1397 return false;
1398
1399 const char* s = InFile.c_str()+InFile.size()-4;
1400
1401 return s[0] == '.' &&
1402 s[1] == 'a' &&
1403 s[2] == 's' &&
1404 s[3] == 't';
1405}
1406
Reid Spencer5f016e22007-07-11 17:01:13 +00001407
1408int main(int argc, char **argv) {
Chris Lattnerdcaa0962008-03-03 03:16:03 +00001409 llvm::cl::ParseCommandLineOptions(argc, argv, " llvm clang cfe\n");
Reid Spencer5f016e22007-07-11 17:01:13 +00001410 llvm::sys::PrintStackTraceOnErrorSignal();
1411
1412 // If no input was specified, read from stdin.
1413 if (InputFilenames.empty())
1414 InputFilenames.push_back("-");
Ted Kremenek31e703b2007-12-11 23:28:38 +00001415
Reid Spencer5f016e22007-07-11 17:01:13 +00001416 // Create a file manager object to provide access to and cache the filesystem.
1417 FileManager FileMgr;
1418
Ted Kremenek31e703b2007-12-11 23:28:38 +00001419 // Create the diagnostic client for reporting errors or for
1420 // implementing -verify.
Ted Kremenek88f5cde2008-03-27 06:17:42 +00001421 std::auto_ptr<DiagnosticClient> DiagClient;
1422 TextDiagnostics* TextDiagClient = NULL;
1423
1424 if (!HTMLDiag.empty()) {
Ted Kremeneka760f5f2008-04-16 16:53:18 +00001425
1426 // FIXME: The HTMLDiagnosticClient uses the Preprocessor for
1427 // (optional) syntax highlighting, but we don't have a preprocessor yet.
1428 // Fix this dependency later.
Ted Kremenek339b9c22008-04-17 22:31:54 +00001429 DiagClient.reset(CreateHTMLDiagnosticClient(HTMLDiag, 0, 0));
Ted Kremenek88f5cde2008-03-27 06:17:42 +00001430 }
1431 else { // Use Text diagnostics.
1432 if (!VerifyDiagnostics) {
1433 // Print diagnostics to stderr by default.
1434 TextDiagClient = new TextDiagnosticPrinter();
1435 } else {
1436 // When checking diagnostics, just buffer them up.
1437 TextDiagClient = new TextDiagnosticBuffer();
1438
1439 if (InputFilenames.size() != 1) {
1440 fprintf(stderr,
1441 "-verify only works on single input files for now.\n");
1442 return 1;
1443 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001444 }
Ted Kremenek88f5cde2008-03-27 06:17:42 +00001445
1446 assert (TextDiagClient);
1447 DiagClient.reset(TextDiagClient);
Reid Spencer5f016e22007-07-11 17:01:13 +00001448 }
1449
1450 // Configure our handling of diagnostics.
1451 Diagnostic Diags(*DiagClient);
Ted Kremenek31e703b2007-12-11 23:28:38 +00001452 InitializeDiagnostics(Diags);
1453
Chris Lattner4f037832007-12-05 23:24:17 +00001454 // -I- is a deprecated GCC feature, scan for it and reject it.
1455 for (unsigned i = 0, e = I_dirs.size(); i != e; ++i) {
1456 if (I_dirs[i] == "-") {
Ted Kremenek2eefd862007-12-11 22:57:35 +00001457 Diags.Report(diag::err_pp_I_dash_not_supported);
Chris Lattner4f037832007-12-05 23:24:17 +00001458 I_dirs.erase(I_dirs.begin()+i);
1459 --i;
1460 }
1461 }
Chris Lattner11215192008-03-14 06:12:05 +00001462
1463 // Get information about the target being compiled for.
1464 std::string Triple = CreateTargetTriple();
1465 TargetInfo *Target = TargetInfo::CreateTargetInfo(Triple);
1466 if (Target == 0) {
1467 fprintf(stderr, "Sorry, I don't know what target this is: %s\n",
1468 Triple.c_str());
1469 fprintf(stderr, "Please use -triple or -arch.\n");
1470 exit(1);
1471 }
Chris Lattner4f037832007-12-05 23:24:17 +00001472
Ted Kremenekf4381fd2008-07-02 00:03:09 +00001473 // Are we invoking one or more source analyses?
1474 if (!AnalysisList.empty() && ProgAction == ParseSyntaxOnly)
1475 ProgAction = RunAnalysis;
1476
1477
Ted Kremenekc0c03bc2008-06-06 22:42:39 +00001478 llvm::OwningPtr<SourceManager> SourceMgr;
1479
Reid Spencer5f016e22007-07-11 17:01:13 +00001480 for (unsigned i = 0, e = InputFilenames.size(); i != e; ++i) {
Ted Kremenek31e703b2007-12-11 23:28:38 +00001481 const std::string &InFile = InputFilenames[i];
Ted Kremenek31e703b2007-12-11 23:28:38 +00001482
Ted Kremenek20e97482007-12-12 23:41:08 +00001483 if (isSerializedFile(InFile))
1484 ProcessSerializedFile(InFile,Diags,FileMgr);
1485 else {
1486 /// Create a SourceManager object. This tracks and owns all the file
1487 /// buffers allocated to a translation unit.
Ted Kremenekc0c03bc2008-06-06 22:42:39 +00001488 if (!SourceMgr)
1489 SourceMgr.reset(new SourceManager());
1490 else
1491 SourceMgr->clearIDTables();
Ted Kremenek31e703b2007-12-11 23:28:38 +00001492
Ted Kremenek20e97482007-12-12 23:41:08 +00001493 // Initialize language options, inferring file types from input filenames.
1494 LangOptions LangInfo;
1495 InitializeBaseLanguage();
1496 LangKind LK = GetLanguage(InFile);
1497 InitializeLangOptions(LangInfo, LK);
1498 InitializeLanguageStandard(LangInfo, LK);
Ted Kremenek01d9dbf2008-04-29 04:37:03 +00001499 InitializeGCMode(LangInfo);
Ted Kremenek20e97482007-12-12 23:41:08 +00001500
1501 // Process the -I options and set them in the HeaderInfo.
1502 HeaderSearch HeaderInfo(FileMgr);
Ted Kremenek88f5cde2008-03-27 06:17:42 +00001503 if (TextDiagClient) TextDiagClient->setHeaderSearch(HeaderInfo);
Ted Kremenekc68ecb52008-06-06 01:47:30 +00001504
1505 // FIXME: Sink IncludeGroup into this loop.
1506 IncludeGroup[0].clear();
1507 IncludeGroup[1].clear();
1508 IncludeGroup[2].clear();
1509 IncludeGroup[3].clear();
Chris Lattnerdcaa0962008-03-03 03:16:03 +00001510 InitializeIncludePaths(argv[0], HeaderInfo, FileMgr, LangInfo);
Ted Kremenek20e97482007-12-12 23:41:08 +00001511
Ted Kremenek20e97482007-12-12 23:41:08 +00001512 // Set up the preprocessor with these options.
Ted Kremenek339b9c22008-04-17 22:31:54 +00001513 DriverPreprocessorFactory PPFactory(InFile, Diags, LangInfo, *Target,
Ted Kremenekc0c03bc2008-06-06 22:42:39 +00001514 *SourceMgr.get(), HeaderInfo);
Ted Kremenek20e97482007-12-12 23:41:08 +00001515
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001516 llvm::OwningPtr<Preprocessor> PP(PPFactory.CreatePreprocessor());
1517
Ted Kremenek339b9c22008-04-17 22:31:54 +00001518 if (!PP)
Ted Kremenek76edd0e2007-12-19 22:29:55 +00001519 continue;
1520
Ted Kremenek339b9c22008-04-17 22:31:54 +00001521 ProcessInputFile(*PP, PPFactory, InFile);
Ted Kremenekc0c03bc2008-06-06 22:42:39 +00001522 HeaderInfo.ClearFileInfo();
Ted Kremenek20e97482007-12-12 23:41:08 +00001523
1524 if (Stats)
Ted Kremenekc0c03bc2008-06-06 22:42:39 +00001525 SourceMgr->PrintStats();
Ted Kremenek20e97482007-12-12 23:41:08 +00001526 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001527 }
1528
Ted Kremenekc0c03bc2008-06-06 22:42:39 +00001529
Chris Lattner11215192008-03-14 06:12:05 +00001530 delete Target;
1531
Reid Spencer5f016e22007-07-11 17:01:13 +00001532 unsigned NumDiagnostics = Diags.getNumDiagnostics();
1533
1534 if (NumDiagnostics)
1535 fprintf(stderr, "%d diagnostic%s generated.\n", NumDiagnostics,
1536 (NumDiagnostics == 1 ? "" : "s"));
1537
1538 if (Stats) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001539 FileMgr.PrintStats();
1540 fprintf(stderr, "\n");
1541 }
1542
Chris Lattner96f1a642007-07-21 05:40:53 +00001543 return Diags.getNumErrors() != 0;
Reid Spencer5f016e22007-07-11 17:01:13 +00001544}