blob: e935baa27f3a87b7709982313f3209e51b848be1 [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//
Chris Lattnerdddaa9c2009-02-18 01:17:01 +000020// -Wfatal-errors
Reid Spencer5f016e22007-07-11 17:01:13 +000021// -ftabstop=width
22//
23//===----------------------------------------------------------------------===//
24
Eli Friedman0ec78fa2009-05-19 21:10:40 +000025#include "clang/Frontend/AnalysisConsumer.h"
Eli Friedman8ceb0d92009-05-18 23:02:01 +000026#include "clang/Frontend/ASTConsumers.h"
Daniel Dunbare1bd4e62009-03-02 06:16:29 +000027#include "clang/Frontend/CompileOptions.h"
Douglas Gregor558cb562009-04-02 01:08:08 +000028#include "clang/Frontend/FixItRewriter.h"
Daniel Dunbar50f4f462009-03-12 10:14:16 +000029#include "clang/Frontend/FrontendDiagnostic.h"
Daniel Dunbare1bd4e62009-03-02 06:16:29 +000030#include "clang/Frontend/InitHeaderSearch.h"
Chris Lattnere116ccf2009-04-21 05:40:52 +000031#include "clang/Frontend/InitPreprocessor.h"
Daniel Dunbar50f4f462009-03-12 10:14:16 +000032#include "clang/Frontend/PathDiagnosticClients.h"
Douglas Gregor2cf26342009-04-09 22:27:44 +000033#include "clang/Frontend/PCHReader.h"
Daniel Dunbare1bd4e62009-03-02 06:16:29 +000034#include "clang/Frontend/TextDiagnosticBuffer.h"
35#include "clang/Frontend/TextDiagnosticPrinter.h"
Argyrios Kyrtzidis34d25d82009-06-23 22:01:39 +000036#include "clang/Frontend/CommandLineSourceLoc.h"
Eli Friedmanb09f6e12009-05-19 04:14:29 +000037#include "clang/Frontend/Utils.h"
Ted Kremenek88f5cde2008-03-27 06:17:42 +000038#include "clang/Analysis/PathDiagnostic.h"
Chris Lattner8ee3c032008-02-06 02:01:47 +000039#include "clang/CodeGen/ModuleBuilder.h"
Chris Lattnere91c1342008-02-06 00:23:21 +000040#include "clang/Sema/ParseAST.h"
Chris Lattner88eccaf2009-01-29 06:55:46 +000041#include "clang/Sema/SemaDiagnostic.h"
Chris Lattner556beb72007-09-15 22:56:56 +000042#include "clang/AST/ASTConsumer.h"
Chris Lattner1266eca2009-03-28 04:31:31 +000043#include "clang/AST/ASTContext.h"
44#include "clang/AST/Decl.h"
Chris Lattner682bf922009-03-29 16:50:03 +000045#include "clang/AST/DeclGroup.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000046#include "clang/Parse/Parser.h"
47#include "clang/Lex/HeaderSearch.h"
Chris Lattnerdb766842009-02-06 04:16:41 +000048#include "clang/Lex/LexDiagnostic.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000049#include "clang/Basic/FileManager.h"
50#include "clang/Basic/SourceManager.h"
51#include "clang/Basic/TargetInfo.h"
Daniel Dunbaraa338bc2009-05-06 04:07:06 +000052#include "clang/Basic/Version.h"
Owen Anderson42253cc2009-07-01 17:00:06 +000053#include "llvm/LLVMContext.h"
Chris Lattnerba0f25f2008-09-30 20:16:56 +000054#include "llvm/ADT/OwningPtr.h"
Chris Lattner8f3dab82007-12-15 23:20:07 +000055#include "llvm/ADT/SmallPtrSet.h"
Chris Lattnerba0f25f2008-09-30 20:16:56 +000056#include "llvm/ADT/StringExtras.h"
Daniel Dunbar868bd0a2009-05-06 03:16:41 +000057#include "llvm/ADT/StringMap.h"
Chris Lattnerb8e240e2009-04-08 18:24:34 +000058#include "llvm/ADT/STLExtras.h"
Chris Lattnerba0f25f2008-09-30 20:16:56 +000059#include "llvm/Config/config.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000060#include "llvm/Support/CommandLine.h"
Daniel Dunbar524b86f2008-10-28 00:38:08 +000061#include "llvm/Support/ManagedStatic.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000062#include "llvm/Support/MemoryBuffer.h"
Zhongxing Xu20922362008-11-26 05:23:17 +000063#include "llvm/Support/PluginLoader.h"
Chris Lattner09e94a32009-03-04 21:41:39 +000064#include "llvm/Support/PrettyStackTrace.h"
Eli Friedman66d6f042009-05-18 22:20:00 +000065#include "llvm/Support/Streams.h"
Chris Lattner47099742009-02-18 01:51:21 +000066#include "llvm/Support/Timer.h"
Daniel Dunbare553a722008-10-02 01:21:33 +000067#include "llvm/System/Host.h"
Chris Lattnerdcaa0962008-03-03 03:16:03 +000068#include "llvm/System/Path.h"
Douglas Gregor44cf08e2009-05-03 03:52:38 +000069#include "llvm/System/Process.h"
Eli Friedman66d6f042009-05-18 22:20:00 +000070#include "llvm/System/Program.h"
Chris Lattnerba0f25f2008-09-30 20:16:56 +000071#include "llvm/System/Signals.h"
Chris Lattner2fe11942009-06-17 17:25:50 +000072#include "llvm/Target/TargetSelect.h"
Douglas Gregor26df2f02009-04-02 19:05:20 +000073#include <cstdlib>
Douglas Gregor44cf08e2009-05-03 03:52:38 +000074#if HAVE_SYS_TYPES_H
Douglas Gregor68a0d782009-05-02 00:03:46 +000075# include <sys/types.h>
76#endif
Douglas Gregor26df2f02009-04-02 19:05:20 +000077
Reid Spencer5f016e22007-07-11 17:01:13 +000078using namespace clang;
79
80//===----------------------------------------------------------------------===//
Douglas Gregor26df2f02009-04-02 19:05:20 +000081// Source Location Parser
82//===----------------------------------------------------------------------===//
83
Argyrios Kyrtzidis34d25d82009-06-23 22:01:39 +000084static bool ResolveParsedLocation(ParsedSourceLocation &ParsedLoc,
85 FileManager &FileMgr,
86 RequestedSourceLocation &Result) {
87 const FileEntry *File = FileMgr.getFile(ParsedLoc.FileName);
Douglas Gregor26df2f02009-04-02 19:05:20 +000088 if (!File)
89 return true;
90
91 Result.File = File;
Argyrios Kyrtzidis34d25d82009-06-23 22:01:39 +000092 Result.Line = ParsedLoc.Line;
93 Result.Column = ParsedLoc.Column;
Douglas Gregor26df2f02009-04-02 19:05:20 +000094 return false;
95}
96
Douglas Gregor26df2f02009-04-02 19:05:20 +000097//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +000098// Global options.
99//===----------------------------------------------------------------------===//
100
Chris Lattner47099742009-02-18 01:51:21 +0000101/// ClangFrontendTimer - The front-end activities should charge time to it with
102/// TimeRegion. The -ftime-report option controls whether this will do
103/// anything.
104llvm::Timer *ClangFrontendTimer = 0;
105
Daniel Dunbard3db4012008-10-16 16:54:18 +0000106static bool HadErrors = false;
Daniel Dunbarb0adbba2008-10-04 23:42:49 +0000107
Reid Spencer5f016e22007-07-11 17:01:13 +0000108static llvm::cl::opt<bool>
109Verbose("v", llvm::cl::desc("Enable verbose output"));
110static llvm::cl::opt<bool>
Nate Begemanaabbb122007-12-30 01:38:50 +0000111Stats("print-stats",
112 llvm::cl::desc("Print performance metrics and statistics"));
Daniel Dunbard3db4012008-10-16 16:54:18 +0000113static llvm::cl::opt<bool>
114DisableFree("disable-free",
115 llvm::cl::desc("Disable freeing of memory on exit"),
116 llvm::cl::init(false));
Daniel Dunbar57cbfc02009-04-27 21:19:07 +0000117static llvm::cl::opt<bool>
118EmptyInputOnly("empty-input-only",
119 llvm::cl::desc("Force running on an empty input file"));
Reid Spencer5f016e22007-07-11 17:01:13 +0000120
121enum ProgActions {
Steve Naroffb29b4272008-04-14 22:03:09 +0000122 RewriteObjC, // ObjC->C Rewriter.
Steve Naroff13188952008-09-18 14:10:13 +0000123 RewriteBlocks, // ObjC->C Rewriter for Blocks.
Chris Lattnerb57e3d42008-05-08 06:52:13 +0000124 RewriteMacros, // Expand macros but not #includes.
Chris Lattnerb13c5ee2008-10-12 05:29:20 +0000125 RewriteTest, // Rewriter playground
Douglas Gregor558cb562009-04-02 01:08:08 +0000126 FixIt, // Fix-It Rewriter
Ted Kremenek13e479b2008-03-19 07:53:42 +0000127 HTMLTest, // HTML displayer testing stuff.
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000128 EmitAssembly, // Emit a .s file.
Reid Spencer5f016e22007-07-11 17:01:13 +0000129 EmitLLVM, // Emit a .ll file.
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +0000130 EmitBC, // Emit a .bc file.
Daniel Dunbare8e26002009-02-26 22:39:37 +0000131 EmitLLVMOnly, // Generate LLVM IR, but do not
Ted Kremenek6a340832008-03-18 21:19:49 +0000132 EmitHTML, // Translate input source into HTML.
Chris Lattner3b427b32007-10-11 00:18:28 +0000133 ASTPrint, // Parse ASTs and print them.
Douglas Gregoree75c052009-05-21 20:55:50 +0000134 ASTPrintXML, // Parse ASTs and print them in XML.
Chris Lattner3b427b32007-10-11 00:18:28 +0000135 ASTDump, // Parse ASTs and dump them.
136 ASTView, // Parse ASTs and view them in Graphviz.
Zhongxing Xu2d75d6f2009-01-13 01:29:24 +0000137 PrintDeclContext, // Print DeclContext and their Decls.
Reid Spencer5f016e22007-07-11 17:01:13 +0000138 ParsePrintCallbacks, // Parse and print each callback.
139 ParseSyntaxOnly, // Parse and perform semantic analysis.
140 ParseNoop, // Parse with noop callbacks.
141 RunPreprocessorOnly, // Just lex, no output.
142 PrintPreprocessedInput, // -E mode.
Chris Lattnerc106c102008-10-12 05:03:36 +0000143 DumpTokens, // Dump out preprocessed tokens.
144 DumpRawTokens, // Dump out raw tokens.
Ted Kremenek85888962008-10-21 00:54:44 +0000145 RunAnalysis, // Run one or more source code analyses.
Douglas Gregorbf1bd6e2009-04-02 23:43:50 +0000146 GeneratePTH, // Generate pre-tokenized header.
Douglas Gregor2cf26342009-04-09 22:27:44 +0000147 GeneratePCH, // Generate pre-compiled header.
Ted Kremenek7cae2f62008-10-23 23:36:29 +0000148 InheritanceView // View C++ inheritance for a specified class.
Reid Spencer5f016e22007-07-11 17:01:13 +0000149};
150
151static llvm::cl::opt<ProgActions>
152ProgAction(llvm::cl::desc("Choose output type:"), llvm::cl::ZeroOrMore,
153 llvm::cl::init(ParseSyntaxOnly),
154 llvm::cl::values(
155 clEnumValN(RunPreprocessorOnly, "Eonly",
156 "Just run preprocessor, no output (for timings)"),
157 clEnumValN(PrintPreprocessedInput, "E",
158 "Run preprocessor, emit preprocessed file"),
Chris Lattnerc106c102008-10-12 05:03:36 +0000159 clEnumValN(DumpRawTokens, "dump-raw-tokens",
160 "Lex file in raw mode and dump raw tokens"),
Daniel Dunbard4270232009-01-20 23:17:32 +0000161 clEnumValN(RunAnalysis, "analyze",
162 "Run static analysis engine"),
Chris Lattnerc106c102008-10-12 05:03:36 +0000163 clEnumValN(DumpTokens, "dump-tokens",
Reid Spencer5f016e22007-07-11 17:01:13 +0000164 "Run preprocessor, dump internal rep of tokens"),
165 clEnumValN(ParseNoop, "parse-noop",
166 "Run parser with noop callbacks (for timings)"),
167 clEnumValN(ParseSyntaxOnly, "fsyntax-only",
168 "Run parser and perform semantic analysis"),
169 clEnumValN(ParsePrintCallbacks, "parse-print-callbacks",
170 "Run parser and print each callback invoked"),
Ted Kremenek6a340832008-03-18 21:19:49 +0000171 clEnumValN(EmitHTML, "emit-html",
172 "Output input source as HTML"),
Chris Lattner3b427b32007-10-11 00:18:28 +0000173 clEnumValN(ASTPrint, "ast-print",
174 "Build ASTs and then pretty-print them"),
Douglas Gregoree75c052009-05-21 20:55:50 +0000175 clEnumValN(ASTPrintXML, "ast-print-xml",
176 "Build ASTs and then print them in XML format"),
Chris Lattner3b427b32007-10-11 00:18:28 +0000177 clEnumValN(ASTDump, "ast-dump",
178 "Build ASTs and then debug dump them"),
Chris Lattnerea254db2007-10-11 00:37:43 +0000179 clEnumValN(ASTView, "ast-view",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000180 "Build ASTs and view them with GraphViz"),
Zhongxing Xu2d75d6f2009-01-13 01:29:24 +0000181 clEnumValN(PrintDeclContext, "print-decl-contexts",
Ted Kremenek08478eb2009-04-01 00:23:28 +0000182 "Print DeclContexts and their Decls"),
Douglas Gregorbf1bd6e2009-04-02 23:43:50 +0000183 clEnumValN(GeneratePTH, "emit-pth",
Ted Kremenek08478eb2009-04-01 00:23:28 +0000184 "Generate pre-tokenized header file"),
Douglas Gregor2cf26342009-04-09 22:27:44 +0000185 clEnumValN(GeneratePCH, "emit-pch",
186 "Generate pre-compiled header file"),
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000187 clEnumValN(EmitAssembly, "S",
188 "Emit native assembly code"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000189 clEnumValN(EmitLLVM, "emit-llvm",
Ted Kremenek27b07c52007-09-06 21:26:58 +0000190 "Build ASTs then convert to LLVM, emit .ll file"),
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +0000191 clEnumValN(EmitBC, "emit-llvm-bc",
192 "Build ASTs then convert to LLVM, emit .bc file"),
Daniel Dunbare8e26002009-02-26 22:39:37 +0000193 clEnumValN(EmitLLVMOnly, "emit-llvm-only",
194 "Build ASTs and convert to LLVM, discarding output"),
Chris Lattnerb13c5ee2008-10-12 05:29:20 +0000195 clEnumValN(RewriteTest, "rewrite-test",
196 "Rewriter playground"),
Steve Naroffb29b4272008-04-14 22:03:09 +0000197 clEnumValN(RewriteObjC, "rewrite-objc",
Chris Lattnerb57e3d42008-05-08 06:52:13 +0000198 "Rewrite ObjC into C (code rewriter example)"),
199 clEnumValN(RewriteMacros, "rewrite-macros",
200 "Expand macros without full preprocessing"),
Steve Naroff13188952008-09-18 14:10:13 +0000201 clEnumValN(RewriteBlocks, "rewrite-blocks",
202 "Rewrite Blocks to C"),
Douglas Gregor558cb562009-04-02 01:08:08 +0000203 clEnumValN(FixIt, "fixit",
204 "Apply fix-it advice to the input source"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000205 clEnumValEnd));
206
Ted Kremenekccc76472007-12-19 19:47:59 +0000207
208static llvm::cl::opt<std::string>
209OutputFile("o",
Ted Kremenek50b56412007-12-19 19:50:41 +0000210 llvm::cl::value_desc("path"),
Douglas Gregor370187c2009-04-22 21:45:53 +0000211 llvm::cl::desc("Specify output file"));
Ted Kremenek55af98c2008-04-14 18:40:58 +0000212
Ted Kremenekc2e72992008-12-02 19:57:31 +0000213
214//===----------------------------------------------------------------------===//
215// PTH.
216//===----------------------------------------------------------------------===//
217
218static llvm::cl::opt<std::string>
219TokenCache("token-cache", llvm::cl::value_desc("path"),
220 llvm::cl::desc("Use specified token cache file"));
221
Sanjiv Guptae8b9f5b2008-05-08 08:54:20 +0000222//===----------------------------------------------------------------------===//
Ted Kremenek55af98c2008-04-14 18:40:58 +0000223// Diagnostic Options
224//===----------------------------------------------------------------------===//
225
Ted Kremenek41193e42007-09-26 19:42:19 +0000226static llvm::cl::opt<bool>
227VerifyDiagnostics("verify",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000228 llvm::cl::desc("Verify emitted diagnostics and warnings"));
Ted Kremenek41193e42007-09-26 19:42:19 +0000229
Ted Kremenek88f5cde2008-03-27 06:17:42 +0000230static llvm::cl::opt<std::string>
231HTMLDiag("html-diags",
232 llvm::cl::desc("Generate HTML to report diagnostics"),
233 llvm::cl::value_desc("HTML directory"));
234
Nico Weberfd54ebc2008-08-05 23:33:20 +0000235static llvm::cl::opt<bool>
236NoShowColumn("fno-show-column",
237 llvm::cl::desc("Do not include column number on diagnostics"));
238
239static llvm::cl::opt<bool>
Chris Lattner65f5e642009-01-30 19:01:41 +0000240NoShowLocation("fno-show-source-location",
241 llvm::cl::desc("Do not include source location information with"
242 " diagnostics"));
243
244static llvm::cl::opt<bool>
Nico Weberfd54ebc2008-08-05 23:33:20 +0000245NoCaretDiagnostics("fno-caret-diagnostics",
246 llvm::cl::desc("Do not include source line and caret with"
247 " diagnostics"));
248
Chris Lattner1fbee5d2009-03-13 01:08:23 +0000249static llvm::cl::opt<bool>
Chris Lattneraa5bf2e2009-04-19 07:44:08 +0000250NoDiagnosticsFixIt("fno-diagnostics-fixit-info",
251 llvm::cl::desc("Do not include fixit information in"
252 " diagnostics"));
253
254static llvm::cl::opt<bool>
Chris Lattner182e0922009-04-21 05:34:31 +0000255PrintSourceRangeInfo("fdiagnostics-print-source-range-info",
256 llvm::cl::desc("Print source range spans in numeric form"));
257
Chris Lattnerd51d74a2009-04-16 05:44:38 +0000258static llvm::cl::opt<bool>
259PrintDiagnosticOption("fdiagnostics-show-option",
260 llvm::cl::desc("Print diagnostic name with mappable diagnostics"));
Nico Weberfd54ebc2008-08-05 23:33:20 +0000261
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000262static llvm::cl::opt<unsigned>
263MessageLength("fmessage-length",
264 llvm::cl::desc("Format message diagnostics so that they fit "
265 "within N columns or fewer, when possible."),
266 llvm::cl::value_desc("N"));
267
Torok Edwin603fca72009-06-04 07:18:23 +0000268static llvm::cl::opt<bool>
Torok Edwina46c71a2009-06-04 07:27:53 +0000269NoColorDiagnostic("fno-color-diagnostics",
Torok Edwin603fca72009-06-04 07:18:23 +0000270 llvm::cl::desc("Don't use colors when showing diagnostics "
271 "(automatically turned off if output is not a "
272 "terminal)."));
Reid Spencer5f016e22007-07-11 17:01:13 +0000273//===----------------------------------------------------------------------===//
Ted Kremenek7cae2f62008-10-23 23:36:29 +0000274// C++ Visualization.
275//===----------------------------------------------------------------------===//
276
277static llvm::cl::opt<std::string>
278InheritanceViewCls("cxx-inheritance-view",
279 llvm::cl::value_desc("class name"),
Daniel Dunbard77b2512009-01-14 18:56:36 +0000280 llvm::cl::desc("View C++ inheritance for a specified class"));
Ted Kremenek7cae2f62008-10-23 23:36:29 +0000281
282//===----------------------------------------------------------------------===//
Douglas Gregor3573c0c2009-02-14 20:49:29 +0000283// Builtin Options
284//===----------------------------------------------------------------------===//
Chris Lattnerb2509e12009-02-18 01:12:43 +0000285
286static llvm::cl::opt<bool>
287TimeReport("ftime-report",
288 llvm::cl::desc("Print the amount of time each "
289 "phase of compilation takes"));
290
Douglas Gregor3573c0c2009-02-14 20:49:29 +0000291static llvm::cl::opt<bool>
292Freestanding("ffreestanding",
Daniel Dunbaref2abfe2009-02-16 22:43:43 +0000293 llvm::cl::desc("Assert that the compilation takes place in a "
Douglas Gregor3573c0c2009-02-14 20:49:29 +0000294 "freestanding environment"));
295
Daniel Dunbaref2abfe2009-02-16 22:43:43 +0000296static llvm::cl::opt<bool>
Daniel Dunbar48d1ef72009-04-07 21:16:11 +0000297AllowBuiltins("fbuiltin", llvm::cl::init(true),
298 llvm::cl::desc("Disable implicit builtin knowledge of functions"));
Chris Lattner7644f072009-03-13 22:38:49 +0000299
300
301static llvm::cl::opt<bool>
Daniel Dunbar48d1ef72009-04-07 21:16:11 +0000302MathErrno("fmath-errno", llvm::cl::init(true),
303 llvm::cl::desc("Require math functions to respect errno"));
Daniel Dunbaref2abfe2009-02-16 22:43:43 +0000304
Douglas Gregor3573c0c2009-02-14 20:49:29 +0000305//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +0000306// Language Options
307//===----------------------------------------------------------------------===//
308
309enum LangKind {
310 langkind_unspecified,
311 langkind_c,
312 langkind_c_cpp,
Chris Lattnera778d7d2008-10-22 17:29:21 +0000313 langkind_asm_cpp,
Reid Spencer5f016e22007-07-11 17:01:13 +0000314 langkind_cxx,
315 langkind_cxx_cpp,
316 langkind_objc,
317 langkind_objc_cpp,
318 langkind_objcxx,
Nate Begeman4e3629e2009-06-25 22:43:10 +0000319 langkind_objcxx_cpp,
320 langkind_ocl
Reid Spencer5f016e22007-07-11 17:01:13 +0000321};
322
Reid Spencer5f016e22007-07-11 17:01:13 +0000323static llvm::cl::opt<LangKind>
324BaseLang("x", llvm::cl::desc("Base language to compile"),
325 llvm::cl::init(langkind_unspecified),
326 llvm::cl::values(clEnumValN(langkind_c, "c", "C"),
Nate Begeman4e3629e2009-06-25 22:43:10 +0000327 clEnumValN(langkind_ocl, "cl", "OpenCL C"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000328 clEnumValN(langkind_cxx, "c++", "C++"),
329 clEnumValN(langkind_objc, "objective-c", "Objective C"),
330 clEnumValN(langkind_objcxx,"objective-c++","Objective C++"),
Daniel Dunbard2ea3862009-01-29 23:50:47 +0000331 clEnumValN(langkind_c_cpp, "cpp-output",
Reid Spencer5f016e22007-07-11 17:01:13 +0000332 "Preprocessed C"),
Chris Lattnera778d7d2008-10-22 17:29:21 +0000333 clEnumValN(langkind_asm_cpp, "assembler-with-cpp",
334 "Preprocessed asm"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000335 clEnumValN(langkind_cxx_cpp, "c++-cpp-output",
Chris Lattnerc76d8072009-02-06 06:19:20 +0000336 "Preprocessed C++"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000337 clEnumValN(langkind_objc_cpp, "objective-c-cpp-output",
338 "Preprocessed Objective C"),
Chris Lattnerc76d8072009-02-06 06:19:20 +0000339 clEnumValN(langkind_objcxx_cpp, "objective-c++-cpp-output",
Reid Spencer5f016e22007-07-11 17:01:13 +0000340 "Preprocessed Objective C++"),
Daniel Dunbar0b5b0da2009-04-01 05:09:09 +0000341 clEnumValN(langkind_c, "c-header",
342 "C header"),
343 clEnumValN(langkind_objc, "objective-c-header",
344 "Objective-C header"),
345 clEnumValN(langkind_cxx, "c++-header",
346 "C++ header"),
347 clEnumValN(langkind_objcxx, "objective-c++-header",
348 "Objective-C++ header"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000349 clEnumValEnd));
350
351static llvm::cl::opt<bool>
352LangObjC("ObjC", llvm::cl::desc("Set base language to Objective-C"),
353 llvm::cl::Hidden);
354static llvm::cl::opt<bool>
355LangObjCXX("ObjC++", llvm::cl::desc("Set base language to Objective-C++"),
356 llvm::cl::Hidden);
357
Chris Lattner2c78b872009-04-14 23:22:57 +0000358static llvm::cl::opt<bool>
359ObjCExclusiveGC("fobjc-gc-only",
360 llvm::cl::desc("Use GC exclusively for Objective-C related "
361 "memory management"));
362
363static llvm::cl::opt<bool>
364ObjCEnableGC("fobjc-gc",
365 llvm::cl::desc("Enable Objective-C garbage collection"));
366
Fariborz Jahanian448f5e62009-04-17 03:04:15 +0000367static llvm::cl::opt<bool>
368ObjCEnableGCBitmapPrint("print-ivar-layout",
369 llvm::cl::desc("Enable Objective-C Ivar layout bitmap print trace"));
370
Chris Lattner2c78b872009-04-14 23:22:57 +0000371static llvm::cl::opt<LangOptions::VisibilityMode>
372SymbolVisibility("fvisibility",
373 llvm::cl::desc("Set the default symbol visibility:"),
374 llvm::cl::init(LangOptions::Default),
375 llvm::cl::values(clEnumValN(LangOptions::Default, "default",
376 "Use default symbol visibility"),
377 clEnumValN(LangOptions::Hidden, "hidden",
378 "Use hidden symbol visibility"),
379 clEnumValN(LangOptions::Protected,"protected",
380 "Use protected symbol visibility"),
381 clEnumValEnd));
382
383static llvm::cl::opt<bool>
384OverflowChecking("ftrapv",
385 llvm::cl::desc("Trap on integer overflow"),
386 llvm::cl::init(false));
387
Fariborz Jahanian34e65772009-05-22 20:17:16 +0000388static llvm::cl::opt<bool>
389ObjCSenderDispatch("fobjc-sender-dependent-dispatch",
390 llvm::cl::desc("Enable sender-dependent dispatch for"
391 "Objective-C messages"), llvm::cl::init(false));
Chris Lattner2c78b872009-04-14 23:22:57 +0000392
Ted Kremenek8904f152007-12-05 23:49:08 +0000393/// InitializeBaseLanguage - Handle the -x foo options.
394static void InitializeBaseLanguage() {
395 if (LangObjC)
396 BaseLang = langkind_objc;
397 else if (LangObjCXX)
398 BaseLang = langkind_objcxx;
399}
400
401static LangKind GetLanguage(const std::string &Filename) {
402 if (BaseLang != langkind_unspecified)
403 return BaseLang;
404
405 std::string::size_type DotPos = Filename.rfind('.');
406
407 if (DotPos == std::string::npos) {
408 BaseLang = langkind_c; // Default to C if no extension.
Chris Lattner9b2f6c42008-01-04 19:12:28 +0000409 return langkind_c;
Reid Spencer5f016e22007-07-11 17:01:13 +0000410 }
411
Ted Kremenek8904f152007-12-05 23:49:08 +0000412 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
413 // C header: .h
414 // C++ header: .hh or .H;
415 // assembler no preprocessing: .s
416 // assembler: .S
417 if (Ext == "c")
418 return langkind_c;
Chris Lattnerd9cd4c92009-03-23 16:24:37 +0000419 else if (Ext == "S" ||
420 // If the compiler is run on a .s file, preprocess it as .S
421 Ext == "s")
Chris Lattnera778d7d2008-10-22 17:29:21 +0000422 return langkind_asm_cpp;
Ted Kremenek8904f152007-12-05 23:49:08 +0000423 else if (Ext == "i")
424 return langkind_c_cpp;
425 else if (Ext == "ii")
426 return langkind_cxx_cpp;
427 else if (Ext == "m")
428 return langkind_objc;
429 else if (Ext == "mi")
430 return langkind_objc_cpp;
431 else if (Ext == "mm" || Ext == "M")
432 return langkind_objcxx;
433 else if (Ext == "mii")
434 return langkind_objcxx_cpp;
435 else if (Ext == "C" || Ext == "cc" || Ext == "cpp" || Ext == "CPP" ||
436 Ext == "c++" || Ext == "cp" || Ext == "cxx")
437 return langkind_cxx;
Nate Begeman4e3629e2009-06-25 22:43:10 +0000438 else if (Ext == "cl")
439 return langkind_ocl;
Ted Kremenek8904f152007-12-05 23:49:08 +0000440 else
441 return langkind_c;
442}
443
444
Ted Kremenek85888962008-10-21 00:54:44 +0000445static void InitializeCOptions(LangOptions &Options) {
446 // Do nothing.
447}
448
449static void InitializeObjCOptions(LangOptions &Options) {
450 Options.ObjC1 = Options.ObjC2 = 1;
451}
452
453
Daniel Dunbar0b5b0da2009-04-01 05:09:09 +0000454static void InitializeLangOptions(LangOptions &Options, LangKind LK){
Reid Spencer5f016e22007-07-11 17:01:13 +0000455 // FIXME: implement -fpreprocessed mode.
456 bool NoPreprocess = false;
457
Ted Kremenek8904f152007-12-05 23:49:08 +0000458 switch (LK) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000459 default: assert(0 && "Unknown language kind!");
Chris Lattnera778d7d2008-10-22 17:29:21 +0000460 case langkind_asm_cpp:
Daniel Dunbarc1571452008-12-01 18:55:22 +0000461 Options.AsmPreprocessor = 1;
Chris Lattnera778d7d2008-10-22 17:29:21 +0000462 // FALLTHROUGH
Reid Spencer5f016e22007-07-11 17:01:13 +0000463 case langkind_c_cpp:
464 NoPreprocess = true;
465 // FALLTHROUGH
466 case langkind_c:
Ted Kremenek85888962008-10-21 00:54:44 +0000467 InitializeCOptions(Options);
Reid Spencer5f016e22007-07-11 17:01:13 +0000468 break;
469 case langkind_cxx_cpp:
470 NoPreprocess = true;
471 // FALLTHROUGH
472 case langkind_cxx:
473 Options.CPlusPlus = 1;
474 break;
475 case langkind_objc_cpp:
476 NoPreprocess = true;
477 // FALLTHROUGH
478 case langkind_objc:
Ted Kremenek85888962008-10-21 00:54:44 +0000479 InitializeObjCOptions(Options);
Reid Spencer5f016e22007-07-11 17:01:13 +0000480 break;
481 case langkind_objcxx_cpp:
482 NoPreprocess = true;
483 // FALLTHROUGH
484 case langkind_objcxx:
485 Options.ObjC1 = Options.ObjC2 = 1;
486 Options.CPlusPlus = 1;
487 break;
Nate Begeman4e3629e2009-06-25 22:43:10 +0000488 case langkind_ocl:
489 Options.OpenCL = 1;
490 Options.AltiVec = 1;
491 Options.CXXOperatorNames = 1;
492 Options.LaxVectorConversions = 1;
493 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000494 }
Chris Lattner2c78b872009-04-14 23:22:57 +0000495
496 if (ObjCExclusiveGC)
497 Options.setGCMode(LangOptions::GCOnly);
498 else if (ObjCEnableGC)
499 Options.setGCMode(LangOptions::HybridGC);
500
Fariborz Jahanian448f5e62009-04-17 03:04:15 +0000501 if (ObjCEnableGCBitmapPrint)
502 Options.ObjCGCBitmapPrint = 1;
503
Chris Lattner2c78b872009-04-14 23:22:57 +0000504 Options.setVisibilityMode(SymbolVisibility);
505 Options.OverflowChecking = OverflowChecking;
Reid Spencer5f016e22007-07-11 17:01:13 +0000506}
507
508/// LangStds - Language standards we support.
509enum LangStds {
510 lang_unspecified,
511 lang_c89, lang_c94, lang_c99,
Ted Kremenekea644d82008-09-03 21:22:16 +0000512 lang_gnu_START,
513 lang_gnu89 = lang_gnu_START, lang_gnu99,
Chris Lattnerd4b80f12007-07-16 04:18:29 +0000514 lang_cxx98, lang_gnucxx98,
515 lang_cxx0x, lang_gnucxx0x
Reid Spencer5f016e22007-07-11 17:01:13 +0000516};
517
518static llvm::cl::opt<LangStds>
519LangStd("std", llvm::cl::desc("Language standard to compile for"),
520 llvm::cl::init(lang_unspecified),
521 llvm::cl::values(clEnumValN(lang_c89, "c89", "ISO C 1990"),
522 clEnumValN(lang_c89, "c90", "ISO C 1990"),
523 clEnumValN(lang_c89, "iso9899:1990", "ISO C 1990"),
524 clEnumValN(lang_c94, "iso9899:199409",
525 "ISO C 1990 with amendment 1"),
526 clEnumValN(lang_c99, "c99", "ISO C 1999"),
Chris Lattner50748f42009-04-06 17:17:55 +0000527 clEnumValN(lang_c99, "c9x", "ISO C 1999"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000528 clEnumValN(lang_c99, "iso9899:1999", "ISO C 1999"),
Chris Lattner50748f42009-04-06 17:17:55 +0000529 clEnumValN(lang_c99, "iso9899:199x", "ISO C 1999"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000530 clEnumValN(lang_gnu89, "gnu89",
Gabor Greif10b26142009-02-28 09:22:15 +0000531 "ISO C 1990 with GNU extensions"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000532 clEnumValN(lang_gnu99, "gnu99",
Gabor Greif10b26142009-02-28 09:22:15 +0000533 "ISO C 1999 with GNU extensions (default for C)"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000534 clEnumValN(lang_gnu99, "gnu9x",
535 "ISO C 1999 with GNU extensions"),
536 clEnumValN(lang_cxx98, "c++98",
537 "ISO C++ 1998 with amendments"),
538 clEnumValN(lang_gnucxx98, "gnu++98",
539 "ISO C++ 1998 with amendments and GNU "
540 "extensions (default for C++)"),
Chris Lattnerd4b80f12007-07-16 04:18:29 +0000541 clEnumValN(lang_cxx0x, "c++0x",
542 "Upcoming ISO C++ 200x with amendments"),
543 clEnumValN(lang_gnucxx0x, "gnu++0x",
544 "Upcoming ISO C++ 200x with amendments and GNU "
Gabor Greif5f8d1db2009-03-11 23:07:18 +0000545 "extensions"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000546 clEnumValEnd));
547
548static llvm::cl::opt<bool>
549NoOperatorNames("fno-operator-names",
550 llvm::cl::desc("Do not treat C++ operator name keywords as "
551 "synonyms for operators"));
552
Anders Carlssonee98ac52007-10-15 02:50:23 +0000553static llvm::cl::opt<bool>
554PascalStrings("fpascal-strings",
555 llvm::cl::desc("Recognize and construct Pascal-style "
556 "string literals"));
Steve Naroffd62701b2008-02-07 03:50:06 +0000557
558static llvm::cl::opt<bool>
559MSExtensions("fms-extensions",
560 llvm::cl::desc("Accept some non-standard constructs used in "
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000561 "Microsoft header files "));
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000562
563static llvm::cl::opt<bool>
564WritableStrings("fwritable-strings",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000565 llvm::cl::desc("Store string literals as writable data"));
Anders Carlsson695dbb62007-11-30 04:21:22 +0000566
567static llvm::cl::opt<bool>
Anders Carlssonad53eff2009-01-30 23:26:40 +0000568NoLaxVectorConversions("fno-lax-vector-conversions",
Anders Carlssonb0f90cc2009-01-30 23:17:46 +0000569 llvm::cl::desc("Disallow implicit conversions between "
570 "vectors with a different number of "
571 "elements or different element types"));
Chris Lattnerae0ee032008-12-04 23:20:07 +0000572
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000573static llvm::cl::opt<bool>
Daniel Dunbar48d1ef72009-04-07 21:16:11 +0000574EnableBlocks("fblocks", llvm::cl::desc("enable the 'blocks' language feature"));
Mike Stumpa0f02aa2009-02-02 22:57:57 +0000575
576static llvm::cl::opt<bool>
Chris Lattner810f6d52009-03-13 17:38:01 +0000577EnableHeinousExtensions("fheinous-gnu-extensions",
578 llvm::cl::desc("enable GNU extensions that you really really shouldn't use"),
579 llvm::cl::ValueDisallowed, llvm::cl::Hidden);
580
581static llvm::cl::opt<bool>
Mike Stumpa0f02aa2009-02-02 22:57:57 +0000582ObjCNonFragileABI("fobjc-nonfragile-abi",
583 llvm::cl::desc("enable objective-c's nonfragile abi"));
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000584
Daniel Dunbard6884a02009-05-04 05:16:21 +0000585
586static llvm::cl::opt<bool>
Daniel Dunbard604c402009-02-04 21:19:06 +0000587EmitAllDecls("femit-all-decls",
588 llvm::cl::desc("Emit all declarations, even if unused"));
Ted Kremenek01d9dbf2008-04-29 04:37:03 +0000589
Daniel Dunbar6379a7a2008-08-11 17:36:14 +0000590static llvm::cl::opt<bool>
591Exceptions("fexceptions",
Chris Lattnerf5db8f82009-04-19 07:00:02 +0000592 llvm::cl::desc("Enable support for exception handling"));
Daniel Dunbar6379a7a2008-08-11 17:36:14 +0000593
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000594static llvm::cl::opt<bool>
Mike Stump738f8c22009-07-31 23:15:31 +0000595Rtti("frtti", llvm::cl::init(true),
596 llvm::cl::desc("Enable generation of rtti information"));
597
598static llvm::cl::opt<bool>
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000599GNURuntime("fgnu-runtime",
Ted Kremenek85888962008-10-21 00:54:44 +0000600 llvm::cl::desc("Generate output compatible with the standard GNU "
Chris Lattnerf5db8f82009-04-19 07:00:02 +0000601 "Objective-C runtime"));
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000602
603static llvm::cl::opt<bool>
604NeXTRuntime("fnext-runtime",
Ted Kremenek85888962008-10-21 00:54:44 +0000605 llvm::cl::desc("Generate output compatible with the NeXT "
Chris Lattnerf5db8f82009-04-19 07:00:02 +0000606 "runtime"));
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000607
Eli Friedmanc4757bd2009-06-05 07:12:17 +0000608static llvm::cl::opt<bool>
609CharIsSigned("fsigned-char",
610 llvm::cl::desc("Force char to be a signed/unsigned type"));
Ted Kremenekea644d82008-09-03 21:22:16 +0000611
612
613static llvm::cl::opt<bool>
Chris Lattnerf5db8f82009-04-19 07:00:02 +0000614Trigraphs("trigraphs", llvm::cl::desc("Process trigraph sequences"));
Ted Kremenekea644d82008-09-03 21:22:16 +0000615
Douglas Gregor26dce442009-03-10 00:06:19 +0000616static llvm::cl::opt<unsigned>
617TemplateDepth("ftemplate-depth", llvm::cl::init(99),
618 llvm::cl::desc("Maximum depth of recursive template "
619 "instantiation"));
Chris Lattnerf5db8f82009-04-19 07:00:02 +0000620static llvm::cl::opt<bool>
621DollarsInIdents("fdollars-in-identifiers",
622 llvm::cl::desc("Allow '$' in identifiers"));
Chris Lattner16167a62009-03-02 22:11:07 +0000623
Anders Carlsson4ca076f2009-04-06 17:37:10 +0000624
625static llvm::cl::opt<bool>
626OptSize("Os", llvm::cl::desc("Optimize for size"));
627
628static llvm::cl::opt<bool>
Daniel Dunbar877db382009-06-02 22:07:45 +0000629DisableLLVMOptimizations("disable-llvm-optzns",
630 llvm::cl::desc("Don't run LLVM optimization passes"));
631
632static llvm::cl::opt<bool>
Anders Carlsson4ca076f2009-04-06 17:37:10 +0000633NoCommon("fno-common",
634 llvm::cl::desc("Compile common globals like normal definitions"),
635 llvm::cl::ValueDisallowed);
636
Daniel Dunbarc9abc042009-04-08 05:11:16 +0000637static llvm::cl::opt<std::string>
638MainFileName("main-file-name",
639 llvm::cl::desc("Main file name to use for debug info"));
Anders Carlsson4ca076f2009-04-06 17:37:10 +0000640
Anders Carlssona33d9b42009-05-13 19:49:53 +0000641// FIXME: Also add an "-fno-access-control" option.
642static llvm::cl::opt<bool>
643AccessControl("faccess-control",
644 llvm::cl::desc("Enable C++ access control"));
645
Anders Carlsson4ca076f2009-04-06 17:37:10 +0000646// It might be nice to add bounds to the CommandLine library directly.
647struct OptLevelParser : public llvm::cl::parser<unsigned> {
648 bool parse(llvm::cl::Option &O, const char *ArgName,
649 const std::string &Arg, unsigned &Val) {
650 if (llvm::cl::parser<unsigned>::parse(O, ArgName, Arg, Val))
651 return true;
Anders Carlsson4ca076f2009-04-06 17:37:10 +0000652 if (Val > 3)
Benjamin Kramer21fde992009-08-02 12:12:11 +0000653 return O.error("'" + Arg + "' invalid optimization level!");
Anders Carlsson4ca076f2009-04-06 17:37:10 +0000654 return false;
655 }
656};
657static llvm::cl::opt<unsigned, false, OptLevelParser>
658OptLevel("O", llvm::cl::Prefix,
659 llvm::cl::desc("Optimization level"),
660 llvm::cl::init(0));
661
Daniel Dunbar9fd0b1f2009-04-08 03:03:23 +0000662static llvm::cl::opt<unsigned>
Daniel Dunbar3bbc7532009-04-08 18:03:55 +0000663PICLevel("pic-level", llvm::cl::desc("Value for __PIC__"));
664
665static llvm::cl::opt<bool>
666StaticDefine("static-define", llvm::cl::desc("Should __STATIC__ be defined"));
Daniel Dunbar9fd0b1f2009-04-08 03:03:23 +0000667
Bill Wendling45483f72009-06-28 07:36:13 +0000668static llvm::cl::opt<int>
669StackProtector("stack-protector",
670 llvm::cl::desc("Enable stack protectors"),
671 llvm::cl::init(-1));
672
Daniel Dunbardcb4a1a2008-08-23 08:43:39 +0000673static void InitializeLanguageStandard(LangOptions &Options, LangKind LK,
Daniel Dunbar868bd0a2009-05-06 03:16:41 +0000674 TargetInfo *Target,
675 const llvm::StringMap<bool> &Features) {
Chris Lattner8fc4dfb2008-12-04 22:54:33 +0000676 // Allow the target to set the default the langauge options as it sees fit.
677 Target->getDefaultLangOptions(Options);
Daniel Dunbar868bd0a2009-05-06 03:16:41 +0000678
679 // Pass the map of target features to the target for validation and
680 // processing.
681 Target->HandleTargetFeatures(Features);
Chris Lattner16167a62009-03-02 22:11:07 +0000682
Reid Spencer5f016e22007-07-11 17:01:13 +0000683 if (LangStd == lang_unspecified) {
684 // Based on the base language, pick one.
Ted Kremenek8904f152007-12-05 23:49:08 +0000685 switch (LK) {
Ted Kremenekf2a17b12009-03-19 19:02:20 +0000686 case lang_unspecified: assert(0 && "Unknown base language");
Nate Begeman4e3629e2009-06-25 22:43:10 +0000687 case langkind_ocl:
688 LangStd = lang_c99;
689 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000690 case langkind_c:
Chris Lattnera778d7d2008-10-22 17:29:21 +0000691 case langkind_asm_cpp:
Reid Spencer5f016e22007-07-11 17:01:13 +0000692 case langkind_c_cpp:
693 case langkind_objc:
694 case langkind_objc_cpp:
695 LangStd = lang_gnu99;
696 break;
697 case langkind_cxx:
698 case langkind_cxx_cpp:
699 case langkind_objcxx:
700 case langkind_objcxx_cpp:
701 LangStd = lang_gnucxx98;
702 break;
703 }
704 }
705
706 switch (LangStd) {
707 default: assert(0 && "Unknown language standard!");
708
709 // Fall through from newer standards to older ones. This isn't really right.
710 // FIXME: Enable specifically the right features based on the language stds.
Chris Lattnerd4b80f12007-07-16 04:18:29 +0000711 case lang_gnucxx0x:
712 case lang_cxx0x:
713 Options.CPlusPlus0x = 1;
714 // FALL THROUGH
Reid Spencer5f016e22007-07-11 17:01:13 +0000715 case lang_gnucxx98:
716 case lang_cxx98:
717 Options.CPlusPlus = 1;
718 Options.CXXOperatorNames = !NoOperatorNames;
719 // FALL THROUGH.
720 case lang_gnu99:
721 case lang_c99:
Reid Spencer5f016e22007-07-11 17:01:13 +0000722 Options.C99 = 1;
723 Options.HexFloats = 1;
724 // FALL THROUGH.
725 case lang_gnu89:
726 Options.BCPLComment = 1; // Only for C99/C++.
727 // FALL THROUGH.
728 case lang_c94:
Chris Lattner3426b9b2008-02-25 04:01:39 +0000729 Options.Digraphs = 1; // C94, C99, C++.
730 // FALL THROUGH.
Reid Spencer5f016e22007-07-11 17:01:13 +0000731 case lang_c89:
732 break;
733 }
Argyrios Kyrtzidisd1465522008-09-11 04:21:06 +0000734
Chris Lattner7e9c90b2009-03-20 15:44:26 +0000735 // GNUMode - Set if we're in gnu99, gnu89, gnucxx98, etc.
736 Options.GNUMode = LangStd >= lang_gnu_START;
737
Argyrios Kyrtzidisd1465522008-09-11 04:21:06 +0000738 if (Options.CPlusPlus) {
739 Options.C99 = 0;
Chris Lattner7e9c90b2009-03-20 15:44:26 +0000740 Options.HexFloats = Options.GNUMode;
Argyrios Kyrtzidisd1465522008-09-11 04:21:06 +0000741 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000742
Chris Lattnerd658b562008-04-05 06:32:51 +0000743 if (LangStd == lang_c89 || LangStd == lang_c94 || LangStd == lang_gnu89)
744 Options.ImplicitInt = 1;
745 else
746 Options.ImplicitInt = 0;
Ted Kremenekea644d82008-09-03 21:22:16 +0000747
Daniel Dunbard573d262009-04-07 22:13:21 +0000748 // Mimicing gcc's behavior, trigraphs are only enabled if -trigraphs
749 // is specified, or -std is set to a conforming mode.
Chris Lattner7e9c90b2009-03-20 15:44:26 +0000750 Options.Trigraphs = !Options.GNUMode;
Chris Lattner802db9b2008-12-05 00:10:44 +0000751 if (Trigraphs.getPosition())
Chris Lattner7e9c90b2009-03-20 15:44:26 +0000752 Options.Trigraphs = Trigraphs; // Command line option wins if specified.
Ted Kremenekea644d82008-09-03 21:22:16 +0000753
Chris Lattner802db9b2008-12-05 00:10:44 +0000754 // If in a conformant language mode (e.g. -std=c99) Blocks defaults to off
755 // even if they are normally on for the target. In GNU modes (e.g.
756 // -std=gnu99) the default for blocks depends on the target settings.
Anders Carlssone56f6ff2009-01-21 18:47:36 +0000757 // However, blocks are not turned off when compiling Obj-C or Obj-C++ code.
Chris Lattner7e9c90b2009-03-20 15:44:26 +0000758 if (!Options.ObjC1 && !Options.GNUMode)
Chris Lattner802db9b2008-12-05 00:10:44 +0000759 Options.Blocks = 0;
760
Chris Lattner01638a62009-04-19 07:06:52 +0000761 // Default to not accepting '$' in identifiers when preprocessing assembler,
762 // but do accept when preprocessing C. FIXME: these defaults are right for
763 // darwin, are they right everywhere?
764 Options.DollarIdents = LK != langkind_asm_cpp;
765 if (DollarsInIdents.getPosition()) // Explicit setting overrides default.
Chris Lattnerf5db8f82009-04-19 07:00:02 +0000766 Options.DollarIdents = DollarsInIdents;
767
Chris Lattnerae0ee032008-12-04 23:20:07 +0000768 if (PascalStrings.getPosition())
769 Options.PascalStrings = PascalStrings;
Eli Friedmanabc4e322009-06-08 06:11:14 +0000770 if (MSExtensions.getPosition())
771 Options.Microsoft = MSExtensions;
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000772 Options.WritableStrings = WritableStrings;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +0000773 if (NoLaxVectorConversions.getPosition())
774 Options.LaxVectorConversions = 0;
Daniel Dunbar6379a7a2008-08-11 17:36:14 +0000775 Options.Exceptions = Exceptions;
Mike Stump738f8c22009-07-31 23:15:31 +0000776 Options.Rtti = Rtti;
Mike Stumpa0f02aa2009-02-02 22:57:57 +0000777 if (EnableBlocks.getPosition())
Chris Lattnerae0ee032008-12-04 23:20:07 +0000778 Options.Blocks = EnableBlocks;
Eli Friedmanc4757bd2009-06-05 07:12:17 +0000779 if (CharIsSigned.getPosition())
780 Options.CharIsSigned = CharIsSigned;
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000781
Daniel Dunbar9f9768c2009-03-20 23:49:28 +0000782 if (!AllowBuiltins)
Chris Lattner7644f072009-03-13 22:38:49 +0000783 Options.NoBuiltin = 1;
Douglas Gregor3573c0c2009-02-14 20:49:29 +0000784 if (Freestanding)
Chris Lattner7644f072009-03-13 22:38:49 +0000785 Options.Freestanding = Options.NoBuiltin = 1;
786
Chris Lattner810f6d52009-03-13 17:38:01 +0000787 if (EnableHeinousExtensions)
788 Options.HeinousExtensions = 1;
Douglas Gregor3573c0c2009-02-14 20:49:29 +0000789
Anders Carlssona33d9b42009-05-13 19:49:53 +0000790 if (AccessControl)
791 Options.AccessControl = 1;
792
Chris Lattnere4f21422009-06-30 01:26:17 +0000793 // OpenCL and C++ both have bool, true, false keywords.
794 Options.Bool = Options.OpenCL | Options.CPlusPlus;
795
Daniel Dunbaref2abfe2009-02-16 22:43:43 +0000796 Options.MathErrno = MathErrno;
797
Douglas Gregor26dce442009-03-10 00:06:19 +0000798 Options.InstantiationDepth = TemplateDepth;
799
Chris Lattner8fc4dfb2008-12-04 22:54:33 +0000800 // Override the default runtime if the user requested it.
801 if (NeXTRuntime)
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000802 Options.NeXTRuntime = 1;
Chris Lattner8fc4dfb2008-12-04 22:54:33 +0000803 else if (GNURuntime)
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000804 Options.NeXTRuntime = 0;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000805
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000806 if (ObjCNonFragileABI)
807 Options.ObjCNonFragileABI = 1;
Fariborz Jahanian34e65772009-05-22 20:17:16 +0000808
809 Options.ObjCSenderDispatch = ObjCSenderDispatch;
Daniel Dunbard6884a02009-05-04 05:16:21 +0000810
Daniel Dunbard604c402009-02-04 21:19:06 +0000811 if (EmitAllDecls)
812 Options.EmitAllDecls = 1;
Anders Carlsson4ca076f2009-04-06 17:37:10 +0000813
Daniel Dunbar3bbc7532009-04-08 18:03:55 +0000814 // The __OPTIMIZE_SIZE__ define is tied to -Oz, which we don't
815 // support.
816 Options.OptimizeSize = 0;
Anders Carlsson4ca076f2009-04-06 17:37:10 +0000817
818 // -Os implies -O2
Daniel Dunbar3bbc7532009-04-08 18:03:55 +0000819 if (OptSize || OptLevel)
Anders Carlsson4ca076f2009-04-06 17:37:10 +0000820 Options.Optimize = 1;
Daniel Dunbar9fd0b1f2009-04-08 03:03:23 +0000821
822 assert(PICLevel <= 2 && "Invalid value for -pic-level");
823 Options.PICLevel = PICLevel;
Daniel Dunbarc9abc042009-04-08 05:11:16 +0000824
Daniel Dunbar3bbc7532009-04-08 18:03:55 +0000825 Options.GNUInline = !Options.C99;
Chris Lattner5aeb9e72009-05-06 04:38:30 +0000826 // FIXME: This is affected by other options (-fno-inline).
Daniel Dunbar3bbc7532009-04-08 18:03:55 +0000827 Options.NoInline = !OptSize && !OptLevel;
828
829 Options.Static = StaticDefine;
830
Bill Wendling4ebe3e42009-06-28 23:01:01 +0000831 switch (StackProtector) {
832 default:
833 assert(StackProtector <= 2 && "Invalid value for -stack-protector");
834 case -1: break;
835 case 0: Options.setStackProtectorMode(LangOptions::SSPOff); break;
836 case 1: Options.setStackProtectorMode(LangOptions::SSPOn); break;
837 case 2: Options.setStackProtectorMode(LangOptions::SSPReq); break;
838 }
Bill Wendling45483f72009-06-28 07:36:13 +0000839
Daniel Dunbarc9abc042009-04-08 05:11:16 +0000840 if (MainFileName.getPosition())
841 Options.setMainFileName(MainFileName.c_str());
Reid Spencer5f016e22007-07-11 17:01:13 +0000842}
843
844//===----------------------------------------------------------------------===//
Ted Kremenekae360762007-12-03 22:06:55 +0000845// Target Triple Processing.
846//===----------------------------------------------------------------------===//
847
848static llvm::cl::opt<std::string>
849TargetTriple("triple",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000850 llvm::cl::desc("Specify target triple (e.g. i686-apple-darwin9)"));
Ted Kremenekae360762007-12-03 22:06:55 +0000851
Chris Lattner42e67372008-03-05 01:18:20 +0000852static llvm::cl::opt<std::string>
Chris Lattner6a30c1f2008-09-30 01:13:12 +0000853MacOSVersionMin("mmacosx-version-min",
Daniel Dunbar8d33cd72009-04-10 19:52:24 +0000854 llvm::cl::desc("Specify target Mac OS X version (e.g. 10.5)"));
Chris Lattner6a30c1f2008-09-30 01:13:12 +0000855
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000856// If -mmacosx-version-min=10.3.9 is specified, change the triple from being
857// something like powerpc-apple-darwin9 to powerpc-apple-darwin7
Daniel Dunbar64ffc142009-03-31 20:10:05 +0000858
859// FIXME: We should have the driver do this instead.
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000860static void HandleMacOSVersionMin(std::string &Triple) {
861 std::string::size_type DarwinDashIdx = Triple.find("-darwin");
862 if (DarwinDashIdx == std::string::npos) {
863 fprintf(stderr,
Daniel Dunbar8d33cd72009-04-10 19:52:24 +0000864 "-mmacosx-version-min only valid for darwin (Mac OS X) targets\n");
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000865 exit(1);
866 }
867 unsigned DarwinNumIdx = DarwinDashIdx + strlen("-darwin");
868
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000869 // Remove the number.
870 Triple.resize(DarwinNumIdx);
871
872 // Validate that MacOSVersionMin is a 'version number', starting with 10.[3-9]
873 bool MacOSVersionMinIsInvalid = false;
874 int VersionNum = 0;
875 if (MacOSVersionMin.size() < 4 ||
876 MacOSVersionMin.substr(0, 3) != "10." ||
877 !isdigit(MacOSVersionMin[3])) {
878 MacOSVersionMinIsInvalid = true;
879 } else {
880 const char *Start = MacOSVersionMin.c_str()+3;
881 char *End = 0;
882 VersionNum = (int)strtol(Start, &End, 10);
883
Chris Lattner079f2c462008-09-30 20:30:12 +0000884 // The version number must be in the range 0-9.
885 MacOSVersionMinIsInvalid = (unsigned)VersionNum > 9;
886
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000887 // Turn MacOSVersionMin into a darwin number: e.g. 10.3.9 is 3 -> 7.
888 Triple += llvm::itostr(VersionNum+4);
889
Chris Lattner079f2c462008-09-30 20:30:12 +0000890 if (End[0] == '.' && isdigit(End[1]) && End[2] == '\0') { // 10.4.7 is ok.
891 // Add the period piece (.7) to the end of the triple. This gives us
892 // something like ...-darwin8.7
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000893 Triple += End;
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000894 } else if (End[0] != '\0') { // "10.4" is ok. 10.4x is not.
895 MacOSVersionMinIsInvalid = true;
896 }
897 }
898
899 if (MacOSVersionMinIsInvalid) {
900 fprintf(stderr,
Daniel Dunbaraf07f932009-03-31 17:35:15 +0000901 "-mmacosx-version-min=%s is invalid, expected something like '10.4'.\n",
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000902 MacOSVersionMin.c_str());
903 exit(1);
904 }
Fariborz Jahanian6a1284a2009-04-10 20:33:45 +0000905 else if (VersionNum <= 4 &&
906 !strncmp(Triple.c_str(), "x86_64", strlen("x86_64"))) {
907 fprintf(stderr,
908 "-mmacosx-version-min=%s is invalid with -arch x86_64.\n",
909 MacOSVersionMin.c_str());
910 exit(1);
911 }
912
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000913}
914
Daniel Dunbar8d33cd72009-04-10 19:52:24 +0000915static llvm::cl::opt<std::string>
916IPhoneOSVersionMin("miphoneos-version-min",
917 llvm::cl::desc("Specify target iPhone OS version (e.g. 2.0)"));
918
919// If -miphoneos-version-min=2.2 is specified, change the triple from being
920// something like armv6-apple-darwin10 to armv6-apple-darwin9.2.2. We use
921// 9 as the default major Darwin number, and encode the iPhone OS version
922// number in the minor version and revision.
923
924// FIXME: We should have the driver do this instead.
925static void HandleIPhoneOSVersionMin(std::string &Triple) {
926 std::string::size_type DarwinDashIdx = Triple.find("-darwin");
927 if (DarwinDashIdx == std::string::npos) {
928 fprintf(stderr,
929 "-miphoneos-version-min only valid for darwin (Mac OS X) targets\n");
930 exit(1);
931 }
932 unsigned DarwinNumIdx = DarwinDashIdx + strlen("-darwin");
933
934 // Remove the number.
935 Triple.resize(DarwinNumIdx);
936
937 // Validate that IPhoneOSVersionMin is a 'version number', starting with [2-9].[0-9]
938 bool IPhoneOSVersionMinIsInvalid = false;
939 int VersionNum = 0;
940 if (IPhoneOSVersionMin.size() < 3 ||
941 !isdigit(IPhoneOSVersionMin[0])) {
942 IPhoneOSVersionMinIsInvalid = true;
943 } else {
944 const char *Start = IPhoneOSVersionMin.c_str();
945 char *End = 0;
946 VersionNum = (int)strtol(Start, &End, 10);
947
948 // The version number must be in the range 0-9.
949 IPhoneOSVersionMinIsInvalid = (unsigned)VersionNum > 9;
950
951 // Turn IPhoneOSVersionMin into a darwin number: e.g. 2.0 is 2 -> 9.2.
952 Triple += "9." + llvm::itostr(VersionNum);
953
954 if (End[0] == '.' && isdigit(End[1]) && End[2] == '\0') { // 2.2 is ok.
955 // Add the period piece (.2) to the end of the triple. This gives us
956 // something like ...-darwin9.2.2
957 Triple += End;
958 } else if (End[0] != '\0') { // "2.2" is ok. 2x is not.
959 IPhoneOSVersionMinIsInvalid = true;
960 }
961 }
962
963 if (IPhoneOSVersionMinIsInvalid) {
964 fprintf(stderr,
965 "-miphoneos-version-min=%s is invalid, expected something like '2.0'.\n",
966 IPhoneOSVersionMin.c_str());
967 exit(1);
968 }
969}
970
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000971/// CreateTargetTriple - Process the various options that affect the target
972/// triple and build a final aggregate triple that we are compiling for.
Chris Lattner6fd9fa12008-03-09 01:35:13 +0000973static std::string CreateTargetTriple() {
Ted Kremenekae360762007-12-03 22:06:55 +0000974 // Initialize base triple. If a -triple option has been specified, use
975 // that triple. Otherwise, default to the host triple.
Chris Lattner6590d212007-12-12 05:01:48 +0000976 std::string Triple = TargetTriple;
Daniel Dunbaraf07f932009-03-31 17:35:15 +0000977 if (Triple.empty())
978 Triple = llvm::sys::getHostTriple();
Chris Lattner6a30c1f2008-09-30 01:13:12 +0000979
980 // If -mmacosx-version-min=10.3.9 is specified, change the triple from being
981 // something like powerpc-apple-darwin9 to powerpc-apple-darwin7
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000982 if (!MacOSVersionMin.empty())
983 HandleMacOSVersionMin(Triple);
Daniel Dunbar8d33cd72009-04-10 19:52:24 +0000984 else if (!IPhoneOSVersionMin.empty())
985 HandleIPhoneOSVersionMin(Triple);;
Ted Kremenekae360762007-12-03 22:06:55 +0000986
Chris Lattner6a30c1f2008-09-30 01:13:12 +0000987 return Triple;
Ted Kremenekae360762007-12-03 22:06:55 +0000988}
989
990//===----------------------------------------------------------------------===//
Chris Lattnere116ccf2009-04-21 05:40:52 +0000991// SourceManager initialization.
Reid Spencer5f016e22007-07-11 17:01:13 +0000992//===----------------------------------------------------------------------===//
993
Douglas Gregore1d918e2009-04-10 23:10:45 +0000994static bool InitializeSourceManager(Preprocessor &PP,
995 const std::string &InFile) {
996 // Figure out where to get and map in the main file.
997 SourceManager &SourceMgr = PP.getSourceManager();
998 FileManager &FileMgr = PP.getFileManager();
Daniel Dunbar57cbfc02009-04-27 21:19:07 +0000999
1000 if (EmptyInputOnly) {
1001 const char *EmptyStr = "";
1002 llvm::MemoryBuffer *SB =
1003 llvm::MemoryBuffer::getMemBuffer(EmptyStr, EmptyStr, "<empty input>");
1004 SourceMgr.createMainFileIDForMemBuffer(SB);
1005 } else if (InFile != "-") {
Douglas Gregore1d918e2009-04-10 23:10:45 +00001006 const FileEntry *File = FileMgr.getFile(InFile);
1007 if (File) SourceMgr.createMainFileID(File, SourceLocation());
1008 if (SourceMgr.getMainFileID().isInvalid()) {
1009 PP.getDiagnostics().Report(FullSourceLoc(), diag::err_fe_error_reading)
1010 << InFile.c_str();
1011 return true;
1012 }
1013 } else {
1014 llvm::MemoryBuffer *SB = llvm::MemoryBuffer::getSTDIN();
1015
1016 // If stdin was empty, SB is null. Cons up an empty memory
1017 // buffer now.
1018 if (!SB) {
1019 const char *EmptyStr = "";
1020 SB = llvm::MemoryBuffer::getMemBuffer(EmptyStr, EmptyStr, "<stdin>");
1021 }
1022
1023 SourceMgr.createMainFileIDForMemBuffer(SB);
1024 if (SourceMgr.getMainFileID().isInvalid()) {
1025 PP.getDiagnostics().Report(FullSourceLoc(),
1026 diag::err_fe_error_reading_stdin);
1027 return true;
1028 }
1029 }
1030
1031 return false;
1032}
1033
Chris Lattneraa391972008-04-19 23:09:31 +00001034
Chris Lattnere116ccf2009-04-21 05:40:52 +00001035//===----------------------------------------------------------------------===//
1036// Preprocessor Initialization
1037//===----------------------------------------------------------------------===//
Sam Bishop1102d6b2008-04-14 14:41:57 +00001038
Chris Lattnere116ccf2009-04-21 05:40:52 +00001039// FIXME: Preprocessor builtins to support.
1040// -A... - Play with #assertions
1041// -undef - Undefine all predefined macros
Chris Lattnerb31ac222009-04-08 20:15:42 +00001042
Chris Lattnere116ccf2009-04-21 05:40:52 +00001043static llvm::cl::list<std::string>
1044D_macros("D", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
1045 llvm::cl::desc("Predefine the specified macro"));
1046static llvm::cl::list<std::string>
1047U_macros("U", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
1048 llvm::cl::desc("Undefine the specified macro"));
Chris Lattnerb8e240e2009-04-08 18:24:34 +00001049
Chris Lattnere116ccf2009-04-21 05:40:52 +00001050static llvm::cl::list<std::string>
1051ImplicitIncludes("include", llvm::cl::value_desc("file"),
1052 llvm::cl::desc("Include file before parsing"));
1053static llvm::cl::list<std::string>
1054ImplicitMacroIncludes("imacros", llvm::cl::value_desc("file"),
1055 llvm::cl::desc("Include macros from file before parsing"));
Chris Lattnerb8e240e2009-04-08 18:24:34 +00001056
Chris Lattnere116ccf2009-04-21 05:40:52 +00001057static llvm::cl::opt<std::string>
1058ImplicitIncludePCH("include-pch", llvm::cl::value_desc("file"),
1059 llvm::cl::desc("Include precompiled header file"));
1060
1061static llvm::cl::opt<std::string>
1062ImplicitIncludePTH("include-pth", llvm::cl::value_desc("file"),
1063 llvm::cl::desc("Include file before parsing"));
1064
Douglas Gregore650c8c2009-07-07 00:12:59 +00001065static llvm::cl::opt<bool>
1066RelocatablePCH("relocatable-pch",
1067 llvm::cl::desc("Whether to build a relocatable precompiled "
1068 "header"));
Reid Spencer5f016e22007-07-11 17:01:13 +00001069
1070//===----------------------------------------------------------------------===//
1071// Preprocessor include path information.
1072//===----------------------------------------------------------------------===//
1073
1074// This tool exports a large number of command line options to control how the
1075// preprocessor searches for header files. At root, however, the Preprocessor
1076// object takes a very simple interface: a list of directories to search for
1077//
Daniel Dunbarfb4ac7b2009-05-06 03:48:17 +00001078// FIXME: -nostdinc++
Chris Lattner0c946412007-08-26 17:47:35 +00001079// FIXME: -imultilib
Reid Spencer5f016e22007-07-11 17:01:13 +00001080//
Reid Spencer5f016e22007-07-11 17:01:13 +00001081
1082static llvm::cl::opt<bool>
1083nostdinc("nostdinc", llvm::cl::desc("Disable standard #include directories"));
1084
1085// Various command line options. These four add directories to each chain.
1086static llvm::cl::list<std::string>
1087F_dirs("F", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1088 llvm::cl::desc("Add directory to framework include search path"));
1089static llvm::cl::list<std::string>
1090I_dirs("I", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1091 llvm::cl::desc("Add directory to include search path"));
1092static llvm::cl::list<std::string>
1093idirafter_dirs("idirafter", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1094 llvm::cl::desc("Add directory to AFTER include search path"));
1095static llvm::cl::list<std::string>
1096iquote_dirs("iquote", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1097 llvm::cl::desc("Add directory to QUOTE include search path"));
1098static llvm::cl::list<std::string>
1099isystem_dirs("isystem", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1100 llvm::cl::desc("Add directory to SYSTEM include search path"));
1101
1102// These handle -iprefix/-iwithprefix/-iwithprefixbefore.
1103static llvm::cl::list<std::string>
1104iprefix_vals("iprefix", llvm::cl::value_desc("prefix"), llvm::cl::Prefix,
1105 llvm::cl::desc("Set the -iwithprefix/-iwithprefixbefore prefix"));
1106static llvm::cl::list<std::string>
1107iwithprefix_vals("iwithprefix", llvm::cl::value_desc("dir"), llvm::cl::Prefix,
1108 llvm::cl::desc("Set directory to SYSTEM include search path with prefix"));
1109static llvm::cl::list<std::string>
1110iwithprefixbefore_vals("iwithprefixbefore", llvm::cl::value_desc("dir"),
1111 llvm::cl::Prefix,
1112 llvm::cl::desc("Set directory to include search path with prefix"));
1113
Chris Lattner0c946412007-08-26 17:47:35 +00001114static llvm::cl::opt<std::string>
1115isysroot("isysroot", llvm::cl::value_desc("dir"), llvm::cl::init("/"),
1116 llvm::cl::desc("Set the system root directory (usually /)"));
1117
Reid Spencer5f016e22007-07-11 17:01:13 +00001118// Finally, implement the code that groks the options above.
Chris Lattner5f9eae52008-03-01 08:07:28 +00001119
Reid Spencer5f016e22007-07-11 17:01:13 +00001120/// InitializeIncludePaths - Process the -I options and set them in the
1121/// HeaderSearch object.
Nico Weber0fca0222008-08-22 09:25:22 +00001122void InitializeIncludePaths(const char *Argv0, HeaderSearch &Headers,
1123 FileManager &FM, const LangOptions &Lang) {
1124 InitHeaderSearch Init(Headers, Verbose, isysroot);
1125
Ted Kremenekf3721112008-05-31 00:27:00 +00001126 // Handle -I... and -F... options, walking the lists in parallel.
1127 unsigned Iidx = 0, Fidx = 0;
1128 while (Iidx < I_dirs.size() && Fidx < F_dirs.size()) {
1129 if (I_dirs.getPosition(Iidx) < F_dirs.getPosition(Fidx)) {
Nico Weber0fca0222008-08-22 09:25:22 +00001130 Init.AddPath(I_dirs[Iidx], InitHeaderSearch::Angled, false, true, false);
Ted Kremenekf3721112008-05-31 00:27:00 +00001131 ++Iidx;
1132 } else {
Nico Weber0fca0222008-08-22 09:25:22 +00001133 Init.AddPath(F_dirs[Fidx], InitHeaderSearch::Angled, false, true, true);
Ted Kremenekf3721112008-05-31 00:27:00 +00001134 ++Fidx;
1135 }
1136 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001137
Ted Kremenekf3721112008-05-31 00:27:00 +00001138 // Consume what's left from whatever list was longer.
1139 for (; Iidx != I_dirs.size(); ++Iidx)
Nico Weber0fca0222008-08-22 09:25:22 +00001140 Init.AddPath(I_dirs[Iidx], InitHeaderSearch::Angled, false, true, false);
Ted Kremenekf3721112008-05-31 00:27:00 +00001141 for (; Fidx != F_dirs.size(); ++Fidx)
Nico Weber0fca0222008-08-22 09:25:22 +00001142 Init.AddPath(F_dirs[Fidx], InitHeaderSearch::Angled, false, true, true);
Reid Spencer5f016e22007-07-11 17:01:13 +00001143
1144 // Handle -idirafter... options.
1145 for (unsigned i = 0, e = idirafter_dirs.size(); i != e; ++i)
Nico Weber0fca0222008-08-22 09:25:22 +00001146 Init.AddPath(idirafter_dirs[i], InitHeaderSearch::After,
1147 false, true, false);
Reid Spencer5f016e22007-07-11 17:01:13 +00001148
1149 // Handle -iquote... options.
1150 for (unsigned i = 0, e = iquote_dirs.size(); i != e; ++i)
Nico Weber0fca0222008-08-22 09:25:22 +00001151 Init.AddPath(iquote_dirs[i], InitHeaderSearch::Quoted, false, true, false);
Reid Spencer5f016e22007-07-11 17:01:13 +00001152
1153 // Handle -isystem... options.
1154 for (unsigned i = 0, e = isystem_dirs.size(); i != e; ++i)
Nico Weber0fca0222008-08-22 09:25:22 +00001155 Init.AddPath(isystem_dirs[i], InitHeaderSearch::System, false, true, false);
Reid Spencer5f016e22007-07-11 17:01:13 +00001156
1157 // Walk the -iprefix/-iwithprefix/-iwithprefixbefore argument lists in
1158 // parallel, processing the values in order of occurance to get the right
1159 // prefixes.
1160 {
1161 std::string Prefix = ""; // FIXME: this isn't the correct default prefix.
1162 unsigned iprefix_idx = 0;
1163 unsigned iwithprefix_idx = 0;
1164 unsigned iwithprefixbefore_idx = 0;
1165 bool iprefix_done = iprefix_vals.empty();
1166 bool iwithprefix_done = iwithprefix_vals.empty();
1167 bool iwithprefixbefore_done = iwithprefixbefore_vals.empty();
1168 while (!iprefix_done || !iwithprefix_done || !iwithprefixbefore_done) {
1169 if (!iprefix_done &&
1170 (iwithprefix_done ||
1171 iprefix_vals.getPosition(iprefix_idx) <
1172 iwithprefix_vals.getPosition(iwithprefix_idx)) &&
1173 (iwithprefixbefore_done ||
1174 iprefix_vals.getPosition(iprefix_idx) <
1175 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
1176 Prefix = iprefix_vals[iprefix_idx];
1177 ++iprefix_idx;
1178 iprefix_done = iprefix_idx == iprefix_vals.size();
1179 } else if (!iwithprefix_done &&
1180 (iwithprefixbefore_done ||
1181 iwithprefix_vals.getPosition(iwithprefix_idx) <
1182 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
Nico Weber0fca0222008-08-22 09:25:22 +00001183 Init.AddPath(Prefix+iwithprefix_vals[iwithprefix_idx],
1184 InitHeaderSearch::System, false, false, false);
Reid Spencer5f016e22007-07-11 17:01:13 +00001185 ++iwithprefix_idx;
1186 iwithprefix_done = iwithprefix_idx == iwithprefix_vals.size();
1187 } else {
Nico Weber0fca0222008-08-22 09:25:22 +00001188 Init.AddPath(Prefix+iwithprefixbefore_vals[iwithprefixbefore_idx],
1189 InitHeaderSearch::Angled, false, false, false);
Reid Spencer5f016e22007-07-11 17:01:13 +00001190 ++iwithprefixbefore_idx;
1191 iwithprefixbefore_done =
1192 iwithprefixbefore_idx == iwithprefixbefore_vals.size();
1193 }
1194 }
1195 }
Chris Lattner5f9eae52008-03-01 08:07:28 +00001196
Nico Weber0fca0222008-08-22 09:25:22 +00001197 Init.AddDefaultEnvVarPaths(Lang);
Chris Lattner5f9eae52008-03-01 08:07:28 +00001198
Daniel Dunbaradcf5b32009-02-21 20:52:41 +00001199 // Add the clang headers, which are relative to the clang binary.
Chris Lattnerdcaa0962008-03-03 03:16:03 +00001200 llvm::sys::Path MainExecutablePath =
Chris Lattner985e1822008-03-03 05:57:43 +00001201 llvm::sys::Path::GetMainExecutable(Argv0,
1202 (void*)(intptr_t)InitializeIncludePaths);
Chris Lattnerdcaa0962008-03-03 03:16:03 +00001203 if (!MainExecutablePath.isEmpty()) {
1204 MainExecutablePath.eraseComponent(); // Remove /clang from foo/bin/clang
1205 MainExecutablePath.eraseComponent(); // Remove /bin from foo/bin
Daniel Dunbaradcf5b32009-02-21 20:52:41 +00001206
Daniel Dunbarfb4ac7b2009-05-06 03:48:17 +00001207 // Get foo/lib/clang/<version>/include
Daniel Dunbaradcf5b32009-02-21 20:52:41 +00001208 MainExecutablePath.appendComponent("lib");
1209 MainExecutablePath.appendComponent("clang");
Daniel Dunbarfb4ac7b2009-05-06 03:48:17 +00001210 MainExecutablePath.appendComponent(CLANG_VERSION_STRING);
Daniel Dunbaradcf5b32009-02-21 20:52:41 +00001211 MainExecutablePath.appendComponent("include");
Chris Lattner6858dd32009-02-19 06:48:28 +00001212
1213 // We pass true to ignore sysroot so that we *always* look for clang headers
1214 // relative to our executable, never relative to -isysroot.
1215 Init.AddPath(MainExecutablePath.c_str(), InitHeaderSearch::System,
1216 false, false, false, true /*ignore sysroot*/);
Chris Lattnerdcaa0962008-03-03 03:16:03 +00001217 }
1218
Nico Weber0fca0222008-08-22 09:25:22 +00001219 if (!nostdinc)
1220 Init.AddDefaultSystemIncludePaths(Lang);
Reid Spencer5f016e22007-07-11 17:01:13 +00001221
1222 // Now that we have collected all of the include paths, merge them all
1223 // together and tell the preprocessor about them.
1224
Nico Weber0fca0222008-08-22 09:25:22 +00001225 Init.Realize();
Reid Spencer5f016e22007-07-11 17:01:13 +00001226}
1227
Chris Lattnere116ccf2009-04-21 05:40:52 +00001228void InitializePreprocessorInitOptions(PreprocessorInitOptions &InitOpts)
1229{
1230 // Add macros from the command line.
1231 unsigned d = 0, D = D_macros.size();
1232 unsigned u = 0, U = U_macros.size();
1233 while (d < D || u < U) {
1234 if (u == U || (d < D && D_macros.getPosition(d) < U_macros.getPosition(u)))
1235 InitOpts.addMacroDef(D_macros[d++]);
1236 else
1237 InitOpts.addMacroUndef(U_macros[u++]);
1238 }
1239
1240 // If -imacros are specified, include them now. These are processed before
1241 // any -include directives.
1242 for (unsigned i = 0, e = ImplicitMacroIncludes.size(); i != e; ++i)
1243 InitOpts.addMacroInclude(ImplicitMacroIncludes[i]);
1244
Douglas Gregorb64c1932009-05-12 01:31:05 +00001245 if (!ImplicitIncludePTH.empty() || !ImplicitIncludes.empty() ||
1246 (!ImplicitIncludePCH.empty() && ProgAction == PrintPreprocessedInput)) {
Chris Lattnere116ccf2009-04-21 05:40:52 +00001247 // We want to add these paths to the predefines buffer in order, make a
1248 // temporary vector to sort by their occurrence.
1249 llvm::SmallVector<std::pair<unsigned, std::string*>, 8> OrderedPaths;
1250
1251 if (!ImplicitIncludePTH.empty())
1252 OrderedPaths.push_back(std::make_pair(ImplicitIncludePTH.getPosition(),
1253 &ImplicitIncludePTH));
Douglas Gregorb64c1932009-05-12 01:31:05 +00001254 if (!ImplicitIncludePCH.empty() && ProgAction == PrintPreprocessedInput)
1255 OrderedPaths.push_back(std::make_pair(ImplicitIncludePCH.getPosition(),
1256 &ImplicitIncludePCH));
Chris Lattnere116ccf2009-04-21 05:40:52 +00001257 for (unsigned i = 0, e = ImplicitIncludes.size(); i != e; ++i)
1258 OrderedPaths.push_back(std::make_pair(ImplicitIncludes.getPosition(i),
1259 &ImplicitIncludes[i]));
1260 llvm::array_pod_sort(OrderedPaths.begin(), OrderedPaths.end());
1261
1262
1263 // Now that they are ordered by position, add to the predefines buffer.
1264 for (unsigned i = 0, e = OrderedPaths.size(); i != e; ++i) {
1265 std::string *Ptr = OrderedPaths[i].second;
1266 if (!ImplicitIncludes.empty() &&
1267 Ptr >= &ImplicitIncludes[0] &&
1268 Ptr <= &ImplicitIncludes[ImplicitIncludes.size()-1]) {
1269 InitOpts.addInclude(*Ptr, false);
Douglas Gregorb64c1932009-05-12 01:31:05 +00001270 } else if (Ptr == &ImplicitIncludePTH) {
Chris Lattnere116ccf2009-04-21 05:40:52 +00001271 InitOpts.addInclude(*Ptr, true);
Douglas Gregorb64c1932009-05-12 01:31:05 +00001272 } else {
1273 // We end up here when we're producing preprocessed output and
1274 // we loaded a PCH file. In this case, just include the header
1275 // file that was used to build the precompiled header.
1276 assert(Ptr == &ImplicitIncludePCH);
1277 std::string OriginalFile = PCHReader::getOriginalSourceFile(*Ptr);
1278 if (!OriginalFile.empty()) {
1279 InitOpts.addInclude(OriginalFile, false);
1280 ImplicitIncludePCH.clear();
1281 }
Chris Lattnere116ccf2009-04-21 05:40:52 +00001282 }
1283 }
1284 }
1285}
1286
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001287//===----------------------------------------------------------------------===//
1288// Driver PreprocessorFactory - For lazily generating preprocessors ...
1289//===----------------------------------------------------------------------===//
1290
1291namespace {
1292class VISIBILITY_HIDDEN DriverPreprocessorFactory : public PreprocessorFactory {
1293 Diagnostic &Diags;
1294 const LangOptions &LangInfo;
1295 TargetInfo &Target;
1296 SourceManager &SourceMgr;
1297 HeaderSearch &HeaderInfo;
Ted Kremenek339b9c22008-04-17 22:31:54 +00001298
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001299public:
Eli Friedmanf086e3b2009-05-18 07:39:39 +00001300 DriverPreprocessorFactory(Diagnostic &diags, const LangOptions &opts,
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001301 TargetInfo &target, SourceManager &SM,
1302 HeaderSearch &Headers)
Eli Friedmanf086e3b2009-05-18 07:39:39 +00001303 : Diags(diags), LangInfo(opts), Target(target),
Douglas Gregore1d918e2009-04-10 23:10:45 +00001304 SourceMgr(SM), HeaderInfo(Headers) {}
Ted Kremenek339b9c22008-04-17 22:31:54 +00001305
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001306
1307 virtual ~DriverPreprocessorFactory() {}
1308
1309 virtual Preprocessor* CreatePreprocessor() {
Ted Kremenek72b1b152009-01-15 18:47:46 +00001310 llvm::OwningPtr<PTHManager> PTHMgr;
1311
Ted Kremenek748d5d62009-03-20 00:26:38 +00001312 if (!TokenCache.empty() && !ImplicitIncludePTH.empty()) {
1313 fprintf(stderr, "error: cannot use both -token-cache and -include-pth "
1314 "options\n");
Ted Kremenek22f0d092009-03-22 06:42:39 +00001315 exit(1);
Ted Kremenek748d5d62009-03-20 00:26:38 +00001316 }
1317
Ted Kremenek72b1b152009-01-15 18:47:46 +00001318 // Use PTH?
Ted Kremenek748d5d62009-03-20 00:26:38 +00001319 if (!TokenCache.empty() || !ImplicitIncludePTH.empty()) {
1320 const std::string& x = TokenCache.empty() ? ImplicitIncludePTH:TokenCache;
Ted Kremenek22f0d092009-03-22 06:42:39 +00001321 PTHMgr.reset(PTHManager::Create(x, &Diags,
1322 TokenCache.empty() ? Diagnostic::Error
1323 : Diagnostic::Warning));
Ted Kremenek748d5d62009-03-20 00:26:38 +00001324 }
Ted Kremenek72b1b152009-01-15 18:47:46 +00001325
Ted Kremenek22f0d092009-03-22 06:42:39 +00001326 if (Diags.hasErrorOccurred())
1327 exit(1);
1328
Ted Kremenek72b1b152009-01-15 18:47:46 +00001329 // Create the Preprocessor.
1330 llvm::OwningPtr<Preprocessor> PP(new Preprocessor(Diags, LangInfo, Target,
1331 SourceMgr, HeaderInfo,
1332 PTHMgr.get()));
1333
1334 // Note that this is different then passing PTHMgr to Preprocessor's ctor.
1335 // That argument is used as the IdentifierInfoLookup argument to
1336 // IdentifierTable's ctor.
1337 if (PTHMgr) {
1338 PTHMgr->setPreprocessor(PP.get());
1339 PP->setPTHManager(PTHMgr.take());
1340 }
Douglas Gregor14f79002009-04-10 03:52:48 +00001341
Chris Lattnere116ccf2009-04-21 05:40:52 +00001342 PreprocessorInitOptions InitOpts;
1343 InitializePreprocessorInitOptions(InitOpts);
Eli Friedmanf086e3b2009-05-18 07:39:39 +00001344 if (InitializePreprocessor(*PP, InitOpts))
Douglas Gregore1d918e2009-04-10 23:10:45 +00001345 return 0;
Chris Lattnere116ccf2009-04-21 05:40:52 +00001346
Douglas Gregore1d918e2009-04-10 23:10:45 +00001347 return PP.take();
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001348 }
1349};
1350}
Reid Spencer5f016e22007-07-11 17:01:13 +00001351
Reid Spencer5f016e22007-07-11 17:01:13 +00001352//===----------------------------------------------------------------------===//
1353// Basic Parser driver
1354//===----------------------------------------------------------------------===//
1355
Chris Lattner51574ea2008-04-19 23:25:44 +00001356static void ParseFile(Preprocessor &PP, MinimalAction *PA) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001357 Parser P(PP, *PA);
Ted Kremenek95041a22007-12-19 22:51:13 +00001358 PP.EnterMainSourceFile();
Reid Spencer5f016e22007-07-11 17:01:13 +00001359
1360 // Parsing the specified input file.
1361 P.ParseTranslationUnit();
1362 delete PA;
1363}
1364
1365//===----------------------------------------------------------------------===//
Daniel Dunbar70f92432008-10-23 05:50:47 +00001366// Code generation options
1367//===----------------------------------------------------------------------===//
1368
1369static llvm::cl::opt<bool>
Chris Lattner15104882009-03-09 22:05:03 +00001370GenerateDebugInfo("g",
1371 llvm::cl::desc("Generate source level debug information"));
1372
Daniel Dunbara034ba82009-02-17 19:47:34 +00001373static llvm::cl::opt<std::string>
1374TargetCPU("mcpu",
1375 llvm::cl::desc("Target a specific cpu type (-mcpu=help for details)"));
1376
Daniel Dunbar868bd0a2009-05-06 03:16:41 +00001377static llvm::cl::list<std::string>
1378TargetFeatures("target-feature", llvm::cl::desc("Target specific attributes"));
1379
Devang Patel24095da2009-06-04 23:32:02 +00001380
1381static llvm::cl::opt<bool>
1382DisableRedZone("disable-red-zone",
1383 llvm::cl::desc("Do not emit code that uses the red zone."),
1384 llvm::cl::init(false));
1385
Devang Patelacebb392009-06-05 22:05:48 +00001386static llvm::cl::opt<bool>
1387NoImplicitFloat("no-implicit-float",
1388 llvm::cl::desc("Don't generate implicit floating point instructions (x86-only)"),
1389 llvm::cl::init(false));
1390
Daniel Dunbar868bd0a2009-05-06 03:16:41 +00001391/// ComputeTargetFeatures - Recompute the target feature list to only
1392/// be the list of things that are enabled, based on the target cpu
1393/// and feature list.
1394static void ComputeFeatureMap(TargetInfo *Target,
1395 llvm::StringMap<bool> &Features) {
1396 assert(Features.empty() && "invalid map");
1397
1398 // Initialize the feature map based on the target.
1399 Target->getDefaultFeatures(TargetCPU, Features);
1400
1401 // Apply the user specified deltas.
1402 for (llvm::cl::list<std::string>::iterator it = TargetFeatures.begin(),
1403 ie = TargetFeatures.end(); it != ie; ++it) {
1404 const char *Name = it->c_str();
1405
1406 // FIXME: Don't handle errors like this.
1407 if (Name[0] != '-' && Name[0] != '+') {
1408 fprintf(stderr, "error: clang-cc: invalid target feature string: %s\n",
1409 Name);
1410 exit(1);
1411 }
Daniel Dunbar17ca3632009-05-06 21:07:50 +00001412 if (!Target->setFeatureEnabled(Features, Name + 1, (Name[0] == '+'))) {
1413 fprintf(stderr, "error: clang-cc: invalid target feature name: %s\n",
1414 Name + 1);
Daniel Dunbar868bd0a2009-05-06 03:16:41 +00001415 exit(1);
1416 }
Daniel Dunbar868bd0a2009-05-06 03:16:41 +00001417 }
1418}
1419
Chris Lattner7afae712009-03-16 18:41:18 +00001420static void InitializeCompileOptions(CompileOptions &Opts,
Daniel Dunbar868bd0a2009-05-06 03:16:41 +00001421 const LangOptions &LangOpts,
1422 const llvm::StringMap<bool> &Features) {
Daniel Dunbar70f92432008-10-23 05:50:47 +00001423 Opts.OptimizeSize = OptSize;
Chris Lattner20126042009-03-09 22:00:34 +00001424 Opts.DebugInfo = GenerateDebugInfo;
Daniel Dunbar877db382009-06-02 22:07:45 +00001425
1426 if (DisableLLVMOptimizations) {
1427 Opts.OptimizationLevel = 0;
1428 Opts.Inlining = CompileOptions::NoInlining;
Daniel Dunbarac7ffe02008-10-29 07:56:11 +00001429 } else {
Daniel Dunbar877db382009-06-02 22:07:45 +00001430 if (OptSize) {
1431 // -Os implies -O2
1432 Opts.OptimizationLevel = 2;
1433 } else {
1434 Opts.OptimizationLevel = OptLevel;
1435 }
1436
1437 // We must always run at least the always inlining pass.
1438 if (Opts.OptimizationLevel > 1)
1439 Opts.Inlining = CompileOptions::NormalInlining;
1440 else
1441 Opts.Inlining = CompileOptions::OnlyAlwaysInlining;
Daniel Dunbarac7ffe02008-10-29 07:56:11 +00001442 }
Daniel Dunbar8e8f3b72008-10-29 03:42:18 +00001443
1444 // FIXME: There are llvm-gcc options to control these selectively.
Daniel Dunbar8e8f3b72008-10-29 03:42:18 +00001445 Opts.UnrollLoops = (Opts.OptimizationLevel > 1 && !OptSize);
Chris Lattner7afae712009-03-16 18:41:18 +00001446 Opts.SimplifyLibCalls = !LangOpts.NoBuiltin;
Daniel Dunbardd913e52008-10-31 09:34:21 +00001447
1448#ifdef NDEBUG
1449 Opts.VerifyModule = 0;
1450#endif
Daniel Dunbara034ba82009-02-17 19:47:34 +00001451
1452 Opts.CPU = TargetCPU;
Daniel Dunbar868bd0a2009-05-06 03:16:41 +00001453 Opts.Features.clear();
1454 for (llvm::StringMap<bool>::const_iterator it = Features.begin(),
1455 ie = Features.end(); it != ie; ++it) {
1456 // FIXME: If we are completely confident that we have the right
1457 // set, we only need to pass the minuses.
1458 std::string Name(it->second ? "+" : "-");
1459 Name += it->first();
1460 Opts.Features.push_back(Name);
1461 }
Chris Lattner44502662009-02-18 01:23:44 +00001462
Chris Lattnerbd360642009-03-26 05:00:52 +00001463 Opts.NoCommon = NoCommon | LangOpts.CPlusPlus;
1464
Chris Lattner44502662009-02-18 01:23:44 +00001465 // Handle -ftime-report.
1466 Opts.TimePasses = TimeReport;
Devang Patel24095da2009-06-04 23:32:02 +00001467
1468 Opts.DisableRedZone = DisableRedZone;
Devang Patelacebb392009-06-05 22:05:48 +00001469 Opts.NoImplicitFloat = NoImplicitFloat;
Daniel Dunbar70f92432008-10-23 05:50:47 +00001470}
1471
1472//===----------------------------------------------------------------------===//
Douglas Gregor26df2f02009-04-02 19:05:20 +00001473// Fix-It Options
1474//===----------------------------------------------------------------------===//
1475static llvm::cl::list<ParsedSourceLocation>
1476FixItAtLocations("fixit-at", llvm::cl::value_desc("source-location"),
1477 llvm::cl::desc("Perform Fix-It modifications at the given source location"));
1478
1479//===----------------------------------------------------------------------===//
Eli Friedmanc6d656e2009-05-18 22:39:16 +00001480// ObjC Rewriter Options
1481//===----------------------------------------------------------------------===//
1482static llvm::cl::opt<bool>
1483SilenceRewriteMacroWarning("Wno-rewrite-macros", llvm::cl::init(false),
1484 llvm::cl::desc("Silence ObjC rewriting warnings"));
1485
1486//===----------------------------------------------------------------------===//
Eli Friedman0eeb86e2009-05-19 01:17:04 +00001487// Warning Options
1488//===----------------------------------------------------------------------===//
1489
1490// This gets all -W options, including -Werror, -W[no-]system-headers, etc. The
1491// driver has stripped off -Wa,foo etc. The driver has also translated -W to
1492// -Wextra, so we don't need to worry about it.
1493static llvm::cl::list<std::string>
1494OptWarnings("W", llvm::cl::Prefix, llvm::cl::ValueOptional);
1495
1496static llvm::cl::opt<bool> OptPedantic("pedantic");
1497static llvm::cl::opt<bool> OptPedanticErrors("pedantic-errors");
1498static llvm::cl::opt<bool> OptNoWarnings("w");
1499
1500//===----------------------------------------------------------------------===//
Eli Friedman12d3b1d2009-05-19 03:06:47 +00001501// Preprocessing (-E mode) Options
1502//===----------------------------------------------------------------------===//
1503static llvm::cl::opt<bool>
1504DisableLineMarkers("P", llvm::cl::desc("Disable linemarker output in -E mode"));
1505static llvm::cl::opt<bool>
1506EnableCommentOutput("C", llvm::cl::desc("Enable comment output in -E mode"));
1507static llvm::cl::opt<bool>
1508EnableMacroCommentOutput("CC",
1509 llvm::cl::desc("Enable comment output in -E mode, "
1510 "even from macro expansions"));
1511static llvm::cl::opt<bool>
1512DumpMacros("dM", llvm::cl::desc("Print macro definitions in -E mode instead of"
1513 " normal output"));
1514static llvm::cl::opt<bool>
1515DumpDefines("dD", llvm::cl::desc("Print macro definitions in -E mode in "
1516 "addition to normal output"));
Eli Friedmanb5c8f8b2009-05-19 03:35:57 +00001517
1518//===----------------------------------------------------------------------===//
1519// Dependency file options
1520//===----------------------------------------------------------------------===//
1521static llvm::cl::opt<std::string>
1522DependencyFile("dependency-file",
1523 llvm::cl::desc("Filename (or -) to write dependency output to"));
1524
1525static llvm::cl::opt<bool>
1526DependenciesIncludeSystemHeaders("sys-header-deps",
1527 llvm::cl::desc("Include system headers in dependency output"));
1528
1529static llvm::cl::list<std::string>
1530DependencyTargets("MT",
1531 llvm::cl::desc("Specify target for dependency"));
1532
1533// FIXME: Implement feature
1534static llvm::cl::opt<bool>
1535PhonyDependencyTarget("MP",
1536 llvm::cl::desc("Create phony target for each dependency "
1537 "(other than main file)"));
1538
Eli Friedman12d3b1d2009-05-19 03:06:47 +00001539//===----------------------------------------------------------------------===//
Eli Friedmane71b85f2009-05-19 10:18:02 +00001540// Analysis options
1541//===----------------------------------------------------------------------===//
1542
1543static llvm::cl::list<Analyses>
1544AnalysisList(llvm::cl::desc("Source Code Analysis - Checks and Analyses"),
1545llvm::cl::values(
1546#define ANALYSIS(NAME, CMDFLAG, DESC, SCOPE)\
1547clEnumValN(NAME, CMDFLAG, DESC),
Eli Friedman0ec78fa2009-05-19 21:10:40 +00001548#include "clang/Frontend/Analyses.def"
Eli Friedmane71b85f2009-05-19 10:18:02 +00001549clEnumValEnd));
1550
1551static llvm::cl::opt<AnalysisStores>
1552AnalysisStoreOpt("analyzer-store",
1553 llvm::cl::desc("Source Code Analysis - Abstract Memory Store Models"),
1554 llvm::cl::init(BasicStoreModel),
1555 llvm::cl::values(
1556#define ANALYSIS_STORE(NAME, CMDFLAG, DESC, CREATFN)\
1557clEnumValN(NAME##Model, CMDFLAG, DESC),
Eli Friedman0ec78fa2009-05-19 21:10:40 +00001558#include "clang/Frontend/Analyses.def"
Eli Friedmane71b85f2009-05-19 10:18:02 +00001559clEnumValEnd));
1560
1561static llvm::cl::opt<AnalysisConstraints>
1562AnalysisConstraintsOpt("analyzer-constraints",
1563 llvm::cl::desc("Source Code Analysis - Symbolic Constraint Engines"),
1564 llvm::cl::init(RangeConstraintsModel),
1565 llvm::cl::values(
1566#define ANALYSIS_CONSTRAINTS(NAME, CMDFLAG, DESC, CREATFN)\
1567clEnumValN(NAME##Model, CMDFLAG, DESC),
Eli Friedman0ec78fa2009-05-19 21:10:40 +00001568#include "clang/Frontend/Analyses.def"
Eli Friedmane71b85f2009-05-19 10:18:02 +00001569clEnumValEnd));
1570
1571static llvm::cl::opt<AnalysisDiagClients>
1572AnalysisDiagOpt("analyzer-output",
1573 llvm::cl::desc("Source Code Analysis - Output Options"),
1574 llvm::cl::init(PD_HTML),
1575 llvm::cl::values(
1576#define ANALYSIS_DIAGNOSTICS(NAME, CMDFLAG, DESC, CREATFN, AUTOCREATE)\
1577clEnumValN(PD_##NAME, CMDFLAG, DESC),
Eli Friedman0ec78fa2009-05-19 21:10:40 +00001578#include "clang/Frontend/Analyses.def"
Eli Friedmane71b85f2009-05-19 10:18:02 +00001579clEnumValEnd));
1580
1581static llvm::cl::opt<bool>
1582VisualizeEGDot("analyzer-viz-egraph-graphviz",
1583 llvm::cl::desc("Display exploded graph using GraphViz"));
1584
1585static llvm::cl::opt<bool>
1586VisualizeEGUbi("analyzer-viz-egraph-ubigraph",
1587 llvm::cl::desc("Display exploded graph using Ubigraph"));
1588
1589static llvm::cl::opt<bool>
1590AnalyzeAll("analyzer-opt-analyze-headers",
1591 llvm::cl::desc("Force the static analyzer to analyze "
1592 "functions defined in header files"));
1593
1594static llvm::cl::opt<bool>
1595AnalyzerDisplayProgress("analyzer-display-progress",
1596 llvm::cl::desc("Emit verbose output about the analyzer's progress."));
1597
1598static llvm::cl::opt<bool>
1599PurgeDead("analyzer-purge-dead",
1600 llvm::cl::init(true),
1601 llvm::cl::desc("Remove dead symbols, bindings, and constraints before"
1602 " processing a statement."));
1603
1604static llvm::cl::opt<bool>
1605EagerlyAssume("analyzer-eagerly-assume",
1606 llvm::cl::init(false),
1607 llvm::cl::desc("Eagerly assume the truth/falseness of some "
1608 "symbolic constraints."));
1609
1610static llvm::cl::opt<std::string>
1611AnalyzeSpecificFunction("analyze-function",
1612 llvm::cl::desc("Run analysis on specific function"));
1613
1614static llvm::cl::opt<bool>
1615TrimGraph("trim-egraph",
1616 llvm::cl::desc("Only show error-related paths in the analysis graph"));
1617
1618static AnalyzerOptions ReadAnalyzerOptions() {
1619 AnalyzerOptions Opts;
1620 Opts.AnalysisList = AnalysisList;
1621 Opts.AnalysisStoreOpt = AnalysisStoreOpt;
1622 Opts.AnalysisConstraintsOpt = AnalysisConstraintsOpt;
1623 Opts.AnalysisDiagOpt = AnalysisDiagOpt;
1624 Opts.VisualizeEGDot = VisualizeEGDot;
1625 Opts.VisualizeEGUbi = VisualizeEGUbi;
1626 Opts.AnalyzeAll = AnalyzeAll;
1627 Opts.AnalyzerDisplayProgress = AnalyzerDisplayProgress;
1628 Opts.PurgeDead = PurgeDead;
1629 Opts.EagerlyAssume = EagerlyAssume;
1630 Opts.AnalyzeSpecificFunction = AnalyzeSpecificFunction;
1631 Opts.TrimGraph = TrimGraph;
1632 return Opts;
1633}
1634
1635//===----------------------------------------------------------------------===//
Chris Lattner75a97cb2009-04-17 21:05:01 +00001636// -dump-build-information Stuff
1637//===----------------------------------------------------------------------===//
1638
1639static llvm::cl::opt<std::string>
1640DumpBuildInformation("dump-build-information",
1641 llvm::cl::value_desc("filename"),
1642 llvm::cl::desc("output a dump of some build information to a file"));
1643
1644static llvm::raw_ostream *BuildLogFile = 0;
1645
1646/// LoggingDiagnosticClient - This is a simple diagnostic client that forwards
1647/// all diagnostics to both BuildLogFile and a chained DiagnosticClient.
1648namespace {
1649class LoggingDiagnosticClient : public DiagnosticClient {
1650 llvm::OwningPtr<DiagnosticClient> Chain1;
1651 llvm::OwningPtr<DiagnosticClient> Chain2;
1652public:
1653
1654 LoggingDiagnosticClient(DiagnosticClient *Normal) {
1655 // Output diags both where requested...
1656 Chain1.reset(Normal);
1657 // .. and to our log file.
1658 Chain2.reset(new TextDiagnosticPrinter(*BuildLogFile,
1659 !NoShowColumn,
1660 !NoCaretDiagnostics,
1661 !NoShowLocation,
1662 PrintSourceRangeInfo,
Chris Lattneraa5bf2e2009-04-19 07:44:08 +00001663 PrintDiagnosticOption,
Douglas Gregorfffd93f2009-05-01 21:53:04 +00001664 !NoDiagnosticsFixIt,
Nate Begeman4e3629e2009-06-25 22:43:10 +00001665 MessageLength));
Chris Lattner75a97cb2009-04-17 21:05:01 +00001666 }
1667
1668 virtual void setLangOptions(const LangOptions *LO) {
1669 Chain1->setLangOptions(LO);
1670 Chain2->setLangOptions(LO);
1671 }
1672
1673 virtual bool IncludeInDiagnosticCounts() const {
1674 return Chain1->IncludeInDiagnosticCounts();
1675 }
1676
1677 virtual void HandleDiagnostic(Diagnostic::Level DiagLevel,
1678 const DiagnosticInfo &Info) {
1679 Chain1->HandleDiagnostic(DiagLevel, Info);
1680 Chain2->HandleDiagnostic(DiagLevel, Info);
1681 }
1682};
1683} // end anonymous namespace.
1684
1685static void SetUpBuildDumpLog(unsigned argc, char **argv,
1686 llvm::OwningPtr<DiagnosticClient> &DiagClient) {
1687
1688 std::string ErrorInfo;
1689 BuildLogFile = new llvm::raw_fd_ostream(DumpBuildInformation.c_str(), false,
Dan Gohman92db2842009-07-15 17:32:18 +00001690 /*Force=*/true, ErrorInfo);
Chris Lattner75a97cb2009-04-17 21:05:01 +00001691
1692 if (!ErrorInfo.empty()) {
1693 llvm::errs() << "error opening -dump-build-information file '"
1694 << DumpBuildInformation << "', option ignored!\n";
1695 delete BuildLogFile;
1696 BuildLogFile = 0;
1697 DumpBuildInformation = "";
1698 return;
1699 }
1700
1701 (*BuildLogFile) << "clang-cc command line arguments: ";
1702 for (unsigned i = 0; i != argc; ++i)
1703 (*BuildLogFile) << argv[i] << ' ';
1704 (*BuildLogFile) << '\n';
1705
1706 // LoggingDiagnosticClient - Insert a new logging diagnostic client in between
1707 // the diagnostic producers and the normal receiver.
1708 DiagClient.reset(new LoggingDiagnosticClient(DiagClient.take()));
1709}
1710
1711
1712
1713//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +00001714// Main driver
1715//===----------------------------------------------------------------------===//
1716
Eli Friedman66d6f042009-05-18 22:20:00 +00001717static llvm::raw_ostream* ComputeOutFile(const std::string& InFile,
1718 const char* Extension,
1719 bool Binary,
1720 llvm::sys::Path& OutPath) {
1721 llvm::raw_ostream* Ret;
1722 bool UseStdout = false;
1723 std::string OutFile;
1724 if (OutputFile == "-" || (OutputFile.empty() && InFile == "-")) {
1725 UseStdout = true;
1726 } else if (!OutputFile.empty()) {
1727 OutFile = OutputFile;
1728 } else if (Extension) {
1729 llvm::sys::Path Path(InFile);
1730 Path.eraseSuffix();
1731 Path.appendSuffix(Extension);
1732 OutFile = Path.toString();
1733 } else {
1734 UseStdout = true;
Chris Lattner8a5c8092009-02-18 01:20:05 +00001735 }
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +00001736
Eli Friedman66d6f042009-05-18 22:20:00 +00001737 if (UseStdout) {
1738 Ret = new llvm::raw_stdout_ostream();
1739 if (Binary)
1740 llvm::sys::Program::ChangeStdoutToBinary();
1741 } else {
1742 std::string Error;
Dan Gohman92db2842009-07-15 17:32:18 +00001743 Ret = new llvm::raw_fd_ostream(OutFile.c_str(), Binary,
1744 /*Force=*/true, Error);
Eli Friedman66d6f042009-05-18 22:20:00 +00001745 if (!Error.empty()) {
1746 // FIXME: Don't fail this way.
1747 llvm::cerr << "ERROR: " << Error << "\n";
1748 ::exit(1);
1749 }
1750 OutPath = OutFile;
Ted Kremenekdb094a22007-12-05 18:27:04 +00001751 }
Eli Friedman66d6f042009-05-18 22:20:00 +00001752
1753 return Ret;
Ted Kremenekdb094a22007-12-05 18:27:04 +00001754}
1755
Reid Spencer5f016e22007-07-11 17:01:13 +00001756/// ProcessInputFile - Process a single input file with the specified state.
1757///
Ted Kremenek339b9c22008-04-17 22:31:54 +00001758static void ProcessInputFile(Preprocessor &PP, PreprocessorFactory &PPF,
Daniel Dunbar868bd0a2009-05-06 03:16:41 +00001759 const std::string &InFile, ProgActions PA,
Owen Anderson42253cc2009-07-01 17:00:06 +00001760 const llvm::StringMap<bool> &Features,
Owen Anderson8f1ca782009-07-01 23:14:14 +00001761 llvm::LLVMContext& Context) {
Eli Friedman66d6f042009-05-18 22:20:00 +00001762 llvm::OwningPtr<llvm::raw_ostream> OS;
Ted Kremenek7e7e6252008-08-08 02:46:37 +00001763 llvm::OwningPtr<ASTConsumer> Consumer;
Chris Lattnerbd247762007-07-22 06:05:44 +00001764 bool ClearSourceMgr = false;
Douglas Gregor558cb562009-04-02 01:08:08 +00001765 FixItRewriter *FixItRewrite = 0;
Douglas Gregorf807fe02009-04-14 16:27:31 +00001766 bool CompleteTranslationUnit = true;
Eli Friedman66d6f042009-05-18 22:20:00 +00001767 llvm::sys::Path OutPath;
Douglas Gregor558cb562009-04-02 01:08:08 +00001768
Ted Kremenek85888962008-10-21 00:54:44 +00001769 switch (PA) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001770 default:
Eli Friedman66d6f042009-05-18 22:20:00 +00001771 fprintf(stderr, "Unexpected program action!\n");
1772 HadErrors = true;
1773 return;
1774
1775 case ASTPrint:
1776 OS.reset(ComputeOutFile(InFile, 0, false, OutPath));
1777 Consumer.reset(CreateASTPrinter(OS.get()));
1778 break;
Ted Kremenekdb094a22007-12-05 18:27:04 +00001779
Douglas Gregoree75c052009-05-21 20:55:50 +00001780 case ASTPrintXML:
1781 OS.reset(ComputeOutFile(InFile, "xml", false, OutPath));
1782 Consumer.reset(CreateASTPrinterXML(OS.get()));
1783 break;
1784
Eli Friedman66d6f042009-05-18 22:20:00 +00001785 case ASTDump:
Douglas Gregor4fe0c8e2009-05-30 00:08:05 +00001786 Consumer.reset(CreateASTDumper());
Eli Friedman66d6f042009-05-18 22:20:00 +00001787 break;
1788
Eli Friedman66d6f042009-05-18 22:20:00 +00001789 case ASTView:
Douglas Gregor4fe0c8e2009-05-30 00:08:05 +00001790 Consumer.reset(CreateASTViewer());
Eli Friedman66d6f042009-05-18 22:20:00 +00001791 break;
1792
1793 case PrintDeclContext:
1794 Consumer.reset(CreateDeclContextPrinter());
1795 break;
1796
1797 case EmitHTML:
1798 OS.reset(ComputeOutFile(InFile, 0, true, OutPath));
1799 Consumer.reset(CreateHTMLPrinter(OS.get(), PP.getDiagnostics(), &PP, &PPF));
1800 break;
1801
1802 case InheritanceView:
1803 Consumer.reset(CreateInheritanceViewer(InheritanceViewCls));
1804 break;
1805
1806 case EmitAssembly:
1807 case EmitLLVM:
1808 case EmitBC:
1809 case EmitLLVMOnly: {
1810 BackendAction Act;
1811 if (ProgAction == EmitAssembly) {
1812 Act = Backend_EmitAssembly;
1813 OS.reset(ComputeOutFile(InFile, "s", true, OutPath));
1814 } else if (ProgAction == EmitLLVM) {
1815 Act = Backend_EmitLL;
1816 OS.reset(ComputeOutFile(InFile, "ll", true, OutPath));
1817 } else if (ProgAction == EmitLLVMOnly) {
1818 Act = Backend_EmitNothing;
1819 } else {
1820 Act = Backend_EmitBC;
1821 OS.reset(ComputeOutFile(InFile, "bc", true, OutPath));
Ted Kremenekdb094a22007-12-05 18:27:04 +00001822 }
Ted Kremenekfdfc1982007-12-19 22:24:34 +00001823
Eli Friedman66d6f042009-05-18 22:20:00 +00001824 CompileOptions Opts;
1825 InitializeCompileOptions(Opts, PP.getLangOptions(), Features);
1826 Consumer.reset(CreateBackendConsumer(Act, PP.getDiagnostics(),
1827 PP.getLangOptions(), Opts, InFile,
Owen Anderson42253cc2009-07-01 17:00:06 +00001828 OS.get(), Context));
Ted Kremenekdb094a22007-12-05 18:27:04 +00001829 break;
Eli Friedman66d6f042009-05-18 22:20:00 +00001830 }
1831
1832 case GeneratePCH:
Douglas Gregore650c8c2009-07-07 00:12:59 +00001833 if (RelocatablePCH.getValue() && !isysroot.getNumOccurrences()) {
1834 PP.Diag(SourceLocation(), diag::err_relocatable_without_without_isysroot);
1835 RelocatablePCH.setValue(false);
1836 }
1837
Eli Friedman66d6f042009-05-18 22:20:00 +00001838 OS.reset(ComputeOutFile(InFile, 0, true, OutPath));
Douglas Gregore650c8c2009-07-07 00:12:59 +00001839 if (RelocatablePCH.getValue())
1840 Consumer.reset(CreatePCHGenerator(PP, OS.get(), isysroot.c_str()));
1841 else
1842 Consumer.reset(CreatePCHGenerator(PP, OS.get()));
Eli Friedman66d6f042009-05-18 22:20:00 +00001843 CompleteTranslationUnit = false;
1844 break;
1845
1846 case RewriteObjC:
1847 OS.reset(ComputeOutFile(InFile, "cpp", true, OutPath));
Eli Friedmanbce831b2009-05-18 22:29:17 +00001848 Consumer.reset(CreateObjCRewriter(InFile, OS.get(), PP.getDiagnostics(),
Eli Friedmanc6d656e2009-05-18 22:39:16 +00001849 PP.getLangOptions(),
1850 SilenceRewriteMacroWarning));
Eli Friedman66d6f042009-05-18 22:20:00 +00001851 break;
1852
1853 case RewriteBlocks:
1854 Consumer.reset(CreateBlockRewriter(InFile, PP.getDiagnostics(),
1855 PP.getLangOptions()));
1856 break;
1857
Eli Friedmane71b85f2009-05-19 10:18:02 +00001858 case RunAnalysis: {
Eli Friedman66d6f042009-05-18 22:20:00 +00001859 Consumer.reset(CreateAnalysisConsumer(PP.getDiagnostics(), &PP, &PPF,
Eli Friedmane71b85f2009-05-19 10:18:02 +00001860 PP.getLangOptions(), OutputFile,
1861 ReadAnalyzerOptions()));
Eli Friedman66d6f042009-05-18 22:20:00 +00001862 break;
Eli Friedmane71b85f2009-05-19 10:18:02 +00001863 }
Eli Friedman66d6f042009-05-18 22:20:00 +00001864
Chris Lattnerc106c102008-10-12 05:03:36 +00001865 case DumpRawTokens: {
Chris Lattner47099742009-02-18 01:51:21 +00001866 llvm::TimeRegion Timer(ClangFrontendTimer);
Chris Lattnerc106c102008-10-12 05:03:36 +00001867 SourceManager &SM = PP.getSourceManager();
Chris Lattnerc106c102008-10-12 05:03:36 +00001868 // Start lexing the specified input file.
Chris Lattner025c3a62009-01-17 07:35:14 +00001869 Lexer RawLex(SM.getMainFileID(), SM, PP.getLangOptions());
Chris Lattnerc106c102008-10-12 05:03:36 +00001870 RawLex.SetKeepWhitespaceMode(true);
1871
1872 Token RawTok;
Chris Lattnerc106c102008-10-12 05:03:36 +00001873 RawLex.LexFromRawLexer(RawTok);
1874 while (RawTok.isNot(tok::eof)) {
1875 PP.DumpToken(RawTok, true);
1876 fprintf(stderr, "\n");
1877 RawLex.LexFromRawLexer(RawTok);
1878 }
1879 ClearSourceMgr = true;
1880 break;
1881 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001882 case DumpTokens: { // Token dump mode.
Chris Lattner47099742009-02-18 01:51:21 +00001883 llvm::TimeRegion Timer(ClangFrontendTimer);
Chris Lattnerd2177732007-07-20 16:59:19 +00001884 Token Tok;
Chris Lattnerc106c102008-10-12 05:03:36 +00001885 // Start preprocessing the specified input file.
Ted Kremenek95041a22007-12-19 22:51:13 +00001886 PP.EnterMainSourceFile();
Reid Spencer5f016e22007-07-11 17:01:13 +00001887 do {
1888 PP.Lex(Tok);
1889 PP.DumpToken(Tok, true);
1890 fprintf(stderr, "\n");
Chris Lattner057aaf62007-10-09 18:03:42 +00001891 } while (Tok.isNot(tok::eof));
Chris Lattnerbd247762007-07-22 06:05:44 +00001892 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001893 break;
1894 }
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001895 case RunPreprocessorOnly:
Reid Spencer5f016e22007-07-11 17:01:13 +00001896 break;
Ted Kremenek85888962008-10-21 00:54:44 +00001897
Douglas Gregorbf1bd6e2009-04-02 23:43:50 +00001898 case GeneratePTH: {
Chris Lattner47099742009-02-18 01:51:21 +00001899 llvm::TimeRegion Timer(ClangFrontendTimer);
Eli Friedmanf54fce82009-05-19 01:02:07 +00001900 if (OutputFile.empty() || OutputFile == "-") {
1901 // FIXME: Don't fail this way.
1902 // FIXME: Verify that we can actually seek in the given file.
1903 llvm::cerr << "ERROR: PTH requires an seekable file for output!\n";
1904 ::exit(1);
1905 }
1906 OS.reset(ComputeOutFile(InFile, 0, true, OutPath));
1907 CacheTokens(PP, static_cast<llvm::raw_fd_ostream*>(OS.get()));
Ted Kremenek85888962008-10-21 00:54:44 +00001908 ClearSourceMgr = true;
1909 break;
1910 }
Douglas Gregor6ab35242009-04-09 21:40:53 +00001911
Chris Lattnercc7dea82009-04-27 22:02:30 +00001912 case PrintPreprocessedInput:
Eli Friedmanf54fce82009-05-19 01:02:07 +00001913 OS.reset(ComputeOutFile(InFile, 0, true, OutPath));
Reid Spencer5f016e22007-07-11 17:01:13 +00001914 break;
Chris Lattnerb57e3d42008-05-08 06:52:13 +00001915
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001916 case ParseNoop:
Reid Spencer5f016e22007-07-11 17:01:13 +00001917 break;
1918
Chris Lattner47099742009-02-18 01:51:21 +00001919 case ParsePrintCallbacks: {
1920 llvm::TimeRegion Timer(ClangFrontendTimer);
Eli Friedmanf54fce82009-05-19 01:02:07 +00001921 OS.reset(ComputeOutFile(InFile, 0, true, OutPath));
1922 ParseFile(PP, CreatePrintParserActionsAction(PP, OS.get()));
Chris Lattnerbd247762007-07-22 06:05:44 +00001923 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001924 break;
Chris Lattner47099742009-02-18 01:51:21 +00001925 }
1926
1927 case ParseSyntaxOnly: { // -fsyntax-only
1928 llvm::TimeRegion Timer(ClangFrontendTimer);
Ted Kremenek7e7e6252008-08-08 02:46:37 +00001929 Consumer.reset(new ASTConsumer());
Ted Kremenek2bf55142007-09-17 20:49:30 +00001930 break;
Chris Lattner47099742009-02-18 01:51:21 +00001931 }
Chris Lattnerb57e3d42008-05-08 06:52:13 +00001932
1933 case RewriteMacros:
Eli Friedmanf54fce82009-05-19 01:02:07 +00001934 OS.reset(ComputeOutFile(InFile, 0, true, OutPath));
1935 RewriteMacrosInInput(PP, OS.get());
Chris Lattnerb57e3d42008-05-08 06:52:13 +00001936 ClearSourceMgr = true;
1937 break;
Chris Lattnerb13c5ee2008-10-12 05:29:20 +00001938
Eli Friedmanf54fce82009-05-19 01:02:07 +00001939 case RewriteTest:
1940 OS.reset(ComputeOutFile(InFile, 0, true, OutPath));
1941 DoRewriteTest(PP, OS.get());
Chris Lattnerb13c5ee2008-10-12 05:29:20 +00001942 ClearSourceMgr = true;
1943 break;
Douglas Gregor558cb562009-04-02 01:08:08 +00001944
1945 case FixIt:
1946 llvm::TimeRegion Timer(ClangFrontendTimer);
1947 Consumer.reset(new ASTConsumer());
Douglas Gregorde4bf6a2009-04-02 17:13:00 +00001948 FixItRewrite = new FixItRewriter(PP.getDiagnostics(),
Chris Lattner2c78b872009-04-14 23:22:57 +00001949 PP.getSourceManager(),
1950 PP.getLangOptions());
Douglas Gregor558cb562009-04-02 01:08:08 +00001951 break;
Chris Lattner47099742009-02-18 01:51:21 +00001952 }
Ted Kremenek46157b52009-01-28 04:29:29 +00001953
Chris Lattner1aee61a2009-04-27 21:25:27 +00001954 if (FixItAtLocations.size() > 0) {
1955 // Even without the "-fixit" flag, with may have some specific
1956 // locations where the user has requested fixes. Process those
1957 // locations now.
1958 if (!FixItRewrite)
1959 FixItRewrite = new FixItRewriter(PP.getDiagnostics(),
1960 PP.getSourceManager(),
1961 PP.getLangOptions());
Chris Lattner9ecd26a2009-03-28 01:37:17 +00001962
Chris Lattner1aee61a2009-04-27 21:25:27 +00001963 bool AddedFixitLocation = false;
1964 for (unsigned Idx = 0, Last = FixItAtLocations.size();
1965 Idx != Last; ++Idx) {
1966 RequestedSourceLocation Requested;
Argyrios Kyrtzidis34d25d82009-06-23 22:01:39 +00001967 if (ResolveParsedLocation(FixItAtLocations[Idx],
1968 PP.getFileManager(), Requested)) {
Chris Lattner1aee61a2009-04-27 21:25:27 +00001969 fprintf(stderr, "FIX-IT could not find file \"%s\"\n",
1970 FixItAtLocations[Idx].FileName.c_str());
1971 } else {
1972 FixItRewrite->addFixItLocation(Requested);
1973 AddedFixitLocation = true;
Douglas Gregor26df2f02009-04-02 19:05:20 +00001974 }
1975 }
1976
Chris Lattner1aee61a2009-04-27 21:25:27 +00001977 if (!AddedFixitLocation) {
1978 // All of the fix-it locations were bad. Don't fix anything.
1979 delete FixItRewrite;
1980 FixItRewrite = 0;
1981 }
1982 }
1983
1984 llvm::OwningPtr<ASTContext> ContextOwner;
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001985 if (Consumer)
Chris Lattner9ecd26a2009-03-28 01:37:17 +00001986 ContextOwner.reset(new ASTContext(PP.getLangOptions(),
1987 PP.getSourceManager(),
1988 PP.getTargetInfo(),
1989 PP.getIdentifierTable(),
1990 PP.getSelectorTable(),
Chris Lattner1b63e4f2009-06-14 01:54:56 +00001991 PP.getBuiltinInfo(),
Douglas Gregor2deaea32009-04-22 18:49:13 +00001992 /* FreeMemory = */ !DisableFree,
Chris Lattner1b63e4f2009-06-14 01:54:56 +00001993 /* size_reserve = */0));
1994
Chris Lattnercc7dea82009-04-27 22:02:30 +00001995 llvm::OwningPtr<PCHReader> Reader;
1996 llvm::OwningPtr<ExternalASTSource> Source;
1997
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001998 if (!ImplicitIncludePCH.empty()) {
Douglas Gregore650c8c2009-07-07 00:12:59 +00001999 // If the user specified -isysroot, it will be used for relocatable PCH
2000 // files.
2001 const char *isysrootPCH = 0;
2002 if (isysroot.getNumOccurrences() != 0)
2003 isysrootPCH = isysroot.c_str();
2004
2005 Reader.reset(new PCHReader(PP, ContextOwner.get(), isysrootPCH));
Chris Lattnercc7dea82009-04-27 22:02:30 +00002006
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002007 // The user has asked us to include a precompiled header. Load
2008 // the precompiled header into the AST context.
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002009 switch (Reader->ReadPCH(ImplicitIncludePCH)) {
2010 case PCHReader::Success: {
Douglas Gregore721f952009-04-28 18:58:38 +00002011 // Set the predefines buffer as suggested by the PCH
2012 // reader. Typically, the predefines buffer will be empty.
2013 PP.setPredefines(Reader->getSuggestedPredefines());
2014
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002015 // Attach the PCH reader to the AST context as an external AST
2016 // source, so that declarations will be deserialized from the
2017 // PCH file as needed.
Chris Lattnercc7dea82009-04-27 22:02:30 +00002018 if (ContextOwner) {
2019 Source.reset(Reader.take());
Douglas Gregore1d918e2009-04-10 23:10:45 +00002020 ContextOwner->setExternalSource(Source);
Chris Lattnercc7dea82009-04-27 22:02:30 +00002021 }
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002022 break;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002023 }
2024
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002025 case PCHReader::Failure:
2026 // Unrecoverable failure: don't even try to process the input
2027 // file.
2028 return;
2029
2030 case PCHReader::IgnorePCH:
Douglas Gregor1ab86ac2009-04-28 22:01:16 +00002031 // No suitable PCH file could be found. Return an error.
2032 return;
2033
2034#if 0
2035 // FIXME: We can recover from failed attempts to load PCH
2036 // files. This code will do so, if we ever want to enable it.
2037
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002038 // We delayed the initialization of builtins in the hope of
2039 // loading the PCH file. Since the PCH file could not be
2040 // loaded, initialize builtins now.
2041 if (ContextOwner)
2042 ContextOwner->InitializeBuiltins(PP.getIdentifierTable());
Douglas Gregor1ab86ac2009-04-28 22:01:16 +00002043#endif
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002044 }
2045
2046 // Finish preprocessor initialization. We do this now (rather
2047 // than earlier) because this initialization creates new source
2048 // location entries in the source manager, which must come after
2049 // the source location entries for the PCH file.
2050 if (InitializeSourceManager(PP, InFile))
2051 return;
Ted Kremenek46157b52009-01-28 04:29:29 +00002052 }
Daniel Dunbar879c3ea2008-10-27 22:03:52 +00002053
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002054
2055 // If we have an ASTConsumer, run the parser with it.
2056 if (Consumer)
2057 ParseAST(PP, Consumer.get(), *ContextOwner.get(), Stats,
2058 CompleteTranslationUnit);
2059
2060 if (PA == RunPreprocessorOnly) { // Just lex as fast as we can, no output.
2061 llvm::TimeRegion Timer(ClangFrontendTimer);
2062 Token Tok;
2063 // Start parsing the specified input file.
2064 PP.EnterMainSourceFile();
2065 do {
2066 PP.Lex(Tok);
2067 } while (Tok.isNot(tok::eof));
2068 ClearSourceMgr = true;
2069 } else if (PA == ParseNoop) { // -parse-noop
2070 llvm::TimeRegion Timer(ClangFrontendTimer);
2071 ParseFile(PP, new MinimalAction(PP));
2072 ClearSourceMgr = true;
Chris Lattnercc7dea82009-04-27 22:02:30 +00002073 } else if (PA == PrintPreprocessedInput){ // -E mode.
2074 llvm::TimeRegion Timer(ClangFrontendTimer);
Eli Friedman12d3b1d2009-05-19 03:06:47 +00002075 if (DumpMacros)
2076 DoPrintMacros(PP, OS.get());
2077 else
2078 DoPrintPreprocessedInput(PP, OS.get(), EnableCommentOutput,
2079 EnableMacroCommentOutput,
2080 DisableLineMarkers, DumpDefines);
Chris Lattnercc7dea82009-04-27 22:02:30 +00002081 ClearSourceMgr = true;
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002082 }
2083
Chris Lattner1aee61a2009-04-27 21:25:27 +00002084 if (FixItRewrite)
2085 FixItRewrite->WriteFixedFile(InFile, OutputFile);
Daniel Dunbar70186ab2009-07-29 02:40:09 +00002086
2087 // Disable the consumer prior to the context, the consumer may perform actions
2088 // in its destructor which require the context.
2089 if (DisableFree)
2090 Consumer.take();
2091 else
2092 Consumer.reset();
Chris Lattner1aee61a2009-04-27 21:25:27 +00002093
2094 // If in -disable-free mode, don't deallocate ASTContext.
2095 if (DisableFree)
2096 ContextOwner.take();
2097 else
2098 ContextOwner.reset(); // Delete ASTContext
Eli Friedman66d6f042009-05-18 22:20:00 +00002099
Daniel Dunbar879c3ea2008-10-27 22:03:52 +00002100 if (VerifyDiagnostics)
Daniel Dunbar276373d2008-10-27 22:10:13 +00002101 if (CheckDiagnostics(PP))
2102 exit(1);
Chris Lattnere66b65c2008-02-06 01:42:25 +00002103
Reid Spencer5f016e22007-07-11 17:01:13 +00002104 if (Stats) {
Ted Kremenekfdfc1982007-12-19 22:24:34 +00002105 fprintf(stderr, "\nSTATISTICS FOR '%s':\n", InFile.c_str());
Reid Spencer5f016e22007-07-11 17:01:13 +00002106 PP.PrintStats();
2107 PP.getIdentifierTable().PrintStats();
Chris Lattnerdee73592007-12-15 20:48:40 +00002108 PP.getHeaderSearchInfo().PrintStats();
Ted Kremenek1b95a652009-01-09 18:20:21 +00002109 PP.getSourceManager().PrintStats();
Reid Spencer5f016e22007-07-11 17:01:13 +00002110 fprintf(stderr, "\n");
2111 }
Chris Lattnerbd247762007-07-22 06:05:44 +00002112
2113 // For a multi-file compilation, some things are ok with nuking the source
2114 // manager tables, other require stable fileid/macroid's across multiple
2115 // files.
Chris Lattnerdee73592007-12-15 20:48:40 +00002116 if (ClearSourceMgr)
2117 PP.getSourceManager().clearIDTables();
Daniel Dunbard68ba0e2008-11-11 06:35:39 +00002118
Eli Friedman66d6f042009-05-18 22:20:00 +00002119 // Always delete the output stream because we don't want to leak file
2120 // handles. Also, we don't want to try to erase an open file.
2121 OS.reset();
2122
2123 if ((HadErrors || (PP.getDiagnostics().getNumErrors() != 0)) &&
2124 !OutPath.isEmpty()) {
2125 // If we had errors, try to erase the output file.
2126 OutPath.eraseFromDisk();
2127 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002128}
2129
2130static llvm::cl::list<std::string>
2131InputFilenames(llvm::cl::Positional, llvm::cl::desc("<input files>"));
2132
Reid Spencer5f016e22007-07-11 17:01:13 +00002133int main(int argc, char **argv) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002134 llvm::sys::PrintStackTraceOnErrorSignal();
Chris Lattner09e94a32009-03-04 21:41:39 +00002135 llvm::PrettyStackTraceProgram X(argc, argv);
Owen Andersond7200462009-07-16 00:14:12 +00002136 llvm::LLVMContext &Context = llvm::getGlobalContext();
Chris Lattnerdc763102009-03-06 05:38:04 +00002137 llvm::cl::ParseCommandLineOptions(argc, argv,
Chris Lattner110e4782009-03-06 05:38:25 +00002138 "LLVM 'Clang' Compiler: http://clang.llvm.org\n");
Owen Anderson42253cc2009-07-01 17:00:06 +00002139
Chris Lattner2fe11942009-06-17 17:25:50 +00002140 llvm::InitializeAllTargets();
2141 llvm::InitializeAllAsmPrinters();
2142
Chris Lattner47099742009-02-18 01:51:21 +00002143 if (TimeReport)
2144 ClangFrontendTimer = new llvm::Timer("Clang front-end time");
2145
Daniel Dunbar08e6dc62009-05-28 16:37:33 +00002146 if (Verbose)
2147 fprintf(stderr, "clang-cc version 1.0 based upon " PACKAGE_STRING
2148 " hosted on " LLVM_HOSTTRIPLE "\n");
2149
Reid Spencer5f016e22007-07-11 17:01:13 +00002150 // If no input was specified, read from stdin.
2151 if (InputFilenames.empty())
2152 InputFilenames.push_back("-");
Douglas Gregor68a0d782009-05-02 00:03:46 +00002153
Ted Kremenek31e703b2007-12-11 23:28:38 +00002154 // Create the diagnostic client for reporting errors or for
2155 // implementing -verify.
Chris Lattner409d4e72009-04-17 20:40:01 +00002156 llvm::OwningPtr<DiagnosticClient> DiagClient;
2157 if (VerifyDiagnostics) {
2158 // When checking diagnostics, just buffer them up.
2159 DiagClient.reset(new TextDiagnosticBuffer());
2160 if (InputFilenames.size() != 1) {
2161 fprintf(stderr, "-verify only works on single input files for now.\n");
2162 return 1;
2163 }
2164 if (!HTMLDiag.empty()) {
2165 fprintf(stderr, "-verify and -html-diags don't work together\n");
2166 return 1;
2167 }
2168 } else if (HTMLDiag.empty()) {
Ted Kremenekb4398aa2008-08-07 17:49:57 +00002169 // Print diagnostics to stderr by default.
Douglas Gregor68a0d782009-05-02 00:03:46 +00002170
2171 // If -fmessage-length=N was not specified, determine whether this
2172 // is a terminal and, if so, implicitly define -fmessage-length
2173 // appropriately.
2174 if (MessageLength.getNumOccurrences() == 0)
Douglas Gregor67187ce2009-05-11 18:06:49 +00002175 MessageLength.setValue(llvm::sys::Process::StandardErrColumns());
Douglas Gregor68a0d782009-05-02 00:03:46 +00002176
Torok Edwin603fca72009-06-04 07:18:23 +00002177 if (!NoColorDiagnostic) {
2178 NoColorDiagnostic.setValue(!llvm::sys::Process::StandardErrHasColors());
2179 }
2180
Chris Lattner409d4e72009-04-17 20:40:01 +00002181 DiagClient.reset(new TextDiagnosticPrinter(llvm::errs(),
Chris Lattnera03a5b52008-11-19 06:56:25 +00002182 !NoShowColumn,
Chris Lattner65f5e642009-01-30 19:01:41 +00002183 !NoCaretDiagnostics,
Chris Lattner1fbee5d2009-03-13 01:08:23 +00002184 !NoShowLocation,
Chris Lattnerd51d74a2009-04-16 05:44:38 +00002185 PrintSourceRangeInfo,
Chris Lattneraa5bf2e2009-04-19 07:44:08 +00002186 PrintDiagnosticOption,
Douglas Gregorfffd93f2009-05-01 21:53:04 +00002187 !NoDiagnosticsFixIt,
Torok Edwin603fca72009-06-04 07:18:23 +00002188 MessageLength,
2189 !NoColorDiagnostic));
Ted Kremenekb4398aa2008-08-07 17:49:57 +00002190 } else {
Chris Lattner409d4e72009-04-17 20:40:01 +00002191 DiagClient.reset(CreateHTMLDiagnosticClient(HTMLDiag));
Reid Spencer5f016e22007-07-11 17:01:13 +00002192 }
Chris Lattner75a97cb2009-04-17 21:05:01 +00002193
2194 if (!DumpBuildInformation.empty()) {
2195 if (!HTMLDiag.empty()) {
2196 fprintf(stderr,
2197 "-dump-build-information and -html-diags don't work together\n");
2198 return 1;
2199 }
2200
2201 SetUpBuildDumpLog(argc, argv, DiagClient);
2202 }
2203
Ted Kremenekb4398aa2008-08-07 17:49:57 +00002204
Reid Spencer5f016e22007-07-11 17:01:13 +00002205 // Configure our handling of diagnostics.
Ted Kremenekb4398aa2008-08-07 17:49:57 +00002206 Diagnostic Diags(DiagClient.get());
Eli Friedman0eeb86e2009-05-19 01:17:04 +00002207 if (ProcessWarningOptions(Diags, OptWarnings, OptPedantic, OptPedanticErrors,
2208 OptNoWarnings))
Sebastian Redl63a9e0f2009-03-06 17:41:35 +00002209 return 1;
Ted Kremenek31e703b2007-12-11 23:28:38 +00002210
Chris Lattner4f037832007-12-05 23:24:17 +00002211 // -I- is a deprecated GCC feature, scan for it and reject it.
2212 for (unsigned i = 0, e = I_dirs.size(); i != e; ++i) {
2213 if (I_dirs[i] == "-") {
Chris Lattner5917fe12008-11-18 05:05:28 +00002214 Diags.Report(FullSourceLoc(), diag::err_pp_I_dash_not_supported);
Chris Lattner4f037832007-12-05 23:24:17 +00002215 I_dirs.erase(I_dirs.begin()+i);
2216 --i;
2217 }
2218 }
Chris Lattner11215192008-03-14 06:12:05 +00002219
2220 // Get information about the target being compiled for.
2221 std::string Triple = CreateTargetTriple();
Ted Kremenek7a08e282008-08-07 18:13:12 +00002222 llvm::OwningPtr<TargetInfo> Target(TargetInfo::CreateTargetInfo(Triple));
2223
Chris Lattner11215192008-03-14 06:12:05 +00002224 if (Target == 0) {
Daniel Dunbar50f4f462009-03-12 10:14:16 +00002225 Diags.Report(FullSourceLoc(), diag::err_fe_unknown_triple)
2226 << Triple.c_str();
Sebastian Redlc5613db2009-03-07 12:09:25 +00002227 return 1;
Chris Lattner11215192008-03-14 06:12:05 +00002228 }
Chris Lattner4f037832007-12-05 23:24:17 +00002229
Daniel Dunbard4270232009-01-20 23:17:32 +00002230 if (!InheritanceViewCls.empty()) // C++ visualization?
Ted Kremenek7cae2f62008-10-23 23:36:29 +00002231 ProgAction = InheritanceView;
Ted Kremenekb4398aa2008-08-07 17:49:57 +00002232
Ted Kremenekc0c03bc2008-06-06 22:42:39 +00002233 llvm::OwningPtr<SourceManager> SourceMgr;
2234
Chris Lattner2c78b872009-04-14 23:22:57 +00002235 // Create a file manager object to provide access to and cache the filesystem.
2236 FileManager FileMgr;
Douglas Gregor4fed3f42009-04-27 18:38:38 +00002237
Daniel Dunbar868bd0a2009-05-06 03:16:41 +00002238 // Compute the feature set, unfortunately this effects the language!
2239 llvm::StringMap<bool> Features;
2240 ComputeFeatureMap(Target.get(), Features);
2241
Reid Spencer5f016e22007-07-11 17:01:13 +00002242 for (unsigned i = 0, e = InputFilenames.size(); i != e; ++i) {
Ted Kremenek31e703b2007-12-11 23:28:38 +00002243 const std::string &InFile = InputFilenames[i];
Ted Kremenek31e703b2007-12-11 23:28:38 +00002244
Chris Lattnerf63aea32009-03-04 21:40:56 +00002245 /// Create a SourceManager object. This tracks and owns all the file
2246 /// buffers allocated to a translation unit.
2247 if (!SourceMgr)
2248 SourceMgr.reset(new SourceManager());
2249 else
2250 SourceMgr->clearIDTables();
2251
2252 // Initialize language options, inferring file types from input filenames.
2253 LangOptions LangInfo;
Chris Lattner409d4e72009-04-17 20:40:01 +00002254 DiagClient->setLangOptions(&LangInfo);
Chris Lattner2c78b872009-04-14 23:22:57 +00002255
Chris Lattnerf63aea32009-03-04 21:40:56 +00002256 InitializeBaseLanguage();
2257 LangKind LK = GetLanguage(InFile);
Daniel Dunbar0b5b0da2009-04-01 05:09:09 +00002258 InitializeLangOptions(LangInfo, LK);
Daniel Dunbar868bd0a2009-05-06 03:16:41 +00002259 InitializeLanguageStandard(LangInfo, LK, Target.get(), Features);
Chris Lattnerf63aea32009-03-04 21:40:56 +00002260
2261 // Process the -I options and set them in the HeaderInfo.
2262 HeaderSearch HeaderInfo(FileMgr);
2263
Chris Lattner2c78b872009-04-14 23:22:57 +00002264
Chris Lattnerf63aea32009-03-04 21:40:56 +00002265 InitializeIncludePaths(argv[0], HeaderInfo, FileMgr, LangInfo);
2266
2267 // Set up the preprocessor with these options.
Eli Friedmanf086e3b2009-05-18 07:39:39 +00002268 DriverPreprocessorFactory PPFactory(Diags, LangInfo, *Target,
Chris Lattnerf63aea32009-03-04 21:40:56 +00002269 *SourceMgr.get(), HeaderInfo);
2270
2271 llvm::OwningPtr<Preprocessor> PP(PPFactory.CreatePreprocessor());
2272
2273 if (!PP)
2274 continue;
Ted Kremenekb4398aa2008-08-07 17:49:57 +00002275
Eli Friedmanb5c8f8b2009-05-19 03:35:57 +00002276 // Handle generating dependencies, if requested
2277 if (!DependencyFile.empty()) {
2278 llvm::raw_ostream *DependencyOS;
2279 if (DependencyTargets.empty()) {
2280 // FIXME: Use a proper diagnostic
2281 llvm::cerr << "-dependency-file requires at least one -MT option\n";
2282 HadErrors = true;
2283 continue;
2284 }
2285 std::string ErrStr;
2286 DependencyOS =
Dan Gohman92db2842009-07-15 17:32:18 +00002287 new llvm::raw_fd_ostream(DependencyFile.c_str(), false,
2288 /*Force=*/true, ErrStr);
Eli Friedmanb5c8f8b2009-05-19 03:35:57 +00002289 if (!ErrStr.empty()) {
2290 // FIXME: Use a proper diagnostic
2291 llvm::cerr << "unable to open dependency file: " + ErrStr;
2292 HadErrors = true;
2293 continue;
2294 }
2295
2296 AttachDependencyFileGen(PP.get(), DependencyOS, DependencyTargets,
2297 DependenciesIncludeSystemHeaders,
2298 PhonyDependencyTarget);
2299 }
2300
Chris Lattner1b63e4f2009-06-14 01:54:56 +00002301 if (ImplicitIncludePCH.empty()) {
2302 if (InitializeSourceManager(*PP.get(), InFile))
2303 continue;
2304
2305 // Initialize builtin info.
2306 PP->getBuiltinInfo().InitializeBuiltins(PP->getIdentifierTable(),
Chris Lattner1b63e4f2009-06-14 01:54:56 +00002307 PP->getLangOptions().NoBuiltin);
2308 }
Douglas Gregor14f79002009-04-10 03:52:48 +00002309
Chris Lattner409d4e72009-04-17 20:40:01 +00002310 if (!HTMLDiag.empty())
2311 ((PathDiagnosticClient*)DiagClient.get())->SetPreprocessor(PP.get());
Chris Lattnerf63aea32009-03-04 21:40:56 +00002312
2313 // Process the source file.
Owen Andersonc93f4982009-07-01 21:23:16 +00002314 ProcessInputFile(*PP, PPFactory, InFile, ProgAction, Features, Context);
Chris Lattnerf63aea32009-03-04 21:40:56 +00002315
Chris Lattner40469652009-04-17 20:16:08 +00002316 HeaderInfo.ClearFileInfo();
Chris Lattner409d4e72009-04-17 20:40:01 +00002317 DiagClient->setLangOptions(0);
Reid Spencer5f016e22007-07-11 17:01:13 +00002318 }
Chris Lattner11215192008-03-14 06:12:05 +00002319
Mike Stumpfc0fed32009-04-28 01:19:10 +00002320 if (!NoCaretDiagnostics)
2321 if (unsigned NumDiagnostics = Diags.getNumDiagnostics())
2322 fprintf(stderr, "%d diagnostic%s generated.\n", NumDiagnostics,
2323 (NumDiagnostics == 1 ? "" : "s"));
Reid Spencer5f016e22007-07-11 17:01:13 +00002324
2325 if (Stats) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002326 FileMgr.PrintStats();
2327 fprintf(stderr, "\n");
2328 }
Chris Lattner75a97cb2009-04-17 21:05:01 +00002329
2330 delete ClangFrontendTimer;
2331 delete BuildLogFile;
Reid Spencer5f016e22007-07-11 17:01:13 +00002332
Daniel Dunbar276373d2008-10-27 22:10:13 +00002333 // If verifying diagnostics and we reached here, all is well.
2334 if (VerifyDiagnostics)
2335 return 0;
Chris Lattner47099742009-02-18 01:51:21 +00002336
Daniel Dunbar524b86f2008-10-28 00:38:08 +00002337 // Managed static deconstruction. Useful for making things like
2338 // -time-passes usable.
2339 llvm::llvm_shutdown();
2340
Daniel Dunbarb0adbba2008-10-04 23:42:49 +00002341 return HadErrors || (Diags.getNumErrors() != 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00002342}