blob: f7fe7ac8ccd1eaddb46f1b42b29ca3f6ce5da661 [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 Dunbaraca2ebd2009-09-17 00:48:13 +000027#include "clang/Frontend/ASTUnit.h"
Daniel Dunbare1bd4e62009-03-02 06:16:29 +000028#include "clang/Frontend/CompileOptions.h"
Daniel Dunbareace8742009-11-04 06:24:30 +000029#include "clang/Frontend/DiagnosticOptions.h"
Douglas Gregor558cb562009-04-02 01:08:08 +000030#include "clang/Frontend/FixItRewriter.h"
Daniel Dunbar50f4f462009-03-12 10:14:16 +000031#include "clang/Frontend/FrontendDiagnostic.h"
Daniel Dunbardd35ce92009-11-07 04:58:12 +000032#include "clang/Frontend/HeaderSearchOptions.h"
Daniel Dunbare1bd4e62009-03-02 06:16:29 +000033#include "clang/Frontend/InitHeaderSearch.h"
Douglas Gregor2cf26342009-04-09 22:27:44 +000034#include "clang/Frontend/PCHReader.h"
Daniel Dunbar8863b982009-11-07 04:20:15 +000035#include "clang/Frontend/PathDiagnosticClients.h"
36#include "clang/Frontend/PreprocessorOptions.h"
Daniel Dunbare1bd4e62009-03-02 06:16:29 +000037#include "clang/Frontend/TextDiagnosticBuffer.h"
38#include "clang/Frontend/TextDiagnosticPrinter.h"
Argyrios Kyrtzidis34d25d82009-06-23 22:01:39 +000039#include "clang/Frontend/CommandLineSourceLoc.h"
Eli Friedmanb09f6e12009-05-19 04:14:29 +000040#include "clang/Frontend/Utils.h"
Ted Kremenek88f5cde2008-03-27 06:17:42 +000041#include "clang/Analysis/PathDiagnostic.h"
Chris Lattner8ee3c032008-02-06 02:01:47 +000042#include "clang/CodeGen/ModuleBuilder.h"
Douglas Gregor81b747b2009-09-17 21:32:03 +000043#include "clang/Sema/CodeCompleteConsumer.h"
Chris Lattnere91c1342008-02-06 00:23:21 +000044#include "clang/Sema/ParseAST.h"
Chris Lattner88eccaf2009-01-29 06:55:46 +000045#include "clang/Sema/SemaDiagnostic.h"
Chris Lattner556beb72007-09-15 22:56:56 +000046#include "clang/AST/ASTConsumer.h"
Chris Lattner1266eca2009-03-28 04:31:31 +000047#include "clang/AST/ASTContext.h"
48#include "clang/AST/Decl.h"
Chris Lattner682bf922009-03-29 16:50:03 +000049#include "clang/AST/DeclGroup.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000050#include "clang/Parse/Parser.h"
51#include "clang/Lex/HeaderSearch.h"
Chris Lattnerdb766842009-02-06 04:16:41 +000052#include "clang/Lex/LexDiagnostic.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000053#include "clang/Basic/FileManager.h"
54#include "clang/Basic/SourceManager.h"
55#include "clang/Basic/TargetInfo.h"
Daniel Dunbaraa338bc2009-05-06 04:07:06 +000056#include "clang/Basic/Version.h"
Owen Anderson42253cc2009-07-01 17:00:06 +000057#include "llvm/LLVMContext.h"
Chris Lattnerba0f25f2008-09-30 20:16:56 +000058#include "llvm/ADT/OwningPtr.h"
Chris Lattner8f3dab82007-12-15 23:20:07 +000059#include "llvm/ADT/SmallPtrSet.h"
Chris Lattnerba0f25f2008-09-30 20:16:56 +000060#include "llvm/ADT/StringExtras.h"
Daniel Dunbar868bd0a2009-05-06 03:16:41 +000061#include "llvm/ADT/StringMap.h"
Chris Lattnerb8e240e2009-04-08 18:24:34 +000062#include "llvm/ADT/STLExtras.h"
Chris Lattnerba0f25f2008-09-30 20:16:56 +000063#include "llvm/Config/config.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000064#include "llvm/Support/CommandLine.h"
Daniel Dunbar70121eb2009-08-10 03:40:28 +000065#include "llvm/Support/ErrorHandling.h"
Daniel Dunbar524b86f2008-10-28 00:38:08 +000066#include "llvm/Support/ManagedStatic.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000067#include "llvm/Support/MemoryBuffer.h"
Zhongxing Xu20922362008-11-26 05:23:17 +000068#include "llvm/Support/PluginLoader.h"
Chris Lattner09e94a32009-03-04 21:41:39 +000069#include "llvm/Support/PrettyStackTrace.h"
Chris Lattner47099742009-02-18 01:51:21 +000070#include "llvm/Support/Timer.h"
Chris Lattner0fa0daa2009-08-24 04:11:30 +000071#include "llvm/Support/raw_ostream.h"
Daniel Dunbare553a722008-10-02 01:21:33 +000072#include "llvm/System/Host.h"
Chris Lattnerdcaa0962008-03-03 03:16:03 +000073#include "llvm/System/Path.h"
Eli Friedman66d6f042009-05-18 22:20:00 +000074#include "llvm/System/Program.h"
Chris Lattnerba0f25f2008-09-30 20:16:56 +000075#include "llvm/System/Signals.h"
Chris Lattner2fe11942009-06-17 17:25:50 +000076#include "llvm/Target/TargetSelect.h"
Douglas Gregor26df2f02009-04-02 19:05:20 +000077#include <cstdlib>
Douglas Gregor44cf08e2009-05-03 03:52:38 +000078#if HAVE_SYS_TYPES_H
Douglas Gregor68a0d782009-05-02 00:03:46 +000079# include <sys/types.h>
80#endif
Douglas Gregor26df2f02009-04-02 19:05:20 +000081
Reid Spencer5f016e22007-07-11 17:01:13 +000082using namespace clang;
83
84//===----------------------------------------------------------------------===//
Douglas Gregor26df2f02009-04-02 19:05:20 +000085// Source Location Parser
86//===----------------------------------------------------------------------===//
87
Argyrios Kyrtzidis34d25d82009-06-23 22:01:39 +000088static bool ResolveParsedLocation(ParsedSourceLocation &ParsedLoc,
89 FileManager &FileMgr,
90 RequestedSourceLocation &Result) {
91 const FileEntry *File = FileMgr.getFile(ParsedLoc.FileName);
Douglas Gregor26df2f02009-04-02 19:05:20 +000092 if (!File)
93 return true;
94
95 Result.File = File;
Argyrios Kyrtzidis34d25d82009-06-23 22:01:39 +000096 Result.Line = ParsedLoc.Line;
97 Result.Column = ParsedLoc.Column;
Douglas Gregor26df2f02009-04-02 19:05:20 +000098 return false;
99}
100
Douglas Gregor26df2f02009-04-02 19:05:20 +0000101//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +0000102// Global options.
103//===----------------------------------------------------------------------===//
104
Chris Lattner47099742009-02-18 01:51:21 +0000105/// ClangFrontendTimer - The front-end activities should charge time to it with
106/// TimeRegion. The -ftime-report option controls whether this will do
107/// anything.
108llvm::Timer *ClangFrontendTimer = 0;
109
Reid Spencer5f016e22007-07-11 17:01:13 +0000110static llvm::cl::opt<bool>
111Verbose("v", llvm::cl::desc("Enable verbose output"));
112static llvm::cl::opt<bool>
Mike Stump1eb44332009-09-09 15:08:12 +0000113Stats("print-stats",
Nate Begemanaabbb122007-12-30 01:38:50 +0000114 llvm::cl::desc("Print performance metrics and statistics"));
Daniel Dunbard3db4012008-10-16 16:54:18 +0000115static llvm::cl::opt<bool>
116DisableFree("disable-free",
117 llvm::cl::desc("Disable freeing of memory on exit"),
118 llvm::cl::init(false));
Daniel Dunbar57cbfc02009-04-27 21:19:07 +0000119static llvm::cl::opt<bool>
Mike Stump1eb44332009-09-09 15:08:12 +0000120EmptyInputOnly("empty-input-only",
Daniel Dunbar57cbfc02009-04-27 21:19:07 +0000121 llvm::cl::desc("Force running on an empty input file"));
Reid Spencer5f016e22007-07-11 17:01:13 +0000122
123enum ProgActions {
Steve Naroffb29b4272008-04-14 22:03:09 +0000124 RewriteObjC, // ObjC->C Rewriter.
Steve Naroff13188952008-09-18 14:10:13 +0000125 RewriteBlocks, // ObjC->C Rewriter for Blocks.
Chris Lattnerb57e3d42008-05-08 06:52:13 +0000126 RewriteMacros, // Expand macros but not #includes.
Chris Lattnerb13c5ee2008-10-12 05:29:20 +0000127 RewriteTest, // Rewriter playground
Douglas Gregor558cb562009-04-02 01:08:08 +0000128 FixIt, // Fix-It Rewriter
Ted Kremenek13e479b2008-03-19 07:53:42 +0000129 HTMLTest, // HTML displayer testing stuff.
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000130 EmitAssembly, // Emit a .s file.
Reid Spencer5f016e22007-07-11 17:01:13 +0000131 EmitLLVM, // Emit a .ll file.
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +0000132 EmitBC, // Emit a .bc file.
Mike Stump1eb44332009-09-09 15:08:12 +0000133 EmitLLVMOnly, // Generate LLVM IR, but do not
Ted Kremenek6a340832008-03-18 21:19:49 +0000134 EmitHTML, // Translate input source into HTML.
Chris Lattner3b427b32007-10-11 00:18:28 +0000135 ASTPrint, // Parse ASTs and print them.
Douglas Gregoree75c052009-05-21 20:55:50 +0000136 ASTPrintXML, // Parse ASTs and print them in XML.
Chris Lattner3b427b32007-10-11 00:18:28 +0000137 ASTDump, // Parse ASTs and dump them.
138 ASTView, // Parse ASTs and view them in Graphviz.
Zhongxing Xu2d75d6f2009-01-13 01:29:24 +0000139 PrintDeclContext, // Print DeclContext and their Decls.
Anders Carlsson78762eb2009-09-24 18:54:49 +0000140 DumpRecordLayouts, // Dump record layout information.
Reid Spencer5f016e22007-07-11 17:01:13 +0000141 ParsePrintCallbacks, // Parse and print each callback.
142 ParseSyntaxOnly, // Parse and perform semantic analysis.
143 ParseNoop, // Parse with noop callbacks.
144 RunPreprocessorOnly, // Just lex, no output.
145 PrintPreprocessedInput, // -E mode.
Chris Lattnerc106c102008-10-12 05:03:36 +0000146 DumpTokens, // Dump out preprocessed tokens.
147 DumpRawTokens, // Dump out raw tokens.
Mike Stump1eb44332009-09-09 15:08:12 +0000148 RunAnalysis, // Run one or more source code analyses.
Douglas Gregorbf1bd6e2009-04-02 23:43:50 +0000149 GeneratePTH, // Generate pre-tokenized header.
Douglas Gregor2cf26342009-04-09 22:27:44 +0000150 GeneratePCH, // Generate pre-compiled header.
Ted Kremenek7cae2f62008-10-23 23:36:29 +0000151 InheritanceView // View C++ inheritance for a specified class.
Reid Spencer5f016e22007-07-11 17:01:13 +0000152};
153
Mike Stump1eb44332009-09-09 15:08:12 +0000154static llvm::cl::opt<ProgActions>
Reid Spencer5f016e22007-07-11 17:01:13 +0000155ProgAction(llvm::cl::desc("Choose output type:"), llvm::cl::ZeroOrMore,
156 llvm::cl::init(ParseSyntaxOnly),
157 llvm::cl::values(
158 clEnumValN(RunPreprocessorOnly, "Eonly",
159 "Just run preprocessor, no output (for timings)"),
160 clEnumValN(PrintPreprocessedInput, "E",
161 "Run preprocessor, emit preprocessed file"),
Chris Lattnerc106c102008-10-12 05:03:36 +0000162 clEnumValN(DumpRawTokens, "dump-raw-tokens",
163 "Lex file in raw mode and dump raw tokens"),
Daniel Dunbard4270232009-01-20 23:17:32 +0000164 clEnumValN(RunAnalysis, "analyze",
165 "Run static analysis engine"),
Chris Lattnerc106c102008-10-12 05:03:36 +0000166 clEnumValN(DumpTokens, "dump-tokens",
Reid Spencer5f016e22007-07-11 17:01:13 +0000167 "Run preprocessor, dump internal rep of tokens"),
168 clEnumValN(ParseNoop, "parse-noop",
169 "Run parser with noop callbacks (for timings)"),
170 clEnumValN(ParseSyntaxOnly, "fsyntax-only",
171 "Run parser and perform semantic analysis"),
172 clEnumValN(ParsePrintCallbacks, "parse-print-callbacks",
173 "Run parser and print each callback invoked"),
Ted Kremenek6a340832008-03-18 21:19:49 +0000174 clEnumValN(EmitHTML, "emit-html",
175 "Output input source as HTML"),
Chris Lattner3b427b32007-10-11 00:18:28 +0000176 clEnumValN(ASTPrint, "ast-print",
177 "Build ASTs and then pretty-print them"),
Douglas Gregoree75c052009-05-21 20:55:50 +0000178 clEnumValN(ASTPrintXML, "ast-print-xml",
179 "Build ASTs and then print them in XML format"),
Chris Lattner3b427b32007-10-11 00:18:28 +0000180 clEnumValN(ASTDump, "ast-dump",
181 "Build ASTs and then debug dump them"),
Chris Lattnerea254db2007-10-11 00:37:43 +0000182 clEnumValN(ASTView, "ast-view",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000183 "Build ASTs and view them with GraphViz"),
Zhongxing Xu2d75d6f2009-01-13 01:29:24 +0000184 clEnumValN(PrintDeclContext, "print-decl-contexts",
Ted Kremenek08478eb2009-04-01 00:23:28 +0000185 "Print DeclContexts and their Decls"),
Anders Carlsson78762eb2009-09-24 18:54:49 +0000186 clEnumValN(DumpRecordLayouts, "dump-record-layouts",
187 "Dump record layout information"),
Douglas Gregorbf1bd6e2009-04-02 23:43:50 +0000188 clEnumValN(GeneratePTH, "emit-pth",
Ted Kremenek08478eb2009-04-01 00:23:28 +0000189 "Generate pre-tokenized header file"),
Douglas Gregor2cf26342009-04-09 22:27:44 +0000190 clEnumValN(GeneratePCH, "emit-pch",
191 "Generate pre-compiled header file"),
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000192 clEnumValN(EmitAssembly, "S",
193 "Emit native assembly code"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000194 clEnumValN(EmitLLVM, "emit-llvm",
Ted Kremenek27b07c52007-09-06 21:26:58 +0000195 "Build ASTs then convert to LLVM, emit .ll file"),
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +0000196 clEnumValN(EmitBC, "emit-llvm-bc",
197 "Build ASTs then convert to LLVM, emit .bc file"),
Daniel Dunbare8e26002009-02-26 22:39:37 +0000198 clEnumValN(EmitLLVMOnly, "emit-llvm-only",
199 "Build ASTs and convert to LLVM, discarding output"),
Chris Lattnerb13c5ee2008-10-12 05:29:20 +0000200 clEnumValN(RewriteTest, "rewrite-test",
201 "Rewriter playground"),
Steve Naroffb29b4272008-04-14 22:03:09 +0000202 clEnumValN(RewriteObjC, "rewrite-objc",
Chris Lattnerb57e3d42008-05-08 06:52:13 +0000203 "Rewrite ObjC into C (code rewriter example)"),
204 clEnumValN(RewriteMacros, "rewrite-macros",
205 "Expand macros without full preprocessing"),
Steve Naroff13188952008-09-18 14:10:13 +0000206 clEnumValN(RewriteBlocks, "rewrite-blocks",
207 "Rewrite Blocks to C"),
Douglas Gregor558cb562009-04-02 01:08:08 +0000208 clEnumValN(FixIt, "fixit",
209 "Apply fix-it advice to the input source"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000210 clEnumValEnd));
211
Ted Kremenekccc76472007-12-19 19:47:59 +0000212
213static llvm::cl::opt<std::string>
214OutputFile("o",
Ted Kremenek50b56412007-12-19 19:50:41 +0000215 llvm::cl::value_desc("path"),
Douglas Gregor370187c2009-04-22 21:45:53 +0000216 llvm::cl::desc("Specify output file"));
Ted Kremenek55af98c2008-04-14 18:40:58 +0000217
Ted Kremenekc2e72992008-12-02 19:57:31 +0000218
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000219enum CodeCompletionPrinter {
220 CCP_Debug,
221 CCP_CIndex
222};
223
Douglas Gregorb657f112009-09-22 21:11:38 +0000224static llvm::cl::opt<ParsedSourceLocation>
225CodeCompletionAt("code-completion-at",
226 llvm::cl::value_desc("file:line:column"),
227 llvm::cl::desc("Dump code-completion information at a location"));
Douglas Gregor81b747b2009-09-17 21:32:03 +0000228
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000229static llvm::cl::opt<CodeCompletionPrinter>
230CodeCompletionPrinter("code-completion-printer",
231 llvm::cl::desc("Choose output type:"),
232 llvm::cl::init(CCP_Debug),
233 llvm::cl::values(
234 clEnumValN(CCP_Debug, "debug",
235 "Debug code-completion results"),
236 clEnumValN(CCP_CIndex, "cindex",
237 "Code-completion results for the CIndex library"),
238 clEnumValEnd));
239
240static llvm::cl::opt<bool>
241CodeCompletionWantsMacros("code-completion-macros",
242 llvm::cl::desc("Include macros in code-completion results"));
243
Douglas Gregor81b747b2009-09-17 21:32:03 +0000244/// \brief Buld a new code-completion consumer that prints the results of
245/// code completion to standard output.
246static CodeCompleteConsumer *BuildPrintingCodeCompleter(Sema &S, void *) {
Douglas Gregor0c8296d2009-11-07 00:00:49 +0000247 switch (CodeCompletionPrinter.getValue()) {
248 case CCP_Debug:
249 return new PrintingCodeCompleteConsumer(S, CodeCompletionWantsMacros,
250 llvm::outs());
251
252 case CCP_CIndex:
253 return new CIndexCodeCompleteConsumer(S, CodeCompletionWantsMacros,
254 llvm::outs());
255 };
256
257 return 0;
Douglas Gregor81b747b2009-09-17 21:32:03 +0000258}
259
Ted Kremenekc2e72992008-12-02 19:57:31 +0000260//===----------------------------------------------------------------------===//
261// PTH.
262//===----------------------------------------------------------------------===//
263
264static llvm::cl::opt<std::string>
265TokenCache("token-cache", llvm::cl::value_desc("path"),
266 llvm::cl::desc("Use specified token cache file"));
267
Sanjiv Guptae8b9f5b2008-05-08 08:54:20 +0000268//===----------------------------------------------------------------------===//
Ted Kremenek55af98c2008-04-14 18:40:58 +0000269// Diagnostic Options
270//===----------------------------------------------------------------------===//
271
Daniel Dunbareace8742009-11-04 06:24:30 +0000272static DiagnosticOptions DiagOpts;
273
Ted Kremenek41193e42007-09-26 19:42:19 +0000274static llvm::cl::opt<bool>
275VerifyDiagnostics("verify",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000276 llvm::cl::desc("Verify emitted diagnostics and warnings"));
Ted Kremenek41193e42007-09-26 19:42:19 +0000277
Nico Weberfd54ebc2008-08-05 23:33:20 +0000278static llvm::cl::opt<bool>
279NoShowColumn("fno-show-column",
280 llvm::cl::desc("Do not include column number on diagnostics"));
281
282static llvm::cl::opt<bool>
Chris Lattner65f5e642009-01-30 19:01:41 +0000283NoShowLocation("fno-show-source-location",
284 llvm::cl::desc("Do not include source location information with"
285 " diagnostics"));
286
287static llvm::cl::opt<bool>
Nico Weberfd54ebc2008-08-05 23:33:20 +0000288NoCaretDiagnostics("fno-caret-diagnostics",
289 llvm::cl::desc("Do not include source line and caret with"
290 " diagnostics"));
291
Chris Lattner1fbee5d2009-03-13 01:08:23 +0000292static llvm::cl::opt<bool>
Chris Lattneraa5bf2e2009-04-19 07:44:08 +0000293NoDiagnosticsFixIt("fno-diagnostics-fixit-info",
294 llvm::cl::desc("Do not include fixit information in"
295 " diagnostics"));
296
297static llvm::cl::opt<bool>
Chris Lattner182e0922009-04-21 05:34:31 +0000298PrintSourceRangeInfo("fdiagnostics-print-source-range-info",
299 llvm::cl::desc("Print source range spans in numeric form"));
300
Chris Lattnerd51d74a2009-04-16 05:44:38 +0000301static llvm::cl::opt<bool>
302PrintDiagnosticOption("fdiagnostics-show-option",
303 llvm::cl::desc("Print diagnostic name with mappable diagnostics"));
Nico Weberfd54ebc2008-08-05 23:33:20 +0000304
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000305static llvm::cl::opt<unsigned>
306MessageLength("fmessage-length",
Mike Stump1eb44332009-09-09 15:08:12 +0000307 llvm::cl::desc("Format message diagnostics so that they fit "
308 "within N columns or fewer, when possible."),
309 llvm::cl::value_desc("N"));
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000310
Torok Edwin603fca72009-06-04 07:18:23 +0000311static llvm::cl::opt<bool>
Daniel Dunbar838be482009-11-04 06:24:57 +0000312PrintColorDiagnostic("fcolor-diagnostics",
313 llvm::cl::desc("Use colors in diagnostics"));
314
Reid Spencer5f016e22007-07-11 17:01:13 +0000315//===----------------------------------------------------------------------===//
Ted Kremenek7cae2f62008-10-23 23:36:29 +0000316// C++ Visualization.
317//===----------------------------------------------------------------------===//
318
319static llvm::cl::opt<std::string>
320InheritanceViewCls("cxx-inheritance-view",
321 llvm::cl::value_desc("class name"),
Daniel Dunbard77b2512009-01-14 18:56:36 +0000322 llvm::cl::desc("View C++ inheritance for a specified class"));
Ted Kremenek7cae2f62008-10-23 23:36:29 +0000323
324//===----------------------------------------------------------------------===//
Douglas Gregor3573c0c2009-02-14 20:49:29 +0000325// Builtin Options
326//===----------------------------------------------------------------------===//
Chris Lattnerb2509e12009-02-18 01:12:43 +0000327
328static llvm::cl::opt<bool>
329TimeReport("ftime-report",
330 llvm::cl::desc("Print the amount of time each "
331 "phase of compilation takes"));
332
Douglas Gregor3573c0c2009-02-14 20:49:29 +0000333static llvm::cl::opt<bool>
334Freestanding("ffreestanding",
Daniel Dunbaref2abfe2009-02-16 22:43:43 +0000335 llvm::cl::desc("Assert that the compilation takes place in a "
Douglas Gregor3573c0c2009-02-14 20:49:29 +0000336 "freestanding environment"));
337
Daniel Dunbaref2abfe2009-02-16 22:43:43 +0000338static llvm::cl::opt<bool>
Daniel Dunbar48d1ef72009-04-07 21:16:11 +0000339AllowBuiltins("fbuiltin", llvm::cl::init(true),
340 llvm::cl::desc("Disable implicit builtin knowledge of functions"));
Chris Lattner7644f072009-03-13 22:38:49 +0000341
342
343static llvm::cl::opt<bool>
Daniel Dunbar48d1ef72009-04-07 21:16:11 +0000344MathErrno("fmath-errno", llvm::cl::init(true),
345 llvm::cl::desc("Require math functions to respect errno"));
Daniel Dunbaref2abfe2009-02-16 22:43:43 +0000346
Douglas Gregor3573c0c2009-02-14 20:49:29 +0000347//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +0000348// Language Options
349//===----------------------------------------------------------------------===//
350
351enum LangKind {
352 langkind_unspecified,
353 langkind_c,
354 langkind_c_cpp,
Chris Lattnera778d7d2008-10-22 17:29:21 +0000355 langkind_asm_cpp,
Reid Spencer5f016e22007-07-11 17:01:13 +0000356 langkind_cxx,
357 langkind_cxx_cpp,
358 langkind_objc,
359 langkind_objc_cpp,
360 langkind_objcxx,
Nate Begeman4e3629e2009-06-25 22:43:10 +0000361 langkind_objcxx_cpp,
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +0000362 langkind_ocl,
363 langkind_ast
Reid Spencer5f016e22007-07-11 17:01:13 +0000364};
365
Reid Spencer5f016e22007-07-11 17:01:13 +0000366static llvm::cl::opt<LangKind>
367BaseLang("x", llvm::cl::desc("Base language to compile"),
368 llvm::cl::init(langkind_unspecified),
369 llvm::cl::values(clEnumValN(langkind_c, "c", "C"),
Nate Begeman4e3629e2009-06-25 22:43:10 +0000370 clEnumValN(langkind_ocl, "cl", "OpenCL C"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000371 clEnumValN(langkind_cxx, "c++", "C++"),
372 clEnumValN(langkind_objc, "objective-c", "Objective C"),
373 clEnumValN(langkind_objcxx,"objective-c++","Objective C++"),
Daniel Dunbard2ea3862009-01-29 23:50:47 +0000374 clEnumValN(langkind_c_cpp, "cpp-output",
Reid Spencer5f016e22007-07-11 17:01:13 +0000375 "Preprocessed C"),
Chris Lattnera778d7d2008-10-22 17:29:21 +0000376 clEnumValN(langkind_asm_cpp, "assembler-with-cpp",
377 "Preprocessed asm"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000378 clEnumValN(langkind_cxx_cpp, "c++-cpp-output",
Chris Lattnerc76d8072009-02-06 06:19:20 +0000379 "Preprocessed C++"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000380 clEnumValN(langkind_objc_cpp, "objective-c-cpp-output",
381 "Preprocessed Objective C"),
Chris Lattnerc76d8072009-02-06 06:19:20 +0000382 clEnumValN(langkind_objcxx_cpp, "objective-c++-cpp-output",
Reid Spencer5f016e22007-07-11 17:01:13 +0000383 "Preprocessed Objective C++"),
Daniel Dunbar0b5b0da2009-04-01 05:09:09 +0000384 clEnumValN(langkind_c, "c-header",
385 "C header"),
386 clEnumValN(langkind_objc, "objective-c-header",
387 "Objective-C header"),
388 clEnumValN(langkind_cxx, "c++-header",
389 "C++ header"),
390 clEnumValN(langkind_objcxx, "objective-c++-header",
391 "Objective-C++ header"),
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +0000392 clEnumValN(langkind_ast, "ast",
393 "Clang AST"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000394 clEnumValEnd));
395
396static llvm::cl::opt<bool>
Chris Lattner2c78b872009-04-14 23:22:57 +0000397ObjCExclusiveGC("fobjc-gc-only",
398 llvm::cl::desc("Use GC exclusively for Objective-C related "
399 "memory management"));
400
David Chisnall8a5a9aa2009-08-31 16:41:57 +0000401static llvm::cl::opt<std::string>
402ObjCConstantStringClass("fconstant-string-class",
403 llvm::cl::value_desc("class name"),
404 llvm::cl::desc("Specify the class to use for constant "
405 "Objective-C string objects."));
406
Chris Lattner2c78b872009-04-14 23:22:57 +0000407static llvm::cl::opt<bool>
408ObjCEnableGC("fobjc-gc",
409 llvm::cl::desc("Enable Objective-C garbage collection"));
410
Fariborz Jahanian448f5e62009-04-17 03:04:15 +0000411static llvm::cl::opt<bool>
412ObjCEnableGCBitmapPrint("print-ivar-layout",
413 llvm::cl::desc("Enable Objective-C Ivar layout bitmap print trace"));
414
Chris Lattner2c78b872009-04-14 23:22:57 +0000415static llvm::cl::opt<LangOptions::VisibilityMode>
416SymbolVisibility("fvisibility",
417 llvm::cl::desc("Set the default symbol visibility:"),
418 llvm::cl::init(LangOptions::Default),
419 llvm::cl::values(clEnumValN(LangOptions::Default, "default",
420 "Use default symbol visibility"),
421 clEnumValN(LangOptions::Hidden, "hidden",
422 "Use hidden symbol visibility"),
423 clEnumValN(LangOptions::Protected,"protected",
424 "Use protected symbol visibility"),
425 clEnumValEnd));
426
427static llvm::cl::opt<bool>
428OverflowChecking("ftrapv",
429 llvm::cl::desc("Trap on integer overflow"),
430 llvm::cl::init(false));
431
Fariborz Jahanian34e65772009-05-22 20:17:16 +0000432static llvm::cl::opt<bool>
Nate Begeman2ef13e52009-08-10 23:49:36 +0000433AltiVec("faltivec", llvm::cl::desc("Enable AltiVec vector initializer syntax"),
434 llvm::cl::init(false));
435
436static llvm::cl::opt<bool>
Daniel Dunbar5345c392009-09-03 04:54:28 +0000437PThread("pthread", llvm::cl::desc("Support POSIX threads in generated code"),
438 llvm::cl::init(false));
439
Daniel Dunbar13fdf282009-09-17 00:47:46 +0000440static LangKind GetLanguage(llvm::StringRef Filename) {
Ted Kremenek8904f152007-12-05 23:49:08 +0000441 if (BaseLang != langkind_unspecified)
442 return BaseLang;
Mike Stump1eb44332009-09-09 15:08:12 +0000443
Daniel Dunbar13fdf282009-09-17 00:47:46 +0000444 llvm::StringRef Ext = Filename.rsplit('.').second;
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +0000445 if (Ext == "ast")
446 return langkind_ast;
447 else if (Ext == "c")
Ted Kremenek8904f152007-12-05 23:49:08 +0000448 return langkind_c;
Daniel Dunbar9f435342009-09-17 00:47:27 +0000449 else if (Ext == "S" || Ext == "s")
Chris Lattnera778d7d2008-10-22 17:29:21 +0000450 return langkind_asm_cpp;
Ted Kremenek8904f152007-12-05 23:49:08 +0000451 else if (Ext == "i")
452 return langkind_c_cpp;
453 else if (Ext == "ii")
454 return langkind_cxx_cpp;
455 else if (Ext == "m")
456 return langkind_objc;
457 else if (Ext == "mi")
458 return langkind_objc_cpp;
459 else if (Ext == "mm" || Ext == "M")
460 return langkind_objcxx;
461 else if (Ext == "mii")
462 return langkind_objcxx_cpp;
463 else if (Ext == "C" || Ext == "cc" || Ext == "cpp" || Ext == "CPP" ||
464 Ext == "c++" || Ext == "cp" || Ext == "cxx")
465 return langkind_cxx;
Nate Begeman4e3629e2009-06-25 22:43:10 +0000466 else if (Ext == "cl")
467 return langkind_ocl;
Ted Kremenek8904f152007-12-05 23:49:08 +0000468 else
469 return langkind_c;
470}
471
472
Ted Kremenek85888962008-10-21 00:54:44 +0000473static void InitializeCOptions(LangOptions &Options) {
474 // Do nothing.
475}
476
477static void InitializeObjCOptions(LangOptions &Options) {
478 Options.ObjC1 = Options.ObjC2 = 1;
479}
Mike Stump1eb44332009-09-09 15:08:12 +0000480
Ted Kremenek85888962008-10-21 00:54:44 +0000481
Daniel Dunbar0b5b0da2009-04-01 05:09:09 +0000482static void InitializeLangOptions(LangOptions &Options, LangKind LK){
Reid Spencer5f016e22007-07-11 17:01:13 +0000483 // FIXME: implement -fpreprocessed mode.
484 bool NoPreprocess = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000485
Ted Kremenek8904f152007-12-05 23:49:08 +0000486 switch (LK) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000487 default: assert(0 && "Unknown language kind!");
Chris Lattnera778d7d2008-10-22 17:29:21 +0000488 case langkind_asm_cpp:
Daniel Dunbarc1571452008-12-01 18:55:22 +0000489 Options.AsmPreprocessor = 1;
Chris Lattnera778d7d2008-10-22 17:29:21 +0000490 // FALLTHROUGH
Reid Spencer5f016e22007-07-11 17:01:13 +0000491 case langkind_c_cpp:
492 NoPreprocess = true;
493 // FALLTHROUGH
494 case langkind_c:
Ted Kremenek85888962008-10-21 00:54:44 +0000495 InitializeCOptions(Options);
Reid Spencer5f016e22007-07-11 17:01:13 +0000496 break;
497 case langkind_cxx_cpp:
498 NoPreprocess = true;
499 // FALLTHROUGH
500 case langkind_cxx:
501 Options.CPlusPlus = 1;
502 break;
503 case langkind_objc_cpp:
504 NoPreprocess = true;
505 // FALLTHROUGH
506 case langkind_objc:
Ted Kremenek85888962008-10-21 00:54:44 +0000507 InitializeObjCOptions(Options);
Reid Spencer5f016e22007-07-11 17:01:13 +0000508 break;
509 case langkind_objcxx_cpp:
510 NoPreprocess = true;
511 // FALLTHROUGH
512 case langkind_objcxx:
513 Options.ObjC1 = Options.ObjC2 = 1;
514 Options.CPlusPlus = 1;
515 break;
Nate Begeman4e3629e2009-06-25 22:43:10 +0000516 case langkind_ocl:
517 Options.OpenCL = 1;
518 Options.AltiVec = 1;
519 Options.CXXOperatorNames = 1;
520 Options.LaxVectorConversions = 1;
521 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000522 }
Mike Stump1eb44332009-09-09 15:08:12 +0000523
Chris Lattner2c78b872009-04-14 23:22:57 +0000524 if (ObjCExclusiveGC)
525 Options.setGCMode(LangOptions::GCOnly);
526 else if (ObjCEnableGC)
527 Options.setGCMode(LangOptions::HybridGC);
Mike Stump1eb44332009-09-09 15:08:12 +0000528
Fariborz Jahanian448f5e62009-04-17 03:04:15 +0000529 if (ObjCEnableGCBitmapPrint)
530 Options.ObjCGCBitmapPrint = 1;
Mike Stump1eb44332009-09-09 15:08:12 +0000531
Nate Begeman2ef13e52009-08-10 23:49:36 +0000532 if (AltiVec)
533 Options.AltiVec = 1;
Daniel Dunbar5345c392009-09-03 04:54:28 +0000534
535 if (PThread)
536 Options.POSIXThreads = 1;
Mike Stump1eb44332009-09-09 15:08:12 +0000537
Chris Lattner2c78b872009-04-14 23:22:57 +0000538 Options.setVisibilityMode(SymbolVisibility);
539 Options.OverflowChecking = OverflowChecking;
Reid Spencer5f016e22007-07-11 17:01:13 +0000540}
541
542/// LangStds - Language standards we support.
543enum LangStds {
Mike Stump1eb44332009-09-09 15:08:12 +0000544 lang_unspecified,
Reid Spencer5f016e22007-07-11 17:01:13 +0000545 lang_c89, lang_c94, lang_c99,
Douglas Gregor214904e2009-09-29 14:42:43 +0000546 lang_gnu89, lang_gnu99,
Chris Lattnerd4b80f12007-07-16 04:18:29 +0000547 lang_cxx98, lang_gnucxx98,
548 lang_cxx0x, lang_gnucxx0x
Reid Spencer5f016e22007-07-11 17:01:13 +0000549};
550
551static llvm::cl::opt<LangStds>
552LangStd("std", llvm::cl::desc("Language standard to compile for"),
553 llvm::cl::init(lang_unspecified),
554 llvm::cl::values(clEnumValN(lang_c89, "c89", "ISO C 1990"),
555 clEnumValN(lang_c89, "c90", "ISO C 1990"),
556 clEnumValN(lang_c89, "iso9899:1990", "ISO C 1990"),
557 clEnumValN(lang_c94, "iso9899:199409",
558 "ISO C 1990 with amendment 1"),
559 clEnumValN(lang_c99, "c99", "ISO C 1999"),
Chris Lattner50748f42009-04-06 17:17:55 +0000560 clEnumValN(lang_c99, "c9x", "ISO C 1999"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000561 clEnumValN(lang_c99, "iso9899:1999", "ISO C 1999"),
Chris Lattner50748f42009-04-06 17:17:55 +0000562 clEnumValN(lang_c99, "iso9899:199x", "ISO C 1999"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000563 clEnumValN(lang_gnu89, "gnu89",
Gabor Greif10b26142009-02-28 09:22:15 +0000564 "ISO C 1990 with GNU extensions"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000565 clEnumValN(lang_gnu99, "gnu99",
Gabor Greif10b26142009-02-28 09:22:15 +0000566 "ISO C 1999 with GNU extensions (default for C)"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000567 clEnumValN(lang_gnu99, "gnu9x",
568 "ISO C 1999 with GNU extensions"),
569 clEnumValN(lang_cxx98, "c++98",
570 "ISO C++ 1998 with amendments"),
571 clEnumValN(lang_gnucxx98, "gnu++98",
572 "ISO C++ 1998 with amendments and GNU "
573 "extensions (default for C++)"),
Chris Lattnerd4b80f12007-07-16 04:18:29 +0000574 clEnumValN(lang_cxx0x, "c++0x",
575 "Upcoming ISO C++ 200x with amendments"),
576 clEnumValN(lang_gnucxx0x, "gnu++0x",
577 "Upcoming ISO C++ 200x with amendments and GNU "
Gabor Greif5f8d1db2009-03-11 23:07:18 +0000578 "extensions"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000579 clEnumValEnd));
580
581static llvm::cl::opt<bool>
582NoOperatorNames("fno-operator-names",
583 llvm::cl::desc("Do not treat C++ operator name keywords as "
584 "synonyms for operators"));
585
Anders Carlssonee98ac52007-10-15 02:50:23 +0000586static llvm::cl::opt<bool>
587PascalStrings("fpascal-strings",
588 llvm::cl::desc("Recognize and construct Pascal-style "
589 "string literals"));
Mike Stump1eb44332009-09-09 15:08:12 +0000590
Steve Naroffd62701b2008-02-07 03:50:06 +0000591static llvm::cl::opt<bool>
592MSExtensions("fms-extensions",
593 llvm::cl::desc("Accept some non-standard constructs used in "
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000594 "Microsoft header files "));
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000595
596static llvm::cl::opt<bool>
597WritableStrings("fwritable-strings",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000598 llvm::cl::desc("Store string literals as writable data"));
Anders Carlsson695dbb62007-11-30 04:21:22 +0000599
600static llvm::cl::opt<bool>
Anders Carlssonad53eff2009-01-30 23:26:40 +0000601NoLaxVectorConversions("fno-lax-vector-conversions",
Anders Carlssonb0f90cc2009-01-30 23:17:46 +0000602 llvm::cl::desc("Disallow implicit conversions between "
603 "vectors with a different number of "
604 "elements or different element types"));
Chris Lattnerae0ee032008-12-04 23:20:07 +0000605
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000606static llvm::cl::opt<bool>
Daniel Dunbar48d1ef72009-04-07 21:16:11 +0000607EnableBlocks("fblocks", llvm::cl::desc("enable the 'blocks' language feature"));
Mike Stumpa0f02aa2009-02-02 22:57:57 +0000608
609static llvm::cl::opt<bool>
Chris Lattner810f6d52009-03-13 17:38:01 +0000610EnableHeinousExtensions("fheinous-gnu-extensions",
611 llvm::cl::desc("enable GNU extensions that you really really shouldn't use"),
612 llvm::cl::ValueDisallowed, llvm::cl::Hidden);
613
614static llvm::cl::opt<bool>
Mike Stumpa0f02aa2009-02-02 22:57:57 +0000615ObjCNonFragileABI("fobjc-nonfragile-abi",
616 llvm::cl::desc("enable objective-c's nonfragile abi"));
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000617
Daniel Dunbard6884a02009-05-04 05:16:21 +0000618
619static llvm::cl::opt<bool>
Daniel Dunbard604c402009-02-04 21:19:06 +0000620EmitAllDecls("femit-all-decls",
621 llvm::cl::desc("Emit all declarations, even if unused"));
Ted Kremenek01d9dbf2008-04-29 04:37:03 +0000622
Daniel Dunbar6379a7a2008-08-11 17:36:14 +0000623static llvm::cl::opt<bool>
624Exceptions("fexceptions",
Chris Lattnerf5db8f82009-04-19 07:00:02 +0000625 llvm::cl::desc("Enable support for exception handling"));
Daniel Dunbar6379a7a2008-08-11 17:36:14 +0000626
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000627static llvm::cl::opt<bool>
Mike Stump738f8c22009-07-31 23:15:31 +0000628Rtti("frtti", llvm::cl::init(true),
629 llvm::cl::desc("Enable generation of rtti information"));
630
631static llvm::cl::opt<bool>
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000632GNURuntime("fgnu-runtime",
Ted Kremenek85888962008-10-21 00:54:44 +0000633 llvm::cl::desc("Generate output compatible with the standard GNU "
Chris Lattnerf5db8f82009-04-19 07:00:02 +0000634 "Objective-C runtime"));
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000635
636static llvm::cl::opt<bool>
637NeXTRuntime("fnext-runtime",
Ted Kremenek85888962008-10-21 00:54:44 +0000638 llvm::cl::desc("Generate output compatible with the NeXT "
Chris Lattnerf5db8f82009-04-19 07:00:02 +0000639 "runtime"));
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000640
Eli Friedmanc4757bd2009-06-05 07:12:17 +0000641static llvm::cl::opt<bool>
642CharIsSigned("fsigned-char",
643 llvm::cl::desc("Force char to be a signed/unsigned type"));
Ted Kremenekea644d82008-09-03 21:22:16 +0000644
John Thompsona6fda122009-11-05 20:14:16 +0000645static llvm::cl::opt<bool>
646ShortWChar("fshort-wchar",
647 llvm::cl::desc("Force wchar_t to be a short unsigned int"));
648
Ted Kremenekea644d82008-09-03 21:22:16 +0000649
650static llvm::cl::opt<bool>
Chris Lattnerf5db8f82009-04-19 07:00:02 +0000651Trigraphs("trigraphs", llvm::cl::desc("Process trigraph sequences"));
Ted Kremenekea644d82008-09-03 21:22:16 +0000652
Douglas Gregor26dce442009-03-10 00:06:19 +0000653static llvm::cl::opt<unsigned>
654TemplateDepth("ftemplate-depth", llvm::cl::init(99),
655 llvm::cl::desc("Maximum depth of recursive template "
656 "instantiation"));
Chris Lattnerf5db8f82009-04-19 07:00:02 +0000657static llvm::cl::opt<bool>
658DollarsInIdents("fdollars-in-identifiers",
659 llvm::cl::desc("Allow '$' in identifiers"));
Chris Lattner16167a62009-03-02 22:11:07 +0000660
Anders Carlsson4ca076f2009-04-06 17:37:10 +0000661
662static llvm::cl::opt<bool>
663OptSize("Os", llvm::cl::desc("Optimize for size"));
664
665static llvm::cl::opt<bool>
Mike Stump1eb44332009-09-09 15:08:12 +0000666DisableLLVMOptimizations("disable-llvm-optzns",
Daniel Dunbar877db382009-06-02 22:07:45 +0000667 llvm::cl::desc("Don't run LLVM optimization passes"));
668
669static llvm::cl::opt<bool>
Anders Carlsson4ca076f2009-04-06 17:37:10 +0000670NoCommon("fno-common",
671 llvm::cl::desc("Compile common globals like normal definitions"),
672 llvm::cl::ValueDisallowed);
673
Daniel Dunbarc9abc042009-04-08 05:11:16 +0000674static llvm::cl::opt<std::string>
675MainFileName("main-file-name",
676 llvm::cl::desc("Main file name to use for debug info"));
Anders Carlsson4ca076f2009-04-06 17:37:10 +0000677
Anders Carlssona33d9b42009-05-13 19:49:53 +0000678// FIXME: Also add an "-fno-access-control" option.
679static llvm::cl::opt<bool>
Mike Stump1eb44332009-09-09 15:08:12 +0000680AccessControl("faccess-control",
Anders Carlssona33d9b42009-05-13 19:49:53 +0000681 llvm::cl::desc("Enable C++ access control"));
682
Anders Carlsson92f58222009-08-22 22:30:33 +0000683static llvm::cl::opt<bool>
684NoElideConstructors("fno-elide-constructors",
685 llvm::cl::desc("Disable C++ copy constructor elision"));
686
Tanya Lattner59876c22009-11-04 01:18:09 +0000687static llvm::cl::opt<bool>
688NoMergeConstants("fno-merge-all-constants",
689 llvm::cl::desc("Disallow merging of constants."));
690
Daniel Dunbar73b79592009-09-14 00:02:12 +0000691static llvm::cl::opt<std::string>
692TargetABI("target-abi",
693 llvm::cl::desc("Target a particular ABI type"));
694
Daniel Dunbar7c15e712009-10-30 18:12:31 +0000695static llvm::cl::opt<std::string>
696TargetTriple("triple",
697 llvm::cl::desc("Specify target triple (e.g. i686-apple-darwin9)"));
698
Anders Carlsson92f58222009-08-22 22:30:33 +0000699
Anders Carlsson4ca076f2009-04-06 17:37:10 +0000700// It might be nice to add bounds to the CommandLine library directly.
701struct OptLevelParser : public llvm::cl::parser<unsigned> {
Chris Lattner59b21722009-09-20 00:39:15 +0000702 bool parse(llvm::cl::Option &O, llvm::StringRef ArgName,
703 llvm::StringRef Arg, unsigned &Val) {
Anders Carlsson4ca076f2009-04-06 17:37:10 +0000704 if (llvm::cl::parser<unsigned>::parse(O, ArgName, Arg, Val))
705 return true;
Anders Carlsson4ca076f2009-04-06 17:37:10 +0000706 if (Val > 3)
Benjamin Kramer21fde992009-08-02 12:12:11 +0000707 return O.error("'" + Arg + "' invalid optimization level!");
Anders Carlsson4ca076f2009-04-06 17:37:10 +0000708 return false;
709 }
710};
711static llvm::cl::opt<unsigned, false, OptLevelParser>
712OptLevel("O", llvm::cl::Prefix,
713 llvm::cl::desc("Optimization level"),
714 llvm::cl::init(0));
715
Daniel Dunbar9fd0b1f2009-04-08 03:03:23 +0000716static llvm::cl::opt<unsigned>
Daniel Dunbar3bbc7532009-04-08 18:03:55 +0000717PICLevel("pic-level", llvm::cl::desc("Value for __PIC__"));
718
719static llvm::cl::opt<bool>
720StaticDefine("static-define", llvm::cl::desc("Should __STATIC__ be defined"));
Daniel Dunbar9fd0b1f2009-04-08 03:03:23 +0000721
Bill Wendling45483f72009-06-28 07:36:13 +0000722static llvm::cl::opt<int>
723StackProtector("stack-protector",
724 llvm::cl::desc("Enable stack protectors"),
725 llvm::cl::init(-1));
726
Daniel Dunbardcb4a1a2008-08-23 08:43:39 +0000727static void InitializeLanguageStandard(LangOptions &Options, LangKind LK,
Daniel Dunbar868bd0a2009-05-06 03:16:41 +0000728 TargetInfo *Target,
729 const llvm::StringMap<bool> &Features) {
Chris Lattner8fc4dfb2008-12-04 22:54:33 +0000730 // Allow the target to set the default the langauge options as it sees fit.
731 Target->getDefaultLangOptions(Options);
Daniel Dunbar868bd0a2009-05-06 03:16:41 +0000732
733 // Pass the map of target features to the target for validation and
734 // processing.
735 Target->HandleTargetFeatures(Features);
Mike Stump1eb44332009-09-09 15:08:12 +0000736
Reid Spencer5f016e22007-07-11 17:01:13 +0000737 if (LangStd == lang_unspecified) {
738 // Based on the base language, pick one.
Ted Kremenek8904f152007-12-05 23:49:08 +0000739 switch (LK) {
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +0000740 case langkind_ast: assert(0 && "Invalid call for AST inputs");
Ted Kremenekf2a17b12009-03-19 19:02:20 +0000741 case lang_unspecified: assert(0 && "Unknown base language");
Nate Begeman4e3629e2009-06-25 22:43:10 +0000742 case langkind_ocl:
743 LangStd = lang_c99;
744 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000745 case langkind_c:
Chris Lattnera778d7d2008-10-22 17:29:21 +0000746 case langkind_asm_cpp:
Reid Spencer5f016e22007-07-11 17:01:13 +0000747 case langkind_c_cpp:
748 case langkind_objc:
749 case langkind_objc_cpp:
750 LangStd = lang_gnu99;
751 break;
752 case langkind_cxx:
753 case langkind_cxx_cpp:
754 case langkind_objcxx:
755 case langkind_objcxx_cpp:
756 LangStd = lang_gnucxx98;
757 break;
758 }
759 }
Mike Stump1eb44332009-09-09 15:08:12 +0000760
Reid Spencer5f016e22007-07-11 17:01:13 +0000761 switch (LangStd) {
762 default: assert(0 && "Unknown language standard!");
763
764 // Fall through from newer standards to older ones. This isn't really right.
765 // FIXME: Enable specifically the right features based on the language stds.
Chris Lattnerd4b80f12007-07-16 04:18:29 +0000766 case lang_gnucxx0x:
767 case lang_cxx0x:
768 Options.CPlusPlus0x = 1;
769 // FALL THROUGH
Reid Spencer5f016e22007-07-11 17:01:13 +0000770 case lang_gnucxx98:
771 case lang_cxx98:
772 Options.CPlusPlus = 1;
773 Options.CXXOperatorNames = !NoOperatorNames;
774 // FALL THROUGH.
775 case lang_gnu99:
776 case lang_c99:
Reid Spencer5f016e22007-07-11 17:01:13 +0000777 Options.C99 = 1;
778 Options.HexFloats = 1;
779 // FALL THROUGH.
780 case lang_gnu89:
781 Options.BCPLComment = 1; // Only for C99/C++.
782 // FALL THROUGH.
783 case lang_c94:
Chris Lattner3426b9b2008-02-25 04:01:39 +0000784 Options.Digraphs = 1; // C94, C99, C++.
785 // FALL THROUGH.
Reid Spencer5f016e22007-07-11 17:01:13 +0000786 case lang_c89:
787 break;
788 }
Argyrios Kyrtzidisd1465522008-09-11 04:21:06 +0000789
Chris Lattner7e9c90b2009-03-20 15:44:26 +0000790 // GNUMode - Set if we're in gnu99, gnu89, gnucxx98, etc.
Douglas Gregor214904e2009-09-29 14:42:43 +0000791 switch (LangStd) {
792 default: assert(0 && "Unknown language standard!");
793 case lang_gnucxx0x:
794 case lang_gnucxx98:
795 case lang_gnu99:
796 case lang_gnu89:
797 Options.GNUMode = 1;
798 break;
799 case lang_cxx0x:
800 case lang_cxx98:
801 case lang_c99:
802 case lang_c94:
803 case lang_c89:
804 Options.GNUMode = 0;
805 break;
806 }
Mike Stump1eb44332009-09-09 15:08:12 +0000807
Argyrios Kyrtzidisd1465522008-09-11 04:21:06 +0000808 if (Options.CPlusPlus) {
809 Options.C99 = 0;
Eli Friedmanab24c8d2009-08-26 20:15:14 +0000810 Options.HexFloats = 0;
Argyrios Kyrtzidisd1465522008-09-11 04:21:06 +0000811 }
Mike Stump1eb44332009-09-09 15:08:12 +0000812
Chris Lattnerd658b562008-04-05 06:32:51 +0000813 if (LangStd == lang_c89 || LangStd == lang_c94 || LangStd == lang_gnu89)
814 Options.ImplicitInt = 1;
815 else
816 Options.ImplicitInt = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000817
Daniel Dunbard573d262009-04-07 22:13:21 +0000818 // Mimicing gcc's behavior, trigraphs are only enabled if -trigraphs
819 // is specified, or -std is set to a conforming mode.
Chris Lattner7e9c90b2009-03-20 15:44:26 +0000820 Options.Trigraphs = !Options.GNUMode;
Chris Lattner802db9b2008-12-05 00:10:44 +0000821 if (Trigraphs.getPosition())
Chris Lattner7e9c90b2009-03-20 15:44:26 +0000822 Options.Trigraphs = Trigraphs; // Command line option wins if specified.
Ted Kremenekea644d82008-09-03 21:22:16 +0000823
Chris Lattner802db9b2008-12-05 00:10:44 +0000824 // If in a conformant language mode (e.g. -std=c99) Blocks defaults to off
825 // even if they are normally on for the target. In GNU modes (e.g.
826 // -std=gnu99) the default for blocks depends on the target settings.
Anders Carlssone56f6ff2009-01-21 18:47:36 +0000827 // However, blocks are not turned off when compiling Obj-C or Obj-C++ code.
Chris Lattner7e9c90b2009-03-20 15:44:26 +0000828 if (!Options.ObjC1 && !Options.GNUMode)
Chris Lattner802db9b2008-12-05 00:10:44 +0000829 Options.Blocks = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000830
Chris Lattner01638a62009-04-19 07:06:52 +0000831 // Default to not accepting '$' in identifiers when preprocessing assembler,
832 // but do accept when preprocessing C. FIXME: these defaults are right for
833 // darwin, are they right everywhere?
834 Options.DollarIdents = LK != langkind_asm_cpp;
835 if (DollarsInIdents.getPosition()) // Explicit setting overrides default.
Chris Lattnerf5db8f82009-04-19 07:00:02 +0000836 Options.DollarIdents = DollarsInIdents;
Mike Stump1eb44332009-09-09 15:08:12 +0000837
Chris Lattnerae0ee032008-12-04 23:20:07 +0000838 if (PascalStrings.getPosition())
839 Options.PascalStrings = PascalStrings;
Eli Friedmanabc4e322009-06-08 06:11:14 +0000840 if (MSExtensions.getPosition())
841 Options.Microsoft = MSExtensions;
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000842 Options.WritableStrings = WritableStrings;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +0000843 if (NoLaxVectorConversions.getPosition())
844 Options.LaxVectorConversions = 0;
Daniel Dunbar6379a7a2008-08-11 17:36:14 +0000845 Options.Exceptions = Exceptions;
Mike Stump738f8c22009-07-31 23:15:31 +0000846 Options.Rtti = Rtti;
Mike Stumpa0f02aa2009-02-02 22:57:57 +0000847 if (EnableBlocks.getPosition())
Chris Lattnerae0ee032008-12-04 23:20:07 +0000848 Options.Blocks = EnableBlocks;
Eli Friedmanc4757bd2009-06-05 07:12:17 +0000849 if (CharIsSigned.getPosition())
850 Options.CharIsSigned = CharIsSigned;
John Thompson40d1bb62009-11-05 22:03:02 +0000851 if (ShortWChar.getPosition())
852 Options.ShortWChar = ShortWChar;
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000853
Daniel Dunbar9f9768c2009-03-20 23:49:28 +0000854 if (!AllowBuiltins)
Chris Lattner7644f072009-03-13 22:38:49 +0000855 Options.NoBuiltin = 1;
Douglas Gregor3573c0c2009-02-14 20:49:29 +0000856 if (Freestanding)
Chris Lattner7644f072009-03-13 22:38:49 +0000857 Options.Freestanding = Options.NoBuiltin = 1;
Mike Stump1eb44332009-09-09 15:08:12 +0000858
Chris Lattner810f6d52009-03-13 17:38:01 +0000859 if (EnableHeinousExtensions)
860 Options.HeinousExtensions = 1;
Douglas Gregor3573c0c2009-02-14 20:49:29 +0000861
Anders Carlssona33d9b42009-05-13 19:49:53 +0000862 if (AccessControl)
863 Options.AccessControl = 1;
Mike Stump1eb44332009-09-09 15:08:12 +0000864
Anders Carlsson92f58222009-08-22 22:30:33 +0000865 Options.ElideConstructors = !NoElideConstructors;
Mike Stump1eb44332009-09-09 15:08:12 +0000866
Chris Lattnere4f21422009-06-30 01:26:17 +0000867 // OpenCL and C++ both have bool, true, false keywords.
868 Options.Bool = Options.OpenCL | Options.CPlusPlus;
Mike Stump1eb44332009-09-09 15:08:12 +0000869
Daniel Dunbaref2abfe2009-02-16 22:43:43 +0000870 Options.MathErrno = MathErrno;
871
Douglas Gregor26dce442009-03-10 00:06:19 +0000872 Options.InstantiationDepth = TemplateDepth;
873
Chris Lattner8fc4dfb2008-12-04 22:54:33 +0000874 // Override the default runtime if the user requested it.
875 if (NeXTRuntime)
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000876 Options.NeXTRuntime = 1;
Chris Lattner8fc4dfb2008-12-04 22:54:33 +0000877 else if (GNURuntime)
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000878 Options.NeXTRuntime = 0;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000879
David Chisnall8a5a9aa2009-08-31 16:41:57 +0000880 if (!ObjCConstantStringClass.empty())
881 Options.ObjCConstantStringClass = ObjCConstantStringClass.c_str();
882
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000883 if (ObjCNonFragileABI)
884 Options.ObjCNonFragileABI = 1;
Fariborz Jahanian34e65772009-05-22 20:17:16 +0000885
Daniel Dunbard604c402009-02-04 21:19:06 +0000886 if (EmitAllDecls)
887 Options.EmitAllDecls = 1;
Anders Carlsson4ca076f2009-04-06 17:37:10 +0000888
Daniel Dunbar3bbc7532009-04-08 18:03:55 +0000889 // The __OPTIMIZE_SIZE__ define is tied to -Oz, which we don't
890 // support.
891 Options.OptimizeSize = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000892
Anders Carlsson4ca076f2009-04-06 17:37:10 +0000893 // -Os implies -O2
Daniel Dunbar3bbc7532009-04-08 18:03:55 +0000894 if (OptSize || OptLevel)
Anders Carlsson4ca076f2009-04-06 17:37:10 +0000895 Options.Optimize = 1;
Daniel Dunbar9fd0b1f2009-04-08 03:03:23 +0000896
897 assert(PICLevel <= 2 && "Invalid value for -pic-level");
898 Options.PICLevel = PICLevel;
Daniel Dunbarc9abc042009-04-08 05:11:16 +0000899
Daniel Dunbar3bbc7532009-04-08 18:03:55 +0000900 Options.GNUInline = !Options.C99;
Mike Stump1eb44332009-09-09 15:08:12 +0000901 // FIXME: This is affected by other options (-fno-inline).
Daniel Dunbar3bbc7532009-04-08 18:03:55 +0000902 Options.NoInline = !OptSize && !OptLevel;
903
904 Options.Static = StaticDefine;
905
Bill Wendling4ebe3e42009-06-28 23:01:01 +0000906 switch (StackProtector) {
907 default:
908 assert(StackProtector <= 2 && "Invalid value for -stack-protector");
909 case -1: break;
910 case 0: Options.setStackProtectorMode(LangOptions::SSPOff); break;
911 case 1: Options.setStackProtectorMode(LangOptions::SSPOn); break;
912 case 2: Options.setStackProtectorMode(LangOptions::SSPReq); break;
913 }
Bill Wendling45483f72009-06-28 07:36:13 +0000914
Daniel Dunbarc9abc042009-04-08 05:11:16 +0000915 if (MainFileName.getPosition())
916 Options.setMainFileName(MainFileName.c_str());
John Thompsona6fda122009-11-05 20:14:16 +0000917
John Thompson40d1bb62009-11-05 22:03:02 +0000918 Target->setForcedLangOptions(Options);
Reid Spencer5f016e22007-07-11 17:01:13 +0000919}
920
921//===----------------------------------------------------------------------===//
Chris Lattnere116ccf2009-04-21 05:40:52 +0000922// SourceManager initialization.
Reid Spencer5f016e22007-07-11 17:01:13 +0000923//===----------------------------------------------------------------------===//
924
Douglas Gregore1d918e2009-04-10 23:10:45 +0000925static bool InitializeSourceManager(Preprocessor &PP,
926 const std::string &InFile) {
927 // Figure out where to get and map in the main file.
928 SourceManager &SourceMgr = PP.getSourceManager();
929 FileManager &FileMgr = PP.getFileManager();
Daniel Dunbar57cbfc02009-04-27 21:19:07 +0000930
931 if (EmptyInputOnly) {
932 const char *EmptyStr = "";
Mike Stump1eb44332009-09-09 15:08:12 +0000933 llvm::MemoryBuffer *SB =
Daniel Dunbar57cbfc02009-04-27 21:19:07 +0000934 llvm::MemoryBuffer::getMemBuffer(EmptyStr, EmptyStr, "<empty input>");
935 SourceMgr.createMainFileIDForMemBuffer(SB);
936 } else if (InFile != "-") {
Douglas Gregore1d918e2009-04-10 23:10:45 +0000937 const FileEntry *File = FileMgr.getFile(InFile);
938 if (File) SourceMgr.createMainFileID(File, SourceLocation());
939 if (SourceMgr.getMainFileID().isInvalid()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000940 PP.getDiagnostics().Report(FullSourceLoc(), diag::err_fe_error_reading)
Douglas Gregore1d918e2009-04-10 23:10:45 +0000941 << InFile.c_str();
942 return true;
943 }
944 } else {
945 llvm::MemoryBuffer *SB = llvm::MemoryBuffer::getSTDIN();
946
947 // If stdin was empty, SB is null. Cons up an empty memory
948 // buffer now.
949 if (!SB) {
950 const char *EmptyStr = "";
951 SB = llvm::MemoryBuffer::getMemBuffer(EmptyStr, EmptyStr, "<stdin>");
952 }
953
954 SourceMgr.createMainFileIDForMemBuffer(SB);
955 if (SourceMgr.getMainFileID().isInvalid()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000956 PP.getDiagnostics().Report(FullSourceLoc(),
Douglas Gregore1d918e2009-04-10 23:10:45 +0000957 diag::err_fe_error_reading_stdin);
958 return true;
959 }
960 }
961
962 return false;
963}
964
Chris Lattneraa391972008-04-19 23:09:31 +0000965
Chris Lattnere116ccf2009-04-21 05:40:52 +0000966//===----------------------------------------------------------------------===//
967// Preprocessor Initialization
968//===----------------------------------------------------------------------===//
Sam Bishop1102d6b2008-04-14 14:41:57 +0000969
Chris Lattnere6113de2009-11-03 19:50:27 +0000970static llvm::cl::opt<bool>
Daniel Dunbar468fe242009-11-04 21:13:02 +0000971UndefMacros("undef", llvm::cl::value_desc("macro"),
972 llvm::cl::desc("undef all system defines"));
Chris Lattnere6113de2009-11-03 19:50:27 +0000973
Chris Lattnere116ccf2009-04-21 05:40:52 +0000974static llvm::cl::list<std::string>
975D_macros("D", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
976 llvm::cl::desc("Predefine the specified macro"));
977static llvm::cl::list<std::string>
978U_macros("U", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
979 llvm::cl::desc("Undefine the specified macro"));
Chris Lattnerb8e240e2009-04-08 18:24:34 +0000980
Chris Lattnere116ccf2009-04-21 05:40:52 +0000981static llvm::cl::list<std::string>
982ImplicitIncludes("include", llvm::cl::value_desc("file"),
983 llvm::cl::desc("Include file before parsing"));
984static llvm::cl::list<std::string>
985ImplicitMacroIncludes("imacros", llvm::cl::value_desc("file"),
986 llvm::cl::desc("Include macros from file before parsing"));
Chris Lattnerb8e240e2009-04-08 18:24:34 +0000987
Chris Lattnere116ccf2009-04-21 05:40:52 +0000988static llvm::cl::opt<std::string>
989ImplicitIncludePCH("include-pch", llvm::cl::value_desc("file"),
990 llvm::cl::desc("Include precompiled header file"));
991
992static llvm::cl::opt<std::string>
993ImplicitIncludePTH("include-pth", llvm::cl::value_desc("file"),
994 llvm::cl::desc("Include file before parsing"));
995
Douglas Gregore650c8c2009-07-07 00:12:59 +0000996static llvm::cl::opt<bool>
Mike Stump1eb44332009-09-09 15:08:12 +0000997RelocatablePCH("relocatable-pch",
Douglas Gregore650c8c2009-07-07 00:12:59 +0000998 llvm::cl::desc("Whether to build a relocatable precompiled "
999 "header"));
Reid Spencer5f016e22007-07-11 17:01:13 +00001000
1001//===----------------------------------------------------------------------===//
1002// Preprocessor include path information.
1003//===----------------------------------------------------------------------===//
1004
1005// This tool exports a large number of command line options to control how the
1006// preprocessor searches for header files. At root, however, the Preprocessor
1007// object takes a very simple interface: a list of directories to search for
Mike Stump1eb44332009-09-09 15:08:12 +00001008//
Daniel Dunbarfb4ac7b2009-05-06 03:48:17 +00001009// FIXME: -nostdinc++
Chris Lattner0c946412007-08-26 17:47:35 +00001010// FIXME: -imultilib
Reid Spencer5f016e22007-07-11 17:01:13 +00001011//
Reid Spencer5f016e22007-07-11 17:01:13 +00001012
1013static llvm::cl::opt<bool>
1014nostdinc("nostdinc", llvm::cl::desc("Disable standard #include directories"));
1015
Rafael Espindola1bb15a92009-10-05 13:12:17 +00001016static llvm::cl::opt<bool>
Rafael Espindola8d737cc2009-10-26 13:36:57 +00001017nobuiltininc("nobuiltininc",
1018 llvm::cl::desc("Disable builtin #include directories"));
Rafael Espindola1bb15a92009-10-05 13:12:17 +00001019
Reid Spencer5f016e22007-07-11 17:01:13 +00001020// Various command line options. These four add directories to each chain.
1021static llvm::cl::list<std::string>
1022F_dirs("F", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1023 llvm::cl::desc("Add directory to framework include search path"));
1024static llvm::cl::list<std::string>
1025I_dirs("I", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1026 llvm::cl::desc("Add directory to include search path"));
1027static llvm::cl::list<std::string>
1028idirafter_dirs("idirafter", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1029 llvm::cl::desc("Add directory to AFTER include search path"));
1030static llvm::cl::list<std::string>
1031iquote_dirs("iquote", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1032 llvm::cl::desc("Add directory to QUOTE include search path"));
1033static llvm::cl::list<std::string>
1034isystem_dirs("isystem", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1035 llvm::cl::desc("Add directory to SYSTEM include search path"));
1036
1037// These handle -iprefix/-iwithprefix/-iwithprefixbefore.
1038static llvm::cl::list<std::string>
1039iprefix_vals("iprefix", llvm::cl::value_desc("prefix"), llvm::cl::Prefix,
1040 llvm::cl::desc("Set the -iwithprefix/-iwithprefixbefore prefix"));
1041static llvm::cl::list<std::string>
1042iwithprefix_vals("iwithprefix", llvm::cl::value_desc("dir"), llvm::cl::Prefix,
1043 llvm::cl::desc("Set directory to SYSTEM include search path with prefix"));
1044static llvm::cl::list<std::string>
1045iwithprefixbefore_vals("iwithprefixbefore", llvm::cl::value_desc("dir"),
1046 llvm::cl::Prefix,
1047 llvm::cl::desc("Set directory to include search path with prefix"));
1048
Chris Lattner0c946412007-08-26 17:47:35 +00001049static llvm::cl::opt<std::string>
1050isysroot("isysroot", llvm::cl::value_desc("dir"), llvm::cl::init("/"),
1051 llvm::cl::desc("Set the system root directory (usually /)"));
1052
Reid Spencer5f016e22007-07-11 17:01:13 +00001053// Finally, implement the code that groks the options above.
Chris Lattner5f9eae52008-03-01 08:07:28 +00001054
Rafael Espindola1bb15a92009-10-05 13:12:17 +00001055// Add the clang headers, which are relative to the clang binary.
Daniel Dunbar750156a2009-11-07 04:19:57 +00001056std::string GetBuiltinIncludePath(const char *Argv0) {
1057 llvm::sys::Path P =
1058 llvm::sys::Path::GetMainExecutable(Argv0,
1059 (void*)(intptr_t) GetBuiltinIncludePath);
Rafael Espindola1bb15a92009-10-05 13:12:17 +00001060
Daniel Dunbar750156a2009-11-07 04:19:57 +00001061 if (!P.isEmpty()) {
1062 P.eraseComponent(); // Remove /clang from foo/bin/clang
1063 P.eraseComponent(); // Remove /bin from foo/bin
Rafael Espindola1bb15a92009-10-05 13:12:17 +00001064
Daniel Dunbar750156a2009-11-07 04:19:57 +00001065 // Get foo/lib/clang/<version>/include
1066 P.appendComponent("lib");
1067 P.appendComponent("clang");
1068 P.appendComponent(CLANG_VERSION_STRING);
1069 P.appendComponent("include");
1070 }
Rafael Espindola1bb15a92009-10-05 13:12:17 +00001071
Daniel Dunbar750156a2009-11-07 04:19:57 +00001072 return P.str();
Rafael Espindola1bb15a92009-10-05 13:12:17 +00001073}
1074
Reid Spencer5f016e22007-07-11 17:01:13 +00001075/// InitializeIncludePaths - Process the -I options and set them in the
1076/// HeaderSearch object.
Nico Weber0fca0222008-08-22 09:25:22 +00001077void InitializeIncludePaths(const char *Argv0, HeaderSearch &Headers,
Mike Stump43d81762009-10-08 23:29:47 +00001078 FileManager &FM, const LangOptions &Lang,
1079 llvm::Triple &triple) {
Daniel Dunbardd35ce92009-11-07 04:58:12 +00001080 HeaderSearchOptions Opts(isysroot);
1081
1082 Opts.Verbose = Verbose;
Nico Weber0fca0222008-08-22 09:25:22 +00001083
Ted Kremenekf3721112008-05-31 00:27:00 +00001084 // Handle -I... and -F... options, walking the lists in parallel.
1085 unsigned Iidx = 0, Fidx = 0;
1086 while (Iidx < I_dirs.size() && Fidx < F_dirs.size()) {
1087 if (I_dirs.getPosition(Iidx) < F_dirs.getPosition(Fidx)) {
Daniel Dunbardd35ce92009-11-07 04:58:12 +00001088 Opts.AddPath(I_dirs[Iidx], InitHeaderSearch::Angled, false, true, false);
Ted Kremenekf3721112008-05-31 00:27:00 +00001089 ++Iidx;
1090 } else {
Daniel Dunbardd35ce92009-11-07 04:58:12 +00001091 Opts.AddPath(F_dirs[Fidx], InitHeaderSearch::Angled, false, true, true);
Ted Kremenekf3721112008-05-31 00:27:00 +00001092 ++Fidx;
1093 }
1094 }
Mike Stump1eb44332009-09-09 15:08:12 +00001095
Ted Kremenekf3721112008-05-31 00:27:00 +00001096 // Consume what's left from whatever list was longer.
1097 for (; Iidx != I_dirs.size(); ++Iidx)
Daniel Dunbardd35ce92009-11-07 04:58:12 +00001098 Opts.AddPath(I_dirs[Iidx], InitHeaderSearch::Angled, false, true, false);
Ted Kremenekf3721112008-05-31 00:27:00 +00001099 for (; Fidx != F_dirs.size(); ++Fidx)
Daniel Dunbardd35ce92009-11-07 04:58:12 +00001100 Opts.AddPath(F_dirs[Fidx], InitHeaderSearch::Angled, false, true, true);
Mike Stump1eb44332009-09-09 15:08:12 +00001101
Reid Spencer5f016e22007-07-11 17:01:13 +00001102 // Handle -idirafter... options.
1103 for (unsigned i = 0, e = idirafter_dirs.size(); i != e; ++i)
Daniel Dunbardd35ce92009-11-07 04:58:12 +00001104 Opts.AddPath(idirafter_dirs[i], InitHeaderSearch::After,
Nico Weber0fca0222008-08-22 09:25:22 +00001105 false, true, false);
Mike Stump1eb44332009-09-09 15:08:12 +00001106
Reid Spencer5f016e22007-07-11 17:01:13 +00001107 // Handle -iquote... options.
1108 for (unsigned i = 0, e = iquote_dirs.size(); i != e; ++i)
Daniel Dunbardd35ce92009-11-07 04:58:12 +00001109 Opts.AddPath(iquote_dirs[i], InitHeaderSearch::Quoted, false, true, false);
Mike Stump1eb44332009-09-09 15:08:12 +00001110
Reid Spencer5f016e22007-07-11 17:01:13 +00001111 // Handle -isystem... options.
1112 for (unsigned i = 0, e = isystem_dirs.size(); i != e; ++i)
Daniel Dunbardd35ce92009-11-07 04:58:12 +00001113 Opts.AddPath(isystem_dirs[i], InitHeaderSearch::System, false, true, false);
Reid Spencer5f016e22007-07-11 17:01:13 +00001114
1115 // Walk the -iprefix/-iwithprefix/-iwithprefixbefore argument lists in
1116 // parallel, processing the values in order of occurance to get the right
1117 // prefixes.
1118 {
1119 std::string Prefix = ""; // FIXME: this isn't the correct default prefix.
1120 unsigned iprefix_idx = 0;
1121 unsigned iwithprefix_idx = 0;
1122 unsigned iwithprefixbefore_idx = 0;
1123 bool iprefix_done = iprefix_vals.empty();
1124 bool iwithprefix_done = iwithprefix_vals.empty();
1125 bool iwithprefixbefore_done = iwithprefixbefore_vals.empty();
1126 while (!iprefix_done || !iwithprefix_done || !iwithprefixbefore_done) {
1127 if (!iprefix_done &&
Mike Stump1eb44332009-09-09 15:08:12 +00001128 (iwithprefix_done ||
1129 iprefix_vals.getPosition(iprefix_idx) <
Reid Spencer5f016e22007-07-11 17:01:13 +00001130 iwithprefix_vals.getPosition(iwithprefix_idx)) &&
Mike Stump1eb44332009-09-09 15:08:12 +00001131 (iwithprefixbefore_done ||
1132 iprefix_vals.getPosition(iprefix_idx) <
Reid Spencer5f016e22007-07-11 17:01:13 +00001133 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
1134 Prefix = iprefix_vals[iprefix_idx];
1135 ++iprefix_idx;
1136 iprefix_done = iprefix_idx == iprefix_vals.size();
1137 } else if (!iwithprefix_done &&
Mike Stump1eb44332009-09-09 15:08:12 +00001138 (iwithprefixbefore_done ||
1139 iwithprefix_vals.getPosition(iwithprefix_idx) <
Reid Spencer5f016e22007-07-11 17:01:13 +00001140 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
Daniel Dunbardd35ce92009-11-07 04:58:12 +00001141 Opts.AddPath(Prefix+iwithprefix_vals[iwithprefix_idx],
Nico Weber0fca0222008-08-22 09:25:22 +00001142 InitHeaderSearch::System, false, false, false);
Reid Spencer5f016e22007-07-11 17:01:13 +00001143 ++iwithprefix_idx;
1144 iwithprefix_done = iwithprefix_idx == iwithprefix_vals.size();
1145 } else {
Daniel Dunbardd35ce92009-11-07 04:58:12 +00001146 Opts.AddPath(Prefix+iwithprefixbefore_vals[iwithprefixbefore_idx],
Nico Weber0fca0222008-08-22 09:25:22 +00001147 InitHeaderSearch::Angled, false, false, false);
Reid Spencer5f016e22007-07-11 17:01:13 +00001148 ++iwithprefixbefore_idx;
Mike Stump1eb44332009-09-09 15:08:12 +00001149 iwithprefixbefore_done =
Reid Spencer5f016e22007-07-11 17:01:13 +00001150 iwithprefixbefore_idx == iwithprefixbefore_vals.size();
1151 }
1152 }
1153 }
Chris Lattner5f9eae52008-03-01 08:07:28 +00001154
Daniel Dunbare1665822009-11-07 04:20:39 +00001155 // Add CPATH environment paths.
1156 if (const char *Env = getenv("CPATH"))
Daniel Dunbardd35ce92009-11-07 04:58:12 +00001157 Opts.EnvIncPath = Env;
Daniel Dunbare1665822009-11-07 04:20:39 +00001158
1159 // Add language specific environment paths.
1160 if (Lang.CPlusPlus && Lang.ObjC1) {
1161 if (const char *Env = getenv("OBJCPLUS_INCLUDE_PATH"))
Daniel Dunbardd35ce92009-11-07 04:58:12 +00001162 Opts.LangEnvIncPath = Env;
Daniel Dunbare1665822009-11-07 04:20:39 +00001163 } else if (Lang.CPlusPlus) {
1164 if (const char *Env = getenv("CPLUS_INCLUDE_PATH"))
Daniel Dunbardd35ce92009-11-07 04:58:12 +00001165 Opts.LangEnvIncPath = Env;
Daniel Dunbare1665822009-11-07 04:20:39 +00001166 } else if (Lang.ObjC1) {
1167 if (const char *Env = getenv("OBJC_INCLUDE_PATH"))
Daniel Dunbardd35ce92009-11-07 04:58:12 +00001168 Opts.LangEnvIncPath = Env;
Daniel Dunbare1665822009-11-07 04:20:39 +00001169 } else {
1170 if (const char *Env = getenv("C_INCLUDE_PATH"))
Daniel Dunbardd35ce92009-11-07 04:58:12 +00001171 Opts.LangEnvIncPath = Env;
Daniel Dunbare1665822009-11-07 04:20:39 +00001172 }
Chris Lattner5f9eae52008-03-01 08:07:28 +00001173
Daniel Dunbardd35ce92009-11-07 04:58:12 +00001174 if (!nobuiltininc)
1175 Opts.BuiltinIncludePath = GetBuiltinIncludePath(Argv0);
Daniel Dunbar750156a2009-11-07 04:19:57 +00001176
Daniel Dunbardd35ce92009-11-07 04:58:12 +00001177 Opts.UseStandardIncludes = !nostdinc;
Mike Stump1eb44332009-09-09 15:08:12 +00001178
Daniel Dunbardd35ce92009-11-07 04:58:12 +00001179 // Apply all the options to the header search object.
1180 ApplyHeaderSearchOptions(Opts, Headers, Lang, triple);
Reid Spencer5f016e22007-07-11 17:01:13 +00001181}
1182
Daniel Dunbar8863b982009-11-07 04:20:15 +00001183void InitializePreprocessorOptions(PreprocessorOptions &InitOpts) {
Daniel Dunbar468fe242009-11-04 21:13:02 +00001184 // Use predefines?
1185 InitOpts.setUsePredefines(!UndefMacros);
1186
Chris Lattnere116ccf2009-04-21 05:40:52 +00001187 // Add macros from the command line.
1188 unsigned d = 0, D = D_macros.size();
1189 unsigned u = 0, U = U_macros.size();
1190 while (d < D || u < U) {
1191 if (u == U || (d < D && D_macros.getPosition(d) < U_macros.getPosition(u)))
1192 InitOpts.addMacroDef(D_macros[d++]);
1193 else
1194 InitOpts.addMacroUndef(U_macros[u++]);
1195 }
1196
1197 // If -imacros are specified, include them now. These are processed before
1198 // any -include directives.
1199 for (unsigned i = 0, e = ImplicitMacroIncludes.size(); i != e; ++i)
1200 InitOpts.addMacroInclude(ImplicitMacroIncludes[i]);
1201
Douglas Gregorb64c1932009-05-12 01:31:05 +00001202 if (!ImplicitIncludePTH.empty() || !ImplicitIncludes.empty() ||
1203 (!ImplicitIncludePCH.empty() && ProgAction == PrintPreprocessedInput)) {
Chris Lattnere116ccf2009-04-21 05:40:52 +00001204 // We want to add these paths to the predefines buffer in order, make a
1205 // temporary vector to sort by their occurrence.
1206 llvm::SmallVector<std::pair<unsigned, std::string*>, 8> OrderedPaths;
1207
1208 if (!ImplicitIncludePTH.empty())
1209 OrderedPaths.push_back(std::make_pair(ImplicitIncludePTH.getPosition(),
1210 &ImplicitIncludePTH));
Douglas Gregorb64c1932009-05-12 01:31:05 +00001211 if (!ImplicitIncludePCH.empty() && ProgAction == PrintPreprocessedInput)
1212 OrderedPaths.push_back(std::make_pair(ImplicitIncludePCH.getPosition(),
1213 &ImplicitIncludePCH));
Chris Lattnere116ccf2009-04-21 05:40:52 +00001214 for (unsigned i = 0, e = ImplicitIncludes.size(); i != e; ++i)
1215 OrderedPaths.push_back(std::make_pair(ImplicitIncludes.getPosition(i),
1216 &ImplicitIncludes[i]));
1217 llvm::array_pod_sort(OrderedPaths.begin(), OrderedPaths.end());
1218
1219
1220 // Now that they are ordered by position, add to the predefines buffer.
1221 for (unsigned i = 0, e = OrderedPaths.size(); i != e; ++i) {
1222 std::string *Ptr = OrderedPaths[i].second;
1223 if (!ImplicitIncludes.empty() &&
1224 Ptr >= &ImplicitIncludes[0] &&
1225 Ptr <= &ImplicitIncludes[ImplicitIncludes.size()-1]) {
1226 InitOpts.addInclude(*Ptr, false);
Douglas Gregorb64c1932009-05-12 01:31:05 +00001227 } else if (Ptr == &ImplicitIncludePTH) {
Chris Lattnere116ccf2009-04-21 05:40:52 +00001228 InitOpts.addInclude(*Ptr, true);
Douglas Gregorb64c1932009-05-12 01:31:05 +00001229 } else {
1230 // We end up here when we're producing preprocessed output and
1231 // we loaded a PCH file. In this case, just include the header
1232 // file that was used to build the precompiled header.
1233 assert(Ptr == &ImplicitIncludePCH);
1234 std::string OriginalFile = PCHReader::getOriginalSourceFile(*Ptr);
1235 if (!OriginalFile.empty()) {
1236 InitOpts.addInclude(OriginalFile, false);
1237 ImplicitIncludePCH.clear();
1238 }
Chris Lattnere116ccf2009-04-21 05:40:52 +00001239 }
1240 }
1241 }
1242}
1243
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001244//===----------------------------------------------------------------------===//
Daniel Dunbar90b18272009-11-04 23:56:25 +00001245// Preprocessor construction
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001246//===----------------------------------------------------------------------===//
1247
Daniel Dunbar90b18272009-11-04 23:56:25 +00001248static Preprocessor *
1249CreatePreprocessor(Diagnostic &Diags,const LangOptions &LangInfo,
1250 TargetInfo &Target, SourceManager &SourceMgr,
1251 HeaderSearch &HeaderInfo) {
1252 PTHManager *PTHMgr = 0;
1253 if (!TokenCache.empty() && !ImplicitIncludePTH.empty()) {
1254 fprintf(stderr, "error: cannot use both -token-cache and -include-pth "
1255 "options\n");
1256 exit(1);
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001257 }
Daniel Dunbar90b18272009-11-04 23:56:25 +00001258
1259 // Use PTH?
1260 if (!TokenCache.empty() || !ImplicitIncludePTH.empty()) {
1261 const std::string& x = TokenCache.empty() ? ImplicitIncludePTH:TokenCache;
1262 PTHMgr = PTHManager::Create(x, &Diags,
1263 TokenCache.empty() ? Diagnostic::Error
1264 : Diagnostic::Warning);
1265 }
1266
1267 if (Diags.hasErrorOccurred())
1268 exit(1);
1269
1270 // Create the Preprocessor.
1271 Preprocessor *PP = new Preprocessor(Diags, LangInfo, Target,
1272 SourceMgr, HeaderInfo, PTHMgr);
1273
1274 // Note that this is different then passing PTHMgr to Preprocessor's ctor.
1275 // That argument is used as the IdentifierInfoLookup argument to
1276 // IdentifierTable's ctor.
1277 if (PTHMgr) {
1278 PTHMgr->setPreprocessor(PP);
1279 PP->setPTHManager(PTHMgr);
1280 }
1281
Daniel Dunbar8863b982009-11-07 04:20:15 +00001282 PreprocessorOptions InitOpts;
1283 InitializePreprocessorOptions(InitOpts);
Daniel Dunbar90b18272009-11-04 23:56:25 +00001284 InitializePreprocessor(*PP, InitOpts);
1285
1286 return PP;
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001287}
Reid Spencer5f016e22007-07-11 17:01:13 +00001288
Reid Spencer5f016e22007-07-11 17:01:13 +00001289//===----------------------------------------------------------------------===//
1290// Basic Parser driver
1291//===----------------------------------------------------------------------===//
1292
Chris Lattner51574ea2008-04-19 23:25:44 +00001293static void ParseFile(Preprocessor &PP, MinimalAction *PA) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001294 Parser P(PP, *PA);
Ted Kremenek95041a22007-12-19 22:51:13 +00001295 PP.EnterMainSourceFile();
Mike Stump1eb44332009-09-09 15:08:12 +00001296
Reid Spencer5f016e22007-07-11 17:01:13 +00001297 // Parsing the specified input file.
1298 P.ParseTranslationUnit();
1299 delete PA;
1300}
1301
1302//===----------------------------------------------------------------------===//
Daniel Dunbar70f92432008-10-23 05:50:47 +00001303// Code generation options
1304//===----------------------------------------------------------------------===//
1305
1306static llvm::cl::opt<bool>
Chris Lattner15104882009-03-09 22:05:03 +00001307GenerateDebugInfo("g",
1308 llvm::cl::desc("Generate source level debug information"));
1309
Daniel Dunbara034ba82009-02-17 19:47:34 +00001310static llvm::cl::opt<std::string>
1311TargetCPU("mcpu",
1312 llvm::cl::desc("Target a specific cpu type (-mcpu=help for details)"));
1313
Daniel Dunbar868bd0a2009-05-06 03:16:41 +00001314static llvm::cl::list<std::string>
1315TargetFeatures("target-feature", llvm::cl::desc("Target specific attributes"));
1316
Devang Patel24095da2009-06-04 23:32:02 +00001317
1318static llvm::cl::opt<bool>
1319DisableRedZone("disable-red-zone",
1320 llvm::cl::desc("Do not emit code that uses the red zone."),
1321 llvm::cl::init(false));
1322
Devang Patelacebb392009-06-05 22:05:48 +00001323static llvm::cl::opt<bool>
1324NoImplicitFloat("no-implicit-float",
1325 llvm::cl::desc("Don't generate implicit floating point instructions (x86-only)"),
1326 llvm::cl::init(false));
1327
Daniel Dunbar868bd0a2009-05-06 03:16:41 +00001328/// ComputeTargetFeatures - Recompute the target feature list to only
1329/// be the list of things that are enabled, based on the target cpu
1330/// and feature list.
1331static void ComputeFeatureMap(TargetInfo *Target,
1332 llvm::StringMap<bool> &Features) {
Mike Stump1eb44332009-09-09 15:08:12 +00001333 assert(Features.empty() && "invalid map");
Daniel Dunbar868bd0a2009-05-06 03:16:41 +00001334
1335 // Initialize the feature map based on the target.
1336 Target->getDefaultFeatures(TargetCPU, Features);
1337
1338 // Apply the user specified deltas.
Mike Stump1eb44332009-09-09 15:08:12 +00001339 for (llvm::cl::list<std::string>::iterator it = TargetFeatures.begin(),
Daniel Dunbar868bd0a2009-05-06 03:16:41 +00001340 ie = TargetFeatures.end(); it != ie; ++it) {
1341 const char *Name = it->c_str();
Mike Stump1eb44332009-09-09 15:08:12 +00001342
Daniel Dunbar868bd0a2009-05-06 03:16:41 +00001343 // FIXME: Don't handle errors like this.
1344 if (Name[0] != '-' && Name[0] != '+') {
Mike Stump1eb44332009-09-09 15:08:12 +00001345 fprintf(stderr, "error: clang-cc: invalid target feature string: %s\n",
Daniel Dunbar868bd0a2009-05-06 03:16:41 +00001346 Name);
1347 exit(1);
1348 }
Daniel Dunbar17ca3632009-05-06 21:07:50 +00001349 if (!Target->setFeatureEnabled(Features, Name + 1, (Name[0] == '+'))) {
Mike Stump1eb44332009-09-09 15:08:12 +00001350 fprintf(stderr, "error: clang-cc: invalid target feature name: %s\n",
Daniel Dunbar17ca3632009-05-06 21:07:50 +00001351 Name + 1);
Daniel Dunbar868bd0a2009-05-06 03:16:41 +00001352 exit(1);
1353 }
Daniel Dunbar868bd0a2009-05-06 03:16:41 +00001354 }
1355}
1356
Chris Lattner7afae712009-03-16 18:41:18 +00001357static void InitializeCompileOptions(CompileOptions &Opts,
Daniel Dunbar868bd0a2009-05-06 03:16:41 +00001358 const LangOptions &LangOpts,
1359 const llvm::StringMap<bool> &Features) {
Daniel Dunbar70f92432008-10-23 05:50:47 +00001360 Opts.OptimizeSize = OptSize;
Chris Lattner20126042009-03-09 22:00:34 +00001361 Opts.DebugInfo = GenerateDebugInfo;
Daniel Dunbar877db382009-06-02 22:07:45 +00001362
1363 if (DisableLLVMOptimizations) {
1364 Opts.OptimizationLevel = 0;
1365 Opts.Inlining = CompileOptions::NoInlining;
Daniel Dunbarac7ffe02008-10-29 07:56:11 +00001366 } else {
Daniel Dunbar877db382009-06-02 22:07:45 +00001367 if (OptSize) {
1368 // -Os implies -O2
1369 Opts.OptimizationLevel = 2;
1370 } else {
1371 Opts.OptimizationLevel = OptLevel;
1372 }
1373
1374 // We must always run at least the always inlining pass.
1375 if (Opts.OptimizationLevel > 1)
1376 Opts.Inlining = CompileOptions::NormalInlining;
1377 else
1378 Opts.Inlining = CompileOptions::OnlyAlwaysInlining;
Daniel Dunbarac7ffe02008-10-29 07:56:11 +00001379 }
Daniel Dunbar8e8f3b72008-10-29 03:42:18 +00001380
1381 // FIXME: There are llvm-gcc options to control these selectively.
Daniel Dunbar8e8f3b72008-10-29 03:42:18 +00001382 Opts.UnrollLoops = (Opts.OptimizationLevel > 1 && !OptSize);
Chris Lattner7afae712009-03-16 18:41:18 +00001383 Opts.SimplifyLibCalls = !LangOpts.NoBuiltin;
Daniel Dunbardd913e52008-10-31 09:34:21 +00001384
1385#ifdef NDEBUG
1386 Opts.VerifyModule = 0;
1387#endif
Daniel Dunbara034ba82009-02-17 19:47:34 +00001388
1389 Opts.CPU = TargetCPU;
Daniel Dunbar868bd0a2009-05-06 03:16:41 +00001390 Opts.Features.clear();
Mike Stump1eb44332009-09-09 15:08:12 +00001391 for (llvm::StringMap<bool>::const_iterator it = Features.begin(),
Daniel Dunbar868bd0a2009-05-06 03:16:41 +00001392 ie = Features.end(); it != ie; ++it) {
1393 // FIXME: If we are completely confident that we have the right
1394 // set, we only need to pass the minuses.
1395 std::string Name(it->second ? "+" : "-");
1396 Name += it->first();
1397 Opts.Features.push_back(Name);
1398 }
Mike Stump1eb44332009-09-09 15:08:12 +00001399
Chris Lattnerbd360642009-03-26 05:00:52 +00001400 Opts.NoCommon = NoCommon | LangOpts.CPlusPlus;
Mike Stump1eb44332009-09-09 15:08:12 +00001401
Chris Lattner44502662009-02-18 01:23:44 +00001402 // Handle -ftime-report.
1403 Opts.TimePasses = TimeReport;
Devang Patel24095da2009-06-04 23:32:02 +00001404
1405 Opts.DisableRedZone = DisableRedZone;
Devang Patelacebb392009-06-05 22:05:48 +00001406 Opts.NoImplicitFloat = NoImplicitFloat;
Tanya Lattner59876c22009-11-04 01:18:09 +00001407
1408 Opts.MergeAllConstants = !NoMergeConstants;
Daniel Dunbar70f92432008-10-23 05:50:47 +00001409}
1410
1411//===----------------------------------------------------------------------===//
Douglas Gregor26df2f02009-04-02 19:05:20 +00001412// Fix-It Options
1413//===----------------------------------------------------------------------===//
1414static llvm::cl::list<ParsedSourceLocation>
1415FixItAtLocations("fixit-at", llvm::cl::value_desc("source-location"),
1416 llvm::cl::desc("Perform Fix-It modifications at the given source location"));
1417
1418//===----------------------------------------------------------------------===//
Eli Friedmanc6d656e2009-05-18 22:39:16 +00001419// ObjC Rewriter Options
1420//===----------------------------------------------------------------------===//
1421static llvm::cl::opt<bool>
1422SilenceRewriteMacroWarning("Wno-rewrite-macros", llvm::cl::init(false),
1423 llvm::cl::desc("Silence ObjC rewriting warnings"));
1424
1425//===----------------------------------------------------------------------===//
Eli Friedman0eeb86e2009-05-19 01:17:04 +00001426// Warning Options
1427//===----------------------------------------------------------------------===//
1428
1429// This gets all -W options, including -Werror, -W[no-]system-headers, etc. The
1430// driver has stripped off -Wa,foo etc. The driver has also translated -W to
1431// -Wextra, so we don't need to worry about it.
1432static llvm::cl::list<std::string>
1433OptWarnings("W", llvm::cl::Prefix, llvm::cl::ValueOptional);
1434
1435static llvm::cl::opt<bool> OptPedantic("pedantic");
1436static llvm::cl::opt<bool> OptPedanticErrors("pedantic-errors");
1437static llvm::cl::opt<bool> OptNoWarnings("w");
1438
1439//===----------------------------------------------------------------------===//
Eli Friedman12d3b1d2009-05-19 03:06:47 +00001440// Preprocessing (-E mode) Options
1441//===----------------------------------------------------------------------===//
1442static llvm::cl::opt<bool>
1443DisableLineMarkers("P", llvm::cl::desc("Disable linemarker output in -E mode"));
1444static llvm::cl::opt<bool>
1445EnableCommentOutput("C", llvm::cl::desc("Enable comment output in -E mode"));
1446static llvm::cl::opt<bool>
1447EnableMacroCommentOutput("CC",
1448 llvm::cl::desc("Enable comment output in -E mode, "
1449 "even from macro expansions"));
1450static llvm::cl::opt<bool>
1451DumpMacros("dM", llvm::cl::desc("Print macro definitions in -E mode instead of"
1452 " normal output"));
1453static llvm::cl::opt<bool>
1454DumpDefines("dD", llvm::cl::desc("Print macro definitions in -E mode in "
1455 "addition to normal output"));
Eli Friedmanb5c8f8b2009-05-19 03:35:57 +00001456
1457//===----------------------------------------------------------------------===//
1458// Dependency file options
1459//===----------------------------------------------------------------------===//
1460static llvm::cl::opt<std::string>
1461DependencyFile("dependency-file",
1462 llvm::cl::desc("Filename (or -) to write dependency output to"));
1463
1464static llvm::cl::opt<bool>
1465DependenciesIncludeSystemHeaders("sys-header-deps",
1466 llvm::cl::desc("Include system headers in dependency output"));
1467
1468static llvm::cl::list<std::string>
1469DependencyTargets("MT",
1470 llvm::cl::desc("Specify target for dependency"));
1471
1472// FIXME: Implement feature
1473static llvm::cl::opt<bool>
1474PhonyDependencyTarget("MP",
1475 llvm::cl::desc("Create phony target for each dependency "
1476 "(other than main file)"));
1477
Eli Friedman12d3b1d2009-05-19 03:06:47 +00001478//===----------------------------------------------------------------------===//
Eli Friedmane71b85f2009-05-19 10:18:02 +00001479// Analysis options
1480//===----------------------------------------------------------------------===//
1481
1482static llvm::cl::list<Analyses>
1483AnalysisList(llvm::cl::desc("Source Code Analysis - Checks and Analyses"),
1484llvm::cl::values(
1485#define ANALYSIS(NAME, CMDFLAG, DESC, SCOPE)\
1486clEnumValN(NAME, CMDFLAG, DESC),
Eli Friedman0ec78fa2009-05-19 21:10:40 +00001487#include "clang/Frontend/Analyses.def"
Eli Friedmane71b85f2009-05-19 10:18:02 +00001488clEnumValEnd));
1489
Mike Stump1eb44332009-09-09 15:08:12 +00001490static llvm::cl::opt<AnalysisStores>
Eli Friedmane71b85f2009-05-19 10:18:02 +00001491AnalysisStoreOpt("analyzer-store",
1492 llvm::cl::desc("Source Code Analysis - Abstract Memory Store Models"),
1493 llvm::cl::init(BasicStoreModel),
1494 llvm::cl::values(
1495#define ANALYSIS_STORE(NAME, CMDFLAG, DESC, CREATFN)\
1496clEnumValN(NAME##Model, CMDFLAG, DESC),
Eli Friedman0ec78fa2009-05-19 21:10:40 +00001497#include "clang/Frontend/Analyses.def"
Eli Friedmane71b85f2009-05-19 10:18:02 +00001498clEnumValEnd));
1499
Mike Stump1eb44332009-09-09 15:08:12 +00001500static llvm::cl::opt<AnalysisConstraints>
Eli Friedmane71b85f2009-05-19 10:18:02 +00001501AnalysisConstraintsOpt("analyzer-constraints",
1502 llvm::cl::desc("Source Code Analysis - Symbolic Constraint Engines"),
1503 llvm::cl::init(RangeConstraintsModel),
1504 llvm::cl::values(
1505#define ANALYSIS_CONSTRAINTS(NAME, CMDFLAG, DESC, CREATFN)\
1506clEnumValN(NAME##Model, CMDFLAG, DESC),
Eli Friedman0ec78fa2009-05-19 21:10:40 +00001507#include "clang/Frontend/Analyses.def"
Eli Friedmane71b85f2009-05-19 10:18:02 +00001508clEnumValEnd));
1509
1510static llvm::cl::opt<AnalysisDiagClients>
1511AnalysisDiagOpt("analyzer-output",
1512 llvm::cl::desc("Source Code Analysis - Output Options"),
1513 llvm::cl::init(PD_HTML),
1514 llvm::cl::values(
1515#define ANALYSIS_DIAGNOSTICS(NAME, CMDFLAG, DESC, CREATFN, AUTOCREATE)\
1516clEnumValN(PD_##NAME, CMDFLAG, DESC),
Eli Friedman0ec78fa2009-05-19 21:10:40 +00001517#include "clang/Frontend/Analyses.def"
Eli Friedmane71b85f2009-05-19 10:18:02 +00001518clEnumValEnd));
1519
1520static llvm::cl::opt<bool>
1521VisualizeEGDot("analyzer-viz-egraph-graphviz",
1522 llvm::cl::desc("Display exploded graph using GraphViz"));
1523
1524static llvm::cl::opt<bool>
1525VisualizeEGUbi("analyzer-viz-egraph-ubigraph",
1526 llvm::cl::desc("Display exploded graph using Ubigraph"));
1527
1528static llvm::cl::opt<bool>
1529AnalyzeAll("analyzer-opt-analyze-headers",
1530 llvm::cl::desc("Force the static analyzer to analyze "
1531 "functions defined in header files"));
1532
1533static llvm::cl::opt<bool>
1534AnalyzerDisplayProgress("analyzer-display-progress",
1535 llvm::cl::desc("Emit verbose output about the analyzer's progress."));
1536
1537static llvm::cl::opt<bool>
1538PurgeDead("analyzer-purge-dead",
1539 llvm::cl::init(true),
1540 llvm::cl::desc("Remove dead symbols, bindings, and constraints before"
1541 " processing a statement."));
1542
1543static llvm::cl::opt<bool>
1544EagerlyAssume("analyzer-eagerly-assume",
1545 llvm::cl::init(false),
1546 llvm::cl::desc("Eagerly assume the truth/falseness of some "
1547 "symbolic constraints."));
1548
1549static llvm::cl::opt<std::string>
1550AnalyzeSpecificFunction("analyze-function",
1551 llvm::cl::desc("Run analysis on specific function"));
1552
1553static llvm::cl::opt<bool>
1554TrimGraph("trim-egraph",
1555 llvm::cl::desc("Only show error-related paths in the analysis graph"));
1556
1557static AnalyzerOptions ReadAnalyzerOptions() {
1558 AnalyzerOptions Opts;
1559 Opts.AnalysisList = AnalysisList;
1560 Opts.AnalysisStoreOpt = AnalysisStoreOpt;
1561 Opts.AnalysisConstraintsOpt = AnalysisConstraintsOpt;
1562 Opts.AnalysisDiagOpt = AnalysisDiagOpt;
1563 Opts.VisualizeEGDot = VisualizeEGDot;
1564 Opts.VisualizeEGUbi = VisualizeEGUbi;
1565 Opts.AnalyzeAll = AnalyzeAll;
1566 Opts.AnalyzerDisplayProgress = AnalyzerDisplayProgress;
1567 Opts.PurgeDead = PurgeDead;
1568 Opts.EagerlyAssume = EagerlyAssume;
1569 Opts.AnalyzeSpecificFunction = AnalyzeSpecificFunction;
1570 Opts.TrimGraph = TrimGraph;
1571 return Opts;
1572}
1573
1574//===----------------------------------------------------------------------===//
Chris Lattner75a97cb2009-04-17 21:05:01 +00001575// -dump-build-information Stuff
1576//===----------------------------------------------------------------------===//
1577
1578static llvm::cl::opt<std::string>
1579DumpBuildInformation("dump-build-information",
1580 llvm::cl::value_desc("filename"),
1581 llvm::cl::desc("output a dump of some build information to a file"));
1582
1583static llvm::raw_ostream *BuildLogFile = 0;
1584
1585/// LoggingDiagnosticClient - This is a simple diagnostic client that forwards
1586/// all diagnostics to both BuildLogFile and a chained DiagnosticClient.
1587namespace {
1588class LoggingDiagnosticClient : public DiagnosticClient {
1589 llvm::OwningPtr<DiagnosticClient> Chain1;
1590 llvm::OwningPtr<DiagnosticClient> Chain2;
1591public:
Mike Stump1eb44332009-09-09 15:08:12 +00001592
Chris Lattner75a97cb2009-04-17 21:05:01 +00001593 LoggingDiagnosticClient(DiagnosticClient *Normal) {
1594 // Output diags both where requested...
1595 Chain1.reset(Normal);
1596 // .. and to our log file.
Daniel Dunbareace8742009-11-04 06:24:30 +00001597 Chain2.reset(new TextDiagnosticPrinter(*BuildLogFile, DiagOpts));
Chris Lattner75a97cb2009-04-17 21:05:01 +00001598 }
Mike Stump1eb44332009-09-09 15:08:12 +00001599
Daniel Dunbarefcbe942009-11-05 02:42:12 +00001600 virtual void BeginSourceFile(const LangOptions &LO) {
1601 Chain1->BeginSourceFile(LO);
1602 Chain2->BeginSourceFile(LO);
1603 }
1604
1605 virtual void EndSourceFile() {
1606 Chain1->EndSourceFile();
1607 Chain2->EndSourceFile();
Chris Lattner75a97cb2009-04-17 21:05:01 +00001608 }
Mike Stump1eb44332009-09-09 15:08:12 +00001609
Chris Lattner75a97cb2009-04-17 21:05:01 +00001610 virtual bool IncludeInDiagnosticCounts() const {
1611 return Chain1->IncludeInDiagnosticCounts();
1612 }
1613
1614 virtual void HandleDiagnostic(Diagnostic::Level DiagLevel,
1615 const DiagnosticInfo &Info) {
1616 Chain1->HandleDiagnostic(DiagLevel, Info);
1617 Chain2->HandleDiagnostic(DiagLevel, Info);
1618 }
1619};
1620} // end anonymous namespace.
1621
1622static void SetUpBuildDumpLog(unsigned argc, char **argv,
1623 llvm::OwningPtr<DiagnosticClient> &DiagClient) {
Mike Stump1eb44332009-09-09 15:08:12 +00001624
Chris Lattner75a97cb2009-04-17 21:05:01 +00001625 std::string ErrorInfo;
Chris Lattner92bcc272009-08-23 02:59:41 +00001626 BuildLogFile = new llvm::raw_fd_ostream(DumpBuildInformation.c_str(),
Dan Gohmanb044c472009-08-25 15:36:09 +00001627 ErrorInfo);
Mike Stump1eb44332009-09-09 15:08:12 +00001628
Chris Lattner75a97cb2009-04-17 21:05:01 +00001629 if (!ErrorInfo.empty()) {
1630 llvm::errs() << "error opening -dump-build-information file '"
1631 << DumpBuildInformation << "', option ignored!\n";
1632 delete BuildLogFile;
1633 BuildLogFile = 0;
1634 DumpBuildInformation = "";
1635 return;
1636 }
1637
1638 (*BuildLogFile) << "clang-cc command line arguments: ";
1639 for (unsigned i = 0; i != argc; ++i)
1640 (*BuildLogFile) << argv[i] << ' ';
1641 (*BuildLogFile) << '\n';
Mike Stump1eb44332009-09-09 15:08:12 +00001642
Chris Lattner75a97cb2009-04-17 21:05:01 +00001643 // LoggingDiagnosticClient - Insert a new logging diagnostic client in between
1644 // the diagnostic producers and the normal receiver.
1645 DiagClient.reset(new LoggingDiagnosticClient(DiagClient.take()));
1646}
1647
1648
1649
1650//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +00001651// Main driver
1652//===----------------------------------------------------------------------===//
1653
Chris Lattner92bcc272009-08-23 02:59:41 +00001654static llvm::raw_ostream *ComputeOutFile(const std::string &InFile,
1655 const char *Extension,
Eli Friedman66d6f042009-05-18 22:20:00 +00001656 bool Binary,
1657 llvm::sys::Path& OutPath) {
Chris Lattner92bcc272009-08-23 02:59:41 +00001658 llvm::raw_ostream *Ret;
Eli Friedman66d6f042009-05-18 22:20:00 +00001659 std::string OutFile;
Chris Lattner92bcc272009-08-23 02:59:41 +00001660 if (!OutputFile.empty())
Eli Friedman66d6f042009-05-18 22:20:00 +00001661 OutFile = OutputFile;
Chris Lattner92bcc272009-08-23 02:59:41 +00001662 else if (InFile == "-") {
1663 OutFile = "-";
Eli Friedman66d6f042009-05-18 22:20:00 +00001664 } else if (Extension) {
1665 llvm::sys::Path Path(InFile);
1666 Path.eraseSuffix();
1667 Path.appendSuffix(Extension);
Chris Lattnerd57a7ef2009-08-23 22:45:33 +00001668 OutFile = Path.str();
Eli Friedman66d6f042009-05-18 22:20:00 +00001669 } else {
Chris Lattner92bcc272009-08-23 02:59:41 +00001670 OutFile = "-";
Chris Lattner8a5c8092009-02-18 01:20:05 +00001671 }
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +00001672
Chris Lattner92bcc272009-08-23 02:59:41 +00001673 std::string Error;
1674 Ret = new llvm::raw_fd_ostream(OutFile.c_str(), Error,
Dan Gohmanb044c472009-08-25 15:36:09 +00001675 (Binary ? llvm::raw_fd_ostream::F_Binary : 0));
Chris Lattner92bcc272009-08-23 02:59:41 +00001676 if (!Error.empty()) {
1677 // FIXME: Don't fail this way.
1678 llvm::errs() << "ERROR: " << Error << "\n";
1679 ::exit(1);
Ted Kremenekdb094a22007-12-05 18:27:04 +00001680 }
Mike Stump1eb44332009-09-09 15:08:12 +00001681
Chris Lattner92bcc272009-08-23 02:59:41 +00001682 if (OutFile != "-")
1683 OutPath = OutFile;
Eli Friedman66d6f042009-05-18 22:20:00 +00001684
1685 return Ret;
Ted Kremenekdb094a22007-12-05 18:27:04 +00001686}
1687
Daniel Dunbar0794d8d2009-09-17 00:48:00 +00001688static ASTConsumer *CreateConsumerAction(Preprocessor &PP,
1689 const std::string &InFile,
1690 ProgActions PA,
1691 llvm::OwningPtr<llvm::raw_ostream> &OS,
1692 llvm::sys::Path &OutPath,
1693 const llvm::StringMap<bool> &Features,
1694 llvm::LLVMContext& Context) {
Ted Kremenek85888962008-10-21 00:54:44 +00001695 switch (PA) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001696 default:
Daniel Dunbar0794d8d2009-09-17 00:48:00 +00001697 return 0;
Eli Friedman66d6f042009-05-18 22:20:00 +00001698
1699 case ASTPrint:
1700 OS.reset(ComputeOutFile(InFile, 0, false, OutPath));
Daniel Dunbar0794d8d2009-09-17 00:48:00 +00001701 return CreateASTPrinter(OS.get());
Mike Stump1eb44332009-09-09 15:08:12 +00001702
Douglas Gregoree75c052009-05-21 20:55:50 +00001703 case ASTPrintXML:
1704 OS.reset(ComputeOutFile(InFile, "xml", false, OutPath));
Daniel Dunbar0794d8d2009-09-17 00:48:00 +00001705 return CreateASTPrinterXML(OS.get());
Douglas Gregoree75c052009-05-21 20:55:50 +00001706
Eli Friedman66d6f042009-05-18 22:20:00 +00001707 case ASTDump:
Daniel Dunbar0794d8d2009-09-17 00:48:00 +00001708 return CreateASTDumper();
Eli Friedman66d6f042009-05-18 22:20:00 +00001709
Eli Friedman66d6f042009-05-18 22:20:00 +00001710 case ASTView:
Daniel Dunbar0794d8d2009-09-17 00:48:00 +00001711 return CreateASTViewer();
Eli Friedman66d6f042009-05-18 22:20:00 +00001712
1713 case PrintDeclContext:
Daniel Dunbar0794d8d2009-09-17 00:48:00 +00001714 return CreateDeclContextPrinter();
Eli Friedman66d6f042009-05-18 22:20:00 +00001715
Anders Carlsson78762eb2009-09-24 18:54:49 +00001716 case DumpRecordLayouts:
1717 return CreateRecordLayoutDumper();
1718
Eli Friedman66d6f042009-05-18 22:20:00 +00001719 case InheritanceView:
Daniel Dunbar0794d8d2009-09-17 00:48:00 +00001720 return CreateInheritanceViewer(InheritanceViewCls);
Eli Friedman66d6f042009-05-18 22:20:00 +00001721
1722 case EmitAssembly:
1723 case EmitLLVM:
Mike Stump1eb44332009-09-09 15:08:12 +00001724 case EmitBC:
Eli Friedman66d6f042009-05-18 22:20:00 +00001725 case EmitLLVMOnly: {
1726 BackendAction Act;
1727 if (ProgAction == EmitAssembly) {
1728 Act = Backend_EmitAssembly;
1729 OS.reset(ComputeOutFile(InFile, "s", true, OutPath));
1730 } else if (ProgAction == EmitLLVM) {
1731 Act = Backend_EmitLL;
1732 OS.reset(ComputeOutFile(InFile, "ll", true, OutPath));
1733 } else if (ProgAction == EmitLLVMOnly) {
1734 Act = Backend_EmitNothing;
1735 } else {
1736 Act = Backend_EmitBC;
1737 OS.reset(ComputeOutFile(InFile, "bc", true, OutPath));
Ted Kremenekdb094a22007-12-05 18:27:04 +00001738 }
Ted Kremenekfdfc1982007-12-19 22:24:34 +00001739
Eli Friedman66d6f042009-05-18 22:20:00 +00001740 CompileOptions Opts;
1741 InitializeCompileOptions(Opts, PP.getLangOptions(), Features);
Daniel Dunbar0794d8d2009-09-17 00:48:00 +00001742 return CreateBackendConsumer(Act, PP.getDiagnostics(), PP.getLangOptions(),
1743 Opts, InFile, OS.get(), Context);
Eli Friedman66d6f042009-05-18 22:20:00 +00001744 }
1745
Daniel Dunbar0794d8d2009-09-17 00:48:00 +00001746 case RewriteObjC:
1747 OS.reset(ComputeOutFile(InFile, "cpp", true, OutPath));
1748 return CreateObjCRewriter(InFile, OS.get(), PP.getDiagnostics(),
1749 PP.getLangOptions(), SilenceRewriteMacroWarning);
1750
1751 case RewriteBlocks:
1752 return CreateBlockRewriter(InFile, PP.getDiagnostics(),
1753 PP.getLangOptions());
1754 }
1755}
1756
1757/// ProcessInputFile - Process a single input file with the specified state.
1758///
Daniel Dunbar90b18272009-11-04 23:56:25 +00001759static void ProcessInputFile(Preprocessor &PP, const std::string &InFile,
1760 ProgActions PA,
Daniel Dunbar0794d8d2009-09-17 00:48:00 +00001761 const llvm::StringMap<bool> &Features,
1762 llvm::LLVMContext& Context) {
1763 llvm::OwningPtr<llvm::raw_ostream> OS;
1764 llvm::OwningPtr<ASTConsumer> Consumer;
1765 bool ClearSourceMgr = false;
1766 FixItRewriter *FixItRewrite = 0;
1767 bool CompleteTranslationUnit = true;
1768 llvm::sys::Path OutPath;
1769
1770 switch (PA) {
1771 default:
1772 Consumer.reset(CreateConsumerAction(PP, InFile, PA, OS, OutPath,
1773 Features, Context));
1774
1775 if (!Consumer.get()) {
Daniel Dunbar8cb65622009-10-29 21:05:18 +00001776 PP.getDiagnostics().Report(FullSourceLoc(),
1777 diag::err_fe_invalid_ast_action);
Daniel Dunbar0794d8d2009-09-17 00:48:00 +00001778 return;
1779 }
1780
1781 break;;
1782
1783 case EmitHTML:
1784 OS.reset(ComputeOutFile(InFile, 0, true, OutPath));
Daniel Dunbar90b18272009-11-04 23:56:25 +00001785 Consumer.reset(CreateHTMLPrinter(OS.get(), PP));
Daniel Dunbar0794d8d2009-09-17 00:48:00 +00001786 break;
1787
1788 case RunAnalysis:
Daniel Dunbarefceabd2009-11-05 02:41:58 +00001789 Consumer.reset(CreateAnalysisConsumer(PP, OutputFile,
Daniel Dunbar0794d8d2009-09-17 00:48:00 +00001790 ReadAnalyzerOptions()));
1791 break;
1792
Eli Friedman66d6f042009-05-18 22:20:00 +00001793 case GeneratePCH:
Douglas Gregore650c8c2009-07-07 00:12:59 +00001794 if (RelocatablePCH.getValue() && !isysroot.getNumOccurrences()) {
1795 PP.Diag(SourceLocation(), diag::err_relocatable_without_without_isysroot);
1796 RelocatablePCH.setValue(false);
1797 }
Mike Stump1eb44332009-09-09 15:08:12 +00001798
Eli Friedman66d6f042009-05-18 22:20:00 +00001799 OS.reset(ComputeOutFile(InFile, 0, true, OutPath));
Douglas Gregore650c8c2009-07-07 00:12:59 +00001800 if (RelocatablePCH.getValue())
1801 Consumer.reset(CreatePCHGenerator(PP, OS.get(), isysroot.c_str()));
1802 else
1803 Consumer.reset(CreatePCHGenerator(PP, OS.get()));
Eli Friedman66d6f042009-05-18 22:20:00 +00001804 CompleteTranslationUnit = false;
1805 break;
1806
Chris Lattnerc106c102008-10-12 05:03:36 +00001807 case DumpRawTokens: {
Chris Lattner47099742009-02-18 01:51:21 +00001808 llvm::TimeRegion Timer(ClangFrontendTimer);
Chris Lattnerc106c102008-10-12 05:03:36 +00001809 SourceManager &SM = PP.getSourceManager();
Chris Lattnerc106c102008-10-12 05:03:36 +00001810 // Start lexing the specified input file.
Chris Lattner025c3a62009-01-17 07:35:14 +00001811 Lexer RawLex(SM.getMainFileID(), SM, PP.getLangOptions());
Chris Lattnerc106c102008-10-12 05:03:36 +00001812 RawLex.SetKeepWhitespaceMode(true);
1813
1814 Token RawTok;
Chris Lattnerc106c102008-10-12 05:03:36 +00001815 RawLex.LexFromRawLexer(RawTok);
1816 while (RawTok.isNot(tok::eof)) {
1817 PP.DumpToken(RawTok, true);
1818 fprintf(stderr, "\n");
1819 RawLex.LexFromRawLexer(RawTok);
1820 }
1821 ClearSourceMgr = true;
1822 break;
1823 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001824 case DumpTokens: { // Token dump mode.
Chris Lattner47099742009-02-18 01:51:21 +00001825 llvm::TimeRegion Timer(ClangFrontendTimer);
Chris Lattnerd2177732007-07-20 16:59:19 +00001826 Token Tok;
Chris Lattnerc106c102008-10-12 05:03:36 +00001827 // Start preprocessing the specified input file.
Ted Kremenek95041a22007-12-19 22:51:13 +00001828 PP.EnterMainSourceFile();
Reid Spencer5f016e22007-07-11 17:01:13 +00001829 do {
1830 PP.Lex(Tok);
1831 PP.DumpToken(Tok, true);
1832 fprintf(stderr, "\n");
Chris Lattner057aaf62007-10-09 18:03:42 +00001833 } while (Tok.isNot(tok::eof));
Chris Lattnerbd247762007-07-22 06:05:44 +00001834 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001835 break;
1836 }
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001837 case RunPreprocessorOnly:
Reid Spencer5f016e22007-07-11 17:01:13 +00001838 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001839
Douglas Gregorbf1bd6e2009-04-02 23:43:50 +00001840 case GeneratePTH: {
Chris Lattner47099742009-02-18 01:51:21 +00001841 llvm::TimeRegion Timer(ClangFrontendTimer);
Eli Friedmanf54fce82009-05-19 01:02:07 +00001842 if (OutputFile.empty() || OutputFile == "-") {
1843 // FIXME: Don't fail this way.
1844 // FIXME: Verify that we can actually seek in the given file.
Chris Lattner92bcc272009-08-23 02:59:41 +00001845 llvm::errs() << "ERROR: PTH requires an seekable file for output!\n";
Eli Friedmanf54fce82009-05-19 01:02:07 +00001846 ::exit(1);
1847 }
1848 OS.reset(ComputeOutFile(InFile, 0, true, OutPath));
1849 CacheTokens(PP, static_cast<llvm::raw_fd_ostream*>(OS.get()));
Ted Kremenek85888962008-10-21 00:54:44 +00001850 ClearSourceMgr = true;
1851 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001852 }
Douglas Gregor6ab35242009-04-09 21:40:53 +00001853
Chris Lattnercc7dea82009-04-27 22:02:30 +00001854 case PrintPreprocessedInput:
Eli Friedmanf54fce82009-05-19 01:02:07 +00001855 OS.reset(ComputeOutFile(InFile, 0, true, OutPath));
Reid Spencer5f016e22007-07-11 17:01:13 +00001856 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001857
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001858 case ParseNoop:
Reid Spencer5f016e22007-07-11 17:01:13 +00001859 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001860
Chris Lattner47099742009-02-18 01:51:21 +00001861 case ParsePrintCallbacks: {
1862 llvm::TimeRegion Timer(ClangFrontendTimer);
Eli Friedmanf54fce82009-05-19 01:02:07 +00001863 OS.reset(ComputeOutFile(InFile, 0, true, OutPath));
1864 ParseFile(PP, CreatePrintParserActionsAction(PP, OS.get()));
Chris Lattnerbd247762007-07-22 06:05:44 +00001865 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001866 break;
Chris Lattner47099742009-02-18 01:51:21 +00001867 }
1868
1869 case ParseSyntaxOnly: { // -fsyntax-only
1870 llvm::TimeRegion Timer(ClangFrontendTimer);
Ted Kremenek7e7e6252008-08-08 02:46:37 +00001871 Consumer.reset(new ASTConsumer());
Ted Kremenek2bf55142007-09-17 20:49:30 +00001872 break;
Chris Lattner47099742009-02-18 01:51:21 +00001873 }
Mike Stump1eb44332009-09-09 15:08:12 +00001874
Chris Lattnerb57e3d42008-05-08 06:52:13 +00001875 case RewriteMacros:
Eli Friedmanf54fce82009-05-19 01:02:07 +00001876 OS.reset(ComputeOutFile(InFile, 0, true, OutPath));
1877 RewriteMacrosInInput(PP, OS.get());
Chris Lattnerb57e3d42008-05-08 06:52:13 +00001878 ClearSourceMgr = true;
1879 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001880
Eli Friedmanf54fce82009-05-19 01:02:07 +00001881 case RewriteTest:
1882 OS.reset(ComputeOutFile(InFile, 0, true, OutPath));
1883 DoRewriteTest(PP, OS.get());
Chris Lattnerb13c5ee2008-10-12 05:29:20 +00001884 ClearSourceMgr = true;
1885 break;
Douglas Gregor558cb562009-04-02 01:08:08 +00001886
1887 case FixIt:
1888 llvm::TimeRegion Timer(ClangFrontendTimer);
1889 Consumer.reset(new ASTConsumer());
Douglas Gregorde4bf6a2009-04-02 17:13:00 +00001890 FixItRewrite = new FixItRewriter(PP.getDiagnostics(),
Chris Lattner2c78b872009-04-14 23:22:57 +00001891 PP.getSourceManager(),
1892 PP.getLangOptions());
Douglas Gregor558cb562009-04-02 01:08:08 +00001893 break;
Chris Lattner47099742009-02-18 01:51:21 +00001894 }
Ted Kremenek46157b52009-01-28 04:29:29 +00001895
Chris Lattner1aee61a2009-04-27 21:25:27 +00001896 if (FixItAtLocations.size() > 0) {
1897 // Even without the "-fixit" flag, with may have some specific
1898 // locations where the user has requested fixes. Process those
1899 // locations now.
1900 if (!FixItRewrite)
1901 FixItRewrite = new FixItRewriter(PP.getDiagnostics(),
1902 PP.getSourceManager(),
1903 PP.getLangOptions());
Chris Lattner9ecd26a2009-03-28 01:37:17 +00001904
Chris Lattner1aee61a2009-04-27 21:25:27 +00001905 bool AddedFixitLocation = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001906 for (unsigned Idx = 0, Last = FixItAtLocations.size();
Chris Lattner1aee61a2009-04-27 21:25:27 +00001907 Idx != Last; ++Idx) {
1908 RequestedSourceLocation Requested;
Argyrios Kyrtzidis34d25d82009-06-23 22:01:39 +00001909 if (ResolveParsedLocation(FixItAtLocations[Idx],
1910 PP.getFileManager(), Requested)) {
Chris Lattner1aee61a2009-04-27 21:25:27 +00001911 fprintf(stderr, "FIX-IT could not find file \"%s\"\n",
1912 FixItAtLocations[Idx].FileName.c_str());
1913 } else {
1914 FixItRewrite->addFixItLocation(Requested);
1915 AddedFixitLocation = true;
Douglas Gregor26df2f02009-04-02 19:05:20 +00001916 }
1917 }
1918
Chris Lattner1aee61a2009-04-27 21:25:27 +00001919 if (!AddedFixitLocation) {
1920 // All of the fix-it locations were bad. Don't fix anything.
1921 delete FixItRewrite;
1922 FixItRewrite = 0;
1923 }
1924 }
1925
1926 llvm::OwningPtr<ASTContext> ContextOwner;
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001927 if (Consumer)
Chris Lattner9ecd26a2009-03-28 01:37:17 +00001928 ContextOwner.reset(new ASTContext(PP.getLangOptions(),
1929 PP.getSourceManager(),
1930 PP.getTargetInfo(),
1931 PP.getIdentifierTable(),
1932 PP.getSelectorTable(),
Chris Lattner1b63e4f2009-06-14 01:54:56 +00001933 PP.getBuiltinInfo(),
Douglas Gregor2deaea32009-04-22 18:49:13 +00001934 /* FreeMemory = */ !DisableFree,
Chris Lattner1b63e4f2009-06-14 01:54:56 +00001935 /* size_reserve = */0));
Mike Stump1eb44332009-09-09 15:08:12 +00001936
Chris Lattnercc7dea82009-04-27 22:02:30 +00001937 llvm::OwningPtr<PCHReader> Reader;
1938 llvm::OwningPtr<ExternalASTSource> Source;
Mike Stump1eb44332009-09-09 15:08:12 +00001939
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001940 if (!ImplicitIncludePCH.empty()) {
Douglas Gregore650c8c2009-07-07 00:12:59 +00001941 // If the user specified -isysroot, it will be used for relocatable PCH
1942 // files.
1943 const char *isysrootPCH = 0;
1944 if (isysroot.getNumOccurrences() != 0)
1945 isysrootPCH = isysroot.c_str();
Mike Stump1eb44332009-09-09 15:08:12 +00001946
Douglas Gregore650c8c2009-07-07 00:12:59 +00001947 Reader.reset(new PCHReader(PP, ContextOwner.get(), isysrootPCH));
Mike Stump1eb44332009-09-09 15:08:12 +00001948
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001949 // The user has asked us to include a precompiled header. Load
1950 // the precompiled header into the AST context.
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001951 switch (Reader->ReadPCH(ImplicitIncludePCH)) {
1952 case PCHReader::Success: {
Douglas Gregore721f952009-04-28 18:58:38 +00001953 // Set the predefines buffer as suggested by the PCH
1954 // reader. Typically, the predefines buffer will be empty.
1955 PP.setPredefines(Reader->getSuggestedPredefines());
1956
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001957 // Attach the PCH reader to the AST context as an external AST
1958 // source, so that declarations will be deserialized from the
1959 // PCH file as needed.
Chris Lattnercc7dea82009-04-27 22:02:30 +00001960 if (ContextOwner) {
1961 Source.reset(Reader.take());
Douglas Gregore1d918e2009-04-10 23:10:45 +00001962 ContextOwner->setExternalSource(Source);
Chris Lattnercc7dea82009-04-27 22:02:30 +00001963 }
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001964 break;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001965 }
1966
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001967 case PCHReader::Failure:
1968 // Unrecoverable failure: don't even try to process the input
1969 // file.
1970 return;
1971
1972 case PCHReader::IgnorePCH:
Douglas Gregor1ab86ac2009-04-28 22:01:16 +00001973 // No suitable PCH file could be found. Return an error.
1974 return;
1975
1976#if 0
1977 // FIXME: We can recover from failed attempts to load PCH
1978 // files. This code will do so, if we ever want to enable it.
1979
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001980 // We delayed the initialization of builtins in the hope of
1981 // loading the PCH file. Since the PCH file could not be
1982 // loaded, initialize builtins now.
1983 if (ContextOwner)
1984 ContextOwner->InitializeBuiltins(PP.getIdentifierTable());
Douglas Gregor1ab86ac2009-04-28 22:01:16 +00001985#endif
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001986 }
1987
1988 // Finish preprocessor initialization. We do this now (rather
1989 // than earlier) because this initialization creates new source
1990 // location entries in the source manager, which must come after
1991 // the source location entries for the PCH file.
1992 if (InitializeSourceManager(PP, InFile))
1993 return;
Ted Kremenek46157b52009-01-28 04:29:29 +00001994 }
Daniel Dunbarbea5a842009-10-29 01:53:18 +00001995
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001996 // If we have an ASTConsumer, run the parser with it.
Douglas Gregor81b747b2009-09-17 21:32:03 +00001997 if (Consumer) {
1998 CodeCompleteConsumer *(*CreateCodeCompleter)(Sema &, void *) = 0;
1999 void *CreateCodeCompleterData = 0;
Daniel Dunbarbea5a842009-10-29 01:53:18 +00002000
Douglas Gregorb657f112009-09-22 21:11:38 +00002001 if (!CodeCompletionAt.FileName.empty()) {
2002 // Tell the source manager to chop off the given file at a specific
2003 // line and column.
Daniel Dunbarbea5a842009-10-29 01:53:18 +00002004 if (const FileEntry *Entry
Douglas Gregorb657f112009-09-22 21:11:38 +00002005 = PP.getFileManager().getFile(CodeCompletionAt.FileName)) {
2006 // Truncate the named file at the given line/column.
2007 PP.getSourceManager().truncateFileAt(Entry, CodeCompletionAt.Line,
2008 CodeCompletionAt.Column);
Daniel Dunbarbea5a842009-10-29 01:53:18 +00002009
Douglas Gregorb657f112009-09-22 21:11:38 +00002010 // Set up the creation routine for code-completion.
2011 CreateCodeCompleter = BuildPrintingCodeCompleter;
2012 } else {
Daniel Dunbarbea5a842009-10-29 01:53:18 +00002013 PP.getDiagnostics().Report(FullSourceLoc(),
Douglas Gregorb657f112009-09-22 21:11:38 +00002014 diag::err_fe_invalid_code_complete_file)
2015 << CodeCompletionAt.FileName;
2016 }
Douglas Gregor81b747b2009-09-17 21:32:03 +00002017 }
2018
Mike Stump1eb44332009-09-09 15:08:12 +00002019 ParseAST(PP, Consumer.get(), *ContextOwner.get(), Stats,
Douglas Gregor81b747b2009-09-17 21:32:03 +00002020 CompleteTranslationUnit,
2021 CreateCodeCompleter, CreateCodeCompleterData);
2022 }
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002023
Daniel Dunbar593c41f2009-11-04 23:41:40 +00002024 // Perform post processing actions and actions which don't use a consumer.
2025 switch (PA) {
2026 default: break;
2027
2028 case RunPreprocessorOnly: { // Just lex as fast as we can, no output.
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002029 llvm::TimeRegion Timer(ClangFrontendTimer);
2030 Token Tok;
2031 // Start parsing the specified input file.
2032 PP.EnterMainSourceFile();
2033 do {
2034 PP.Lex(Tok);
2035 } while (Tok.isNot(tok::eof));
2036 ClearSourceMgr = true;
Daniel Dunbar593c41f2009-11-04 23:41:40 +00002037 break;
2038 }
2039
2040 case ParseNoop: {
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002041 llvm::TimeRegion Timer(ClangFrontendTimer);
2042 ParseFile(PP, new MinimalAction(PP));
2043 ClearSourceMgr = true;
Daniel Dunbar593c41f2009-11-04 23:41:40 +00002044 break;
2045 }
2046
2047 case PrintPreprocessedInput: {
Chris Lattnercc7dea82009-04-27 22:02:30 +00002048 llvm::TimeRegion Timer(ClangFrontendTimer);
Eli Friedman12d3b1d2009-05-19 03:06:47 +00002049 if (DumpMacros)
2050 DoPrintMacros(PP, OS.get());
2051 else
2052 DoPrintPreprocessedInput(PP, OS.get(), EnableCommentOutput,
2053 EnableMacroCommentOutput,
2054 DisableLineMarkers, DumpDefines);
Chris Lattnercc7dea82009-04-27 22:02:30 +00002055 ClearSourceMgr = true;
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002056 }
Mike Stump1eb44332009-09-09 15:08:12 +00002057
Daniel Dunbar593c41f2009-11-04 23:41:40 +00002058 }
2059
Chris Lattner1aee61a2009-04-27 21:25:27 +00002060 if (FixItRewrite)
2061 FixItRewrite->WriteFixedFile(InFile, OutputFile);
Daniel Dunbar70186ab2009-07-29 02:40:09 +00002062
2063 // Disable the consumer prior to the context, the consumer may perform actions
2064 // in its destructor which require the context.
2065 if (DisableFree)
2066 Consumer.take();
2067 else
2068 Consumer.reset();
Mike Stump1eb44332009-09-09 15:08:12 +00002069
Chris Lattner1aee61a2009-04-27 21:25:27 +00002070 // If in -disable-free mode, don't deallocate ASTContext.
2071 if (DisableFree)
2072 ContextOwner.take();
2073 else
2074 ContextOwner.reset(); // Delete ASTContext
Eli Friedman66d6f042009-05-18 22:20:00 +00002075
Daniel Dunbar879c3ea2008-10-27 22:03:52 +00002076 if (VerifyDiagnostics)
Daniel Dunbar276373d2008-10-27 22:10:13 +00002077 if (CheckDiagnostics(PP))
2078 exit(1);
Chris Lattnere66b65c2008-02-06 01:42:25 +00002079
Reid Spencer5f016e22007-07-11 17:01:13 +00002080 if (Stats) {
Ted Kremenekfdfc1982007-12-19 22:24:34 +00002081 fprintf(stderr, "\nSTATISTICS FOR '%s':\n", InFile.c_str());
Reid Spencer5f016e22007-07-11 17:01:13 +00002082 PP.PrintStats();
2083 PP.getIdentifierTable().PrintStats();
Chris Lattnerdee73592007-12-15 20:48:40 +00002084 PP.getHeaderSearchInfo().PrintStats();
Ted Kremenek1b95a652009-01-09 18:20:21 +00002085 PP.getSourceManager().PrintStats();
Reid Spencer5f016e22007-07-11 17:01:13 +00002086 fprintf(stderr, "\n");
2087 }
Chris Lattnerbd247762007-07-22 06:05:44 +00002088
Mike Stump1eb44332009-09-09 15:08:12 +00002089 // For a multi-file compilation, some things are ok with nuking the source
Chris Lattnerbd247762007-07-22 06:05:44 +00002090 // manager tables, other require stable fileid/macroid's across multiple
2091 // files.
Chris Lattnerdee73592007-12-15 20:48:40 +00002092 if (ClearSourceMgr)
2093 PP.getSourceManager().clearIDTables();
Daniel Dunbard68ba0e2008-11-11 06:35:39 +00002094
Eli Friedman66d6f042009-05-18 22:20:00 +00002095 // Always delete the output stream because we don't want to leak file
2096 // handles. Also, we don't want to try to erase an open file.
2097 OS.reset();
2098
Daniel Dunbar8cb65622009-10-29 21:05:18 +00002099 // If we had errors, try to erase the output file.
2100 if (PP.getDiagnostics().getNumErrors() && !OutPath.isEmpty())
Eli Friedman66d6f042009-05-18 22:20:00 +00002101 OutPath.eraseFromDisk();
Reid Spencer5f016e22007-07-11 17:01:13 +00002102}
2103
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +00002104/// ProcessInputFile - Process a single AST input file with the specified state.
2105///
2106static void ProcessASTInputFile(const std::string &InFile, ProgActions PA,
2107 const llvm::StringMap<bool> &Features,
2108 Diagnostic &Diags, FileManager &FileMgr,
2109 llvm::LLVMContext& Context) {
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +00002110 std::string Error;
Steve Naroff36c44642009-10-19 14:34:22 +00002111 llvm::OwningPtr<ASTUnit> AST(ASTUnit::LoadFromPCHFile(InFile, &Error));
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +00002112 if (!AST) {
2113 Diags.Report(FullSourceLoc(), diag::err_fe_invalid_ast_file) << Error;
2114 return;
2115 }
2116
2117 Preprocessor &PP = AST->getPreprocessor();
2118
2119 llvm::OwningPtr<llvm::raw_ostream> OS;
2120 llvm::sys::Path OutPath;
2121 llvm::OwningPtr<ASTConsumer> Consumer(CreateConsumerAction(PP, InFile, PA, OS,
2122 OutPath, Features,
2123 Context));
2124
2125 if (!Consumer.get()) {
2126 Diags.Report(FullSourceLoc(), diag::err_fe_invalid_ast_action);
2127 return;
2128 }
2129
Daniel Dunbara674bf42009-09-21 03:03:56 +00002130 // Set the main file ID to an empty file.
2131 //
2132 // FIXME: We probably shouldn't need this, but for now this is the simplest
2133 // way to reuse the logic in ParseAST.
2134 const char *EmptyStr = "";
2135 llvm::MemoryBuffer *SB =
2136 llvm::MemoryBuffer::getMemBuffer(EmptyStr, EmptyStr, "<dummy input>");
2137 AST->getSourceManager().createMainFileIDForMemBuffer(SB);
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +00002138
Daniel Dunbara674bf42009-09-21 03:03:56 +00002139 // Stream the input AST to the consumer.
Daniel Dunbarefcbe942009-11-05 02:42:12 +00002140 Diags.getClient()->BeginSourceFile(PP.getLangOptions());
Daniel Dunbara674bf42009-09-21 03:03:56 +00002141 ParseAST(PP, Consumer.get(), AST->getASTContext(), Stats);
Daniel Dunbarefcbe942009-11-05 02:42:12 +00002142 Diags.getClient()->EndSourceFile();
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +00002143
2144 // Release the consumer and the AST, in that order since the consumer may
2145 // perform actions in its destructor which require the context.
2146 if (DisableFree) {
2147 Consumer.take();
2148 AST.take();
2149 } else {
2150 Consumer.reset();
2151 AST.reset();
2152 }
2153
2154 // Always delete the output stream because we don't want to leak file
2155 // handles. Also, we don't want to try to erase an open file.
2156 OS.reset();
2157
Daniel Dunbar8cb65622009-10-29 21:05:18 +00002158 // If we had errors, try to erase the output file.
2159 if (PP.getDiagnostics().getNumErrors() && !OutPath.isEmpty())
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +00002160 OutPath.eraseFromDisk();
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +00002161}
2162
Reid Spencer5f016e22007-07-11 17:01:13 +00002163static llvm::cl::list<std::string>
2164InputFilenames(llvm::cl::Positional, llvm::cl::desc("<input files>"));
2165
Daniel Dunbar70121eb2009-08-10 03:40:28 +00002166static void LLVMErrorHandler(void *UserData, const std::string &Message) {
2167 Diagnostic &Diags = *static_cast<Diagnostic*>(UserData);
2168
2169 Diags.Report(FullSourceLoc(), diag::err_fe_error_backend) << Message;
2170
2171 // We cannot recover from llvm errors.
2172 exit(1);
2173}
2174
Reid Spencer5f016e22007-07-11 17:01:13 +00002175int main(int argc, char **argv) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002176 llvm::sys::PrintStackTraceOnErrorSignal();
Chris Lattner09e94a32009-03-04 21:41:39 +00002177 llvm::PrettyStackTraceProgram X(argc, argv);
Owen Andersond7200462009-07-16 00:14:12 +00002178 llvm::LLVMContext &Context = llvm::getGlobalContext();
Daniel Dunbard6970812009-09-02 23:20:15 +00002179
Daniel Dunbar4d861512009-09-03 04:54:12 +00002180 // Initialize targets first, so that --version shows registered targets.
Chris Lattner2fe11942009-06-17 17:25:50 +00002181 llvm::InitializeAllTargets();
2182 llvm::InitializeAllAsmPrinters();
Daniel Dunbard6970812009-09-02 23:20:15 +00002183
2184 llvm::cl::ParseCommandLineOptions(argc, argv,
2185 "LLVM 'Clang' Compiler: http://clang.llvm.org\n");
Mike Stump1eb44332009-09-09 15:08:12 +00002186
Chris Lattner47099742009-02-18 01:51:21 +00002187 if (TimeReport)
2188 ClangFrontendTimer = new llvm::Timer("Clang front-end time");
Mike Stump1eb44332009-09-09 15:08:12 +00002189
Daniel Dunbar08e6dc62009-05-28 16:37:33 +00002190 if (Verbose)
Mike Stump3cbf5a02009-09-15 21:49:22 +00002191 llvm::errs() << "clang-cc version " CLANG_VERSION_STRING
2192 << " based upon " << PACKAGE_STRING
Daniel Dunbar2e30e592009-09-04 17:43:10 +00002193 << " hosted on " << llvm::sys::getHostTriple() << "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00002194
Reid Spencer5f016e22007-07-11 17:01:13 +00002195 // If no input was specified, read from stdin.
2196 if (InputFilenames.empty())
2197 InputFilenames.push_back("-");
Douglas Gregor68a0d782009-05-02 00:03:46 +00002198
Daniel Dunbareace8742009-11-04 06:24:30 +00002199 // Initialize the diagnostic options.
2200 DiagOpts.ShowColumn = !NoShowColumn;
2201 DiagOpts.ShowLocation = !NoShowLocation;
2202 DiagOpts.ShowCarets = !NoCaretDiagnostics;
2203 DiagOpts.ShowFixits = !NoDiagnosticsFixIt;
2204 DiagOpts.ShowSourceRanges = PrintSourceRangeInfo;
2205 DiagOpts.ShowOptionNames = PrintDiagnosticOption;
Daniel Dunbar838be482009-11-04 06:24:57 +00002206 DiagOpts.ShowColors = PrintColorDiagnostic;
Daniel Dunbareace8742009-11-04 06:24:30 +00002207 DiagOpts.MessageLength = MessageLength;
2208
Ted Kremenek31e703b2007-12-11 23:28:38 +00002209 // Create the diagnostic client for reporting errors or for
2210 // implementing -verify.
Chris Lattner409d4e72009-04-17 20:40:01 +00002211 llvm::OwningPtr<DiagnosticClient> DiagClient;
2212 if (VerifyDiagnostics) {
2213 // When checking diagnostics, just buffer them up.
2214 DiagClient.reset(new TextDiagnosticBuffer());
2215 if (InputFilenames.size() != 1) {
2216 fprintf(stderr, "-verify only works on single input files for now.\n");
2217 return 1;
2218 }
Ted Kremenekb4398aa2008-08-07 17:49:57 +00002219 } else {
Daniel Dunbarad451cc2009-11-05 02:11:37 +00002220 DiagClient.reset(new TextDiagnosticPrinter(llvm::errs(), DiagOpts));
Reid Spencer5f016e22007-07-11 17:01:13 +00002221 }
Mike Stump1eb44332009-09-09 15:08:12 +00002222
Daniel Dunbarad451cc2009-11-05 02:11:37 +00002223 if (!DumpBuildInformation.empty())
Chris Lattner75a97cb2009-04-17 21:05:01 +00002224 SetUpBuildDumpLog(argc, argv, DiagClient);
Ted Kremenekb4398aa2008-08-07 17:49:57 +00002225
Reid Spencer5f016e22007-07-11 17:01:13 +00002226 // Configure our handling of diagnostics.
Ted Kremenekb4398aa2008-08-07 17:49:57 +00002227 Diagnostic Diags(DiagClient.get());
Eli Friedman0eeb86e2009-05-19 01:17:04 +00002228 if (ProcessWarningOptions(Diags, OptWarnings, OptPedantic, OptPedanticErrors,
2229 OptNoWarnings))
Sebastian Redl63a9e0f2009-03-06 17:41:35 +00002230 return 1;
Ted Kremenek31e703b2007-12-11 23:28:38 +00002231
Daniel Dunbar70121eb2009-08-10 03:40:28 +00002232 // Set an error handler, so that any LLVM backend diagnostics go through our
2233 // error handler.
2234 llvm::llvm_install_error_handler(LLVMErrorHandler,
2235 static_cast<void*>(&Diags));
2236
Daniel Dunbar7c15e712009-10-30 18:12:31 +00002237 // Initialize base triple. If a -triple option has been specified, use
2238 // that triple. Otherwise, default to the host triple.
2239 llvm::Triple Triple(TargetTriple);
2240 if (Triple.getTriple().empty())
2241 Triple = llvm::Triple(llvm::sys::getHostTriple());
2242
Chris Lattner11215192008-03-14 06:12:05 +00002243 // Get information about the target being compiled for.
Daniel Dunbarbea5a842009-10-29 01:53:18 +00002244 llvm::OwningPtr<TargetInfo>
Chris Lattner2f60af72009-09-12 22:45:58 +00002245 Target(TargetInfo::CreateTargetInfo(Triple.getTriple()));
Mike Stump1eb44332009-09-09 15:08:12 +00002246
Chris Lattner11215192008-03-14 06:12:05 +00002247 if (Target == 0) {
Mike Stump1eb44332009-09-09 15:08:12 +00002248 Diags.Report(FullSourceLoc(), diag::err_fe_unknown_triple)
Chris Lattner2f60af72009-09-12 22:45:58 +00002249 << Triple.getTriple().c_str();
Sebastian Redlc5613db2009-03-07 12:09:25 +00002250 return 1;
Chris Lattner11215192008-03-14 06:12:05 +00002251 }
Mike Stump1eb44332009-09-09 15:08:12 +00002252
Daniel Dunbar73b79592009-09-14 00:02:12 +00002253 // Set the target ABI if specified.
2254 if (!TargetABI.empty()) {
2255 if (!Target->setABI(TargetABI)) {
2256 Diags.Report(FullSourceLoc(), diag::err_fe_unknown_target_abi)
2257 << TargetABI;
2258 return 1;
2259 }
2260 }
2261
Daniel Dunbard4270232009-01-20 23:17:32 +00002262 if (!InheritanceViewCls.empty()) // C++ visualization?
Ted Kremenek7cae2f62008-10-23 23:36:29 +00002263 ProgAction = InheritanceView;
Mike Stump1eb44332009-09-09 15:08:12 +00002264
Daniel Dunbar4cc1a252009-11-05 01:53:23 +00002265 // Create the source manager.
2266 SourceManager SourceMgr;
Mike Stump1eb44332009-09-09 15:08:12 +00002267
Chris Lattner2c78b872009-04-14 23:22:57 +00002268 // Create a file manager object to provide access to and cache the filesystem.
2269 FileManager FileMgr;
Douglas Gregor4fed3f42009-04-27 18:38:38 +00002270
Daniel Dunbar868bd0a2009-05-06 03:16:41 +00002271 // Compute the feature set, unfortunately this effects the language!
2272 llvm::StringMap<bool> Features;
2273 ComputeFeatureMap(Target.get(), Features);
2274
Reid Spencer5f016e22007-07-11 17:01:13 +00002275 for (unsigned i = 0, e = InputFilenames.size(); i != e; ++i) {
Ted Kremenek31e703b2007-12-11 23:28:38 +00002276 const std::string &InFile = InputFilenames[i];
Mike Stump1eb44332009-09-09 15:08:12 +00002277
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +00002278 LangKind LK = GetLanguage(InFile);
2279 // AST inputs are handled specially.
2280 if (LK == langkind_ast) {
2281 ProcessASTInputFile(InFile, ProgAction, Features,
2282 Diags, FileMgr, Context);
2283 continue;
2284 }
2285
Daniel Dunbar4cc1a252009-11-05 01:53:23 +00002286 // Reset the ID tables if we are reusing the SourceManager.
2287 if (i)
2288 SourceMgr.clearIDTables();
Mike Stump1eb44332009-09-09 15:08:12 +00002289
Chris Lattnerf63aea32009-03-04 21:40:56 +00002290 // Initialize language options, inferring file types from input filenames.
2291 LangOptions LangInfo;
Mike Stump1eb44332009-09-09 15:08:12 +00002292
Daniel Dunbar0b5b0da2009-04-01 05:09:09 +00002293 InitializeLangOptions(LangInfo, LK);
Daniel Dunbar868bd0a2009-05-06 03:16:41 +00002294 InitializeLanguageStandard(LangInfo, LK, Target.get(), Features);
Mike Stump1eb44332009-09-09 15:08:12 +00002295
Chris Lattnerf63aea32009-03-04 21:40:56 +00002296 // Process the -I options and set them in the HeaderInfo.
2297 HeaderSearch HeaderInfo(FileMgr);
Mike Stump1eb44332009-09-09 15:08:12 +00002298
2299
Mike Stump43d81762009-10-08 23:29:47 +00002300 InitializeIncludePaths(argv[0], HeaderInfo, FileMgr, LangInfo, Triple);
Mike Stump1eb44332009-09-09 15:08:12 +00002301
Chris Lattnerf63aea32009-03-04 21:40:56 +00002302 // Set up the preprocessor with these options.
Daniel Dunbar90b18272009-11-04 23:56:25 +00002303 llvm::OwningPtr<Preprocessor> PP(CreatePreprocessor(Diags, LangInfo,
Daniel Dunbar4cc1a252009-11-05 01:53:23 +00002304 *Target, SourceMgr,
Daniel Dunbar90b18272009-11-04 23:56:25 +00002305 HeaderInfo));
Ted Kremenekb4398aa2008-08-07 17:49:57 +00002306
Daniel Dunbar8cb65622009-10-29 21:05:18 +00002307 // Handle generating dependencies, if requested.
Eli Friedmanb5c8f8b2009-05-19 03:35:57 +00002308 if (!DependencyFile.empty()) {
Eli Friedmanb5c8f8b2009-05-19 03:35:57 +00002309 if (DependencyTargets.empty()) {
Daniel Dunbar8cb65622009-10-29 21:05:18 +00002310 Diags.Report(FullSourceLoc(), diag::err_fe_dependency_file_requires_MT);
Eli Friedmanb5c8f8b2009-05-19 03:35:57 +00002311 continue;
2312 }
2313 std::string ErrStr;
Daniel Dunbar8cb65622009-10-29 21:05:18 +00002314 llvm::raw_ostream *DependencyOS =
Dan Gohmanb044c472009-08-25 15:36:09 +00002315 new llvm::raw_fd_ostream(DependencyFile.c_str(), ErrStr);
Eli Friedmanb5c8f8b2009-05-19 03:35:57 +00002316 if (!ErrStr.empty()) {
Daniel Dunbar8cb65622009-10-29 21:05:18 +00002317 Diags.Report(FullSourceLoc(), diag::err_fe_error_opening)
2318 << DependencyFile << ErrStr;
Eli Friedmanb5c8f8b2009-05-19 03:35:57 +00002319 continue;
2320 }
2321
2322 AttachDependencyFileGen(PP.get(), DependencyOS, DependencyTargets,
2323 DependenciesIncludeSystemHeaders,
2324 PhonyDependencyTarget);
2325 }
2326
Chris Lattner1b63e4f2009-06-14 01:54:56 +00002327 if (ImplicitIncludePCH.empty()) {
2328 if (InitializeSourceManager(*PP.get(), InFile))
2329 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00002330
Chris Lattner1b63e4f2009-06-14 01:54:56 +00002331 // Initialize builtin info.
2332 PP->getBuiltinInfo().InitializeBuiltins(PP->getIdentifierTable(),
Chris Lattner1b63e4f2009-06-14 01:54:56 +00002333 PP->getLangOptions().NoBuiltin);
2334 }
Douglas Gregor14f79002009-04-10 03:52:48 +00002335
Chris Lattnerf63aea32009-03-04 21:40:56 +00002336 // Process the source file.
Daniel Dunbarefcbe942009-11-05 02:42:12 +00002337 DiagClient->BeginSourceFile(LangInfo);
Daniel Dunbar90b18272009-11-04 23:56:25 +00002338 ProcessInputFile(*PP, InFile, ProgAction, Features, Context);
Daniel Dunbarefcbe942009-11-05 02:42:12 +00002339 DiagClient->EndSourceFile();
Mike Stump1eb44332009-09-09 15:08:12 +00002340
Chris Lattner40469652009-04-17 20:16:08 +00002341 HeaderInfo.ClearFileInfo();
Reid Spencer5f016e22007-07-11 17:01:13 +00002342 }
Chris Lattner11215192008-03-14 06:12:05 +00002343
Mike Stumpfc0fed32009-04-28 01:19:10 +00002344 if (!NoCaretDiagnostics)
2345 if (unsigned NumDiagnostics = Diags.getNumDiagnostics())
2346 fprintf(stderr, "%d diagnostic%s generated.\n", NumDiagnostics,
2347 (NumDiagnostics == 1 ? "" : "s"));
Mike Stump1eb44332009-09-09 15:08:12 +00002348
Reid Spencer5f016e22007-07-11 17:01:13 +00002349 if (Stats) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002350 FileMgr.PrintStats();
2351 fprintf(stderr, "\n");
2352 }
Chris Lattner75a97cb2009-04-17 21:05:01 +00002353
2354 delete ClangFrontendTimer;
2355 delete BuildLogFile;
Mike Stump1eb44332009-09-09 15:08:12 +00002356
Daniel Dunbar276373d2008-10-27 22:10:13 +00002357 // If verifying diagnostics and we reached here, all is well.
2358 if (VerifyDiagnostics)
2359 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002360
Daniel Dunbar524b86f2008-10-28 00:38:08 +00002361 // Managed static deconstruction. Useful for making things like
2362 // -time-passes usable.
2363 llvm::llvm_shutdown();
2364
Daniel Dunbar8cb65622009-10-29 21:05:18 +00002365 return (Diags.getNumErrors() != 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00002366}