blob: 06ae4edf0ee05e598c9fb418ee0eeeb86e8da436 [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 Dunbare1bd4e62009-03-02 06:16:29 +000032#include "clang/Frontend/InitHeaderSearch.h"
Chris Lattnere116ccf2009-04-21 05:40:52 +000033#include "clang/Frontend/InitPreprocessor.h"
Daniel Dunbar50f4f462009-03-12 10:14:16 +000034#include "clang/Frontend/PathDiagnosticClients.h"
Douglas Gregor2cf26342009-04-09 22:27:44 +000035#include "clang/Frontend/PCHReader.h"
Daniel Dunbare1bd4e62009-03-02 06:16:29 +000036#include "clang/Frontend/TextDiagnosticBuffer.h"
37#include "clang/Frontend/TextDiagnosticPrinter.h"
Argyrios Kyrtzidis34d25d82009-06-23 22:01:39 +000038#include "clang/Frontend/CommandLineSourceLoc.h"
Eli Friedmanb09f6e12009-05-19 04:14:29 +000039#include "clang/Frontend/Utils.h"
Ted Kremenek88f5cde2008-03-27 06:17:42 +000040#include "clang/Analysis/PathDiagnostic.h"
Chris Lattner8ee3c032008-02-06 02:01:47 +000041#include "clang/CodeGen/ModuleBuilder.h"
Douglas Gregor81b747b2009-09-17 21:32:03 +000042#include "clang/Sema/CodeCompleteConsumer.h"
Chris Lattnere91c1342008-02-06 00:23:21 +000043#include "clang/Sema/ParseAST.h"
Chris Lattner88eccaf2009-01-29 06:55:46 +000044#include "clang/Sema/SemaDiagnostic.h"
Chris Lattner556beb72007-09-15 22:56:56 +000045#include "clang/AST/ASTConsumer.h"
Chris Lattner1266eca2009-03-28 04:31:31 +000046#include "clang/AST/ASTContext.h"
47#include "clang/AST/Decl.h"
Chris Lattner682bf922009-03-29 16:50:03 +000048#include "clang/AST/DeclGroup.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000049#include "clang/Parse/Parser.h"
50#include "clang/Lex/HeaderSearch.h"
Chris Lattnerdb766842009-02-06 04:16:41 +000051#include "clang/Lex/LexDiagnostic.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000052#include "clang/Basic/FileManager.h"
53#include "clang/Basic/SourceManager.h"
54#include "clang/Basic/TargetInfo.h"
Daniel Dunbaraa338bc2009-05-06 04:07:06 +000055#include "clang/Basic/Version.h"
Owen Anderson42253cc2009-07-01 17:00:06 +000056#include "llvm/LLVMContext.h"
Chris Lattnerba0f25f2008-09-30 20:16:56 +000057#include "llvm/ADT/OwningPtr.h"
Chris Lattner8f3dab82007-12-15 23:20:07 +000058#include "llvm/ADT/SmallPtrSet.h"
Chris Lattnerba0f25f2008-09-30 20:16:56 +000059#include "llvm/ADT/StringExtras.h"
Daniel Dunbar868bd0a2009-05-06 03:16:41 +000060#include "llvm/ADT/StringMap.h"
Chris Lattnerb8e240e2009-04-08 18:24:34 +000061#include "llvm/ADT/STLExtras.h"
Chris Lattnerba0f25f2008-09-30 20:16:56 +000062#include "llvm/Config/config.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000063#include "llvm/Support/CommandLine.h"
Daniel Dunbar70121eb2009-08-10 03:40:28 +000064#include "llvm/Support/ErrorHandling.h"
Daniel Dunbar524b86f2008-10-28 00:38:08 +000065#include "llvm/Support/ManagedStatic.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000066#include "llvm/Support/MemoryBuffer.h"
Zhongxing Xu20922362008-11-26 05:23:17 +000067#include "llvm/Support/PluginLoader.h"
Chris Lattner09e94a32009-03-04 21:41:39 +000068#include "llvm/Support/PrettyStackTrace.h"
Chris Lattner47099742009-02-18 01:51:21 +000069#include "llvm/Support/Timer.h"
Chris Lattner0fa0daa2009-08-24 04:11:30 +000070#include "llvm/Support/raw_ostream.h"
Daniel Dunbare553a722008-10-02 01:21:33 +000071#include "llvm/System/Host.h"
Chris Lattnerdcaa0962008-03-03 03:16:03 +000072#include "llvm/System/Path.h"
Eli Friedman66d6f042009-05-18 22:20:00 +000073#include "llvm/System/Program.h"
Chris Lattnerba0f25f2008-09-30 20:16:56 +000074#include "llvm/System/Signals.h"
Chris Lattner2fe11942009-06-17 17:25:50 +000075#include "llvm/Target/TargetSelect.h"
Douglas Gregor26df2f02009-04-02 19:05:20 +000076#include <cstdlib>
Douglas Gregor44cf08e2009-05-03 03:52:38 +000077#if HAVE_SYS_TYPES_H
Douglas Gregor68a0d782009-05-02 00:03:46 +000078# include <sys/types.h>
79#endif
Douglas Gregor26df2f02009-04-02 19:05:20 +000080
Reid Spencer5f016e22007-07-11 17:01:13 +000081using namespace clang;
82
83//===----------------------------------------------------------------------===//
Douglas Gregor26df2f02009-04-02 19:05:20 +000084// Source Location Parser
85//===----------------------------------------------------------------------===//
86
Argyrios Kyrtzidis34d25d82009-06-23 22:01:39 +000087static bool ResolveParsedLocation(ParsedSourceLocation &ParsedLoc,
88 FileManager &FileMgr,
89 RequestedSourceLocation &Result) {
90 const FileEntry *File = FileMgr.getFile(ParsedLoc.FileName);
Douglas Gregor26df2f02009-04-02 19:05:20 +000091 if (!File)
92 return true;
93
94 Result.File = File;
Argyrios Kyrtzidis34d25d82009-06-23 22:01:39 +000095 Result.Line = ParsedLoc.Line;
96 Result.Column = ParsedLoc.Column;
Douglas Gregor26df2f02009-04-02 19:05:20 +000097 return false;
98}
99
Douglas Gregor26df2f02009-04-02 19:05:20 +0000100//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +0000101// Global options.
102//===----------------------------------------------------------------------===//
103
Chris Lattner47099742009-02-18 01:51:21 +0000104/// ClangFrontendTimer - The front-end activities should charge time to it with
105/// TimeRegion. The -ftime-report option controls whether this will do
106/// anything.
107llvm::Timer *ClangFrontendTimer = 0;
108
Reid Spencer5f016e22007-07-11 17:01:13 +0000109static llvm::cl::opt<bool>
110Verbose("v", llvm::cl::desc("Enable verbose output"));
111static llvm::cl::opt<bool>
Mike Stump1eb44332009-09-09 15:08:12 +0000112Stats("print-stats",
Nate Begemanaabbb122007-12-30 01:38:50 +0000113 llvm::cl::desc("Print performance metrics and statistics"));
Daniel Dunbard3db4012008-10-16 16:54:18 +0000114static llvm::cl::opt<bool>
115DisableFree("disable-free",
116 llvm::cl::desc("Disable freeing of memory on exit"),
117 llvm::cl::init(false));
Daniel Dunbar57cbfc02009-04-27 21:19:07 +0000118static llvm::cl::opt<bool>
Mike Stump1eb44332009-09-09 15:08:12 +0000119EmptyInputOnly("empty-input-only",
Daniel Dunbar57cbfc02009-04-27 21:19:07 +0000120 llvm::cl::desc("Force running on an empty input file"));
Reid Spencer5f016e22007-07-11 17:01:13 +0000121
122enum ProgActions {
Steve Naroffb29b4272008-04-14 22:03:09 +0000123 RewriteObjC, // ObjC->C Rewriter.
Steve Naroff13188952008-09-18 14:10:13 +0000124 RewriteBlocks, // ObjC->C Rewriter for Blocks.
Chris Lattnerb57e3d42008-05-08 06:52:13 +0000125 RewriteMacros, // Expand macros but not #includes.
Chris Lattnerb13c5ee2008-10-12 05:29:20 +0000126 RewriteTest, // Rewriter playground
Douglas Gregor558cb562009-04-02 01:08:08 +0000127 FixIt, // Fix-It Rewriter
Ted Kremenek13e479b2008-03-19 07:53:42 +0000128 HTMLTest, // HTML displayer testing stuff.
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000129 EmitAssembly, // Emit a .s file.
Reid Spencer5f016e22007-07-11 17:01:13 +0000130 EmitLLVM, // Emit a .ll file.
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +0000131 EmitBC, // Emit a .bc file.
Mike Stump1eb44332009-09-09 15:08:12 +0000132 EmitLLVMOnly, // Generate LLVM IR, but do not
Ted Kremenek6a340832008-03-18 21:19:49 +0000133 EmitHTML, // Translate input source into HTML.
Chris Lattner3b427b32007-10-11 00:18:28 +0000134 ASTPrint, // Parse ASTs and print them.
Douglas Gregoree75c052009-05-21 20:55:50 +0000135 ASTPrintXML, // Parse ASTs and print them in XML.
Chris Lattner3b427b32007-10-11 00:18:28 +0000136 ASTDump, // Parse ASTs and dump them.
137 ASTView, // Parse ASTs and view them in Graphviz.
Zhongxing Xu2d75d6f2009-01-13 01:29:24 +0000138 PrintDeclContext, // Print DeclContext and their Decls.
Anders Carlsson78762eb2009-09-24 18:54:49 +0000139 DumpRecordLayouts, // Dump record layout information.
Reid Spencer5f016e22007-07-11 17:01:13 +0000140 ParsePrintCallbacks, // Parse and print each callback.
141 ParseSyntaxOnly, // Parse and perform semantic analysis.
142 ParseNoop, // Parse with noop callbacks.
143 RunPreprocessorOnly, // Just lex, no output.
144 PrintPreprocessedInput, // -E mode.
Chris Lattnerc106c102008-10-12 05:03:36 +0000145 DumpTokens, // Dump out preprocessed tokens.
146 DumpRawTokens, // Dump out raw tokens.
Mike Stump1eb44332009-09-09 15:08:12 +0000147 RunAnalysis, // Run one or more source code analyses.
Douglas Gregorbf1bd6e2009-04-02 23:43:50 +0000148 GeneratePTH, // Generate pre-tokenized header.
Douglas Gregor2cf26342009-04-09 22:27:44 +0000149 GeneratePCH, // Generate pre-compiled header.
Ted Kremenek7cae2f62008-10-23 23:36:29 +0000150 InheritanceView // View C++ inheritance for a specified class.
Reid Spencer5f016e22007-07-11 17:01:13 +0000151};
152
Mike Stump1eb44332009-09-09 15:08:12 +0000153static llvm::cl::opt<ProgActions>
Reid Spencer5f016e22007-07-11 17:01:13 +0000154ProgAction(llvm::cl::desc("Choose output type:"), llvm::cl::ZeroOrMore,
155 llvm::cl::init(ParseSyntaxOnly),
156 llvm::cl::values(
157 clEnumValN(RunPreprocessorOnly, "Eonly",
158 "Just run preprocessor, no output (for timings)"),
159 clEnumValN(PrintPreprocessedInput, "E",
160 "Run preprocessor, emit preprocessed file"),
Chris Lattnerc106c102008-10-12 05:03:36 +0000161 clEnumValN(DumpRawTokens, "dump-raw-tokens",
162 "Lex file in raw mode and dump raw tokens"),
Daniel Dunbard4270232009-01-20 23:17:32 +0000163 clEnumValN(RunAnalysis, "analyze",
164 "Run static analysis engine"),
Chris Lattnerc106c102008-10-12 05:03:36 +0000165 clEnumValN(DumpTokens, "dump-tokens",
Reid Spencer5f016e22007-07-11 17:01:13 +0000166 "Run preprocessor, dump internal rep of tokens"),
167 clEnumValN(ParseNoop, "parse-noop",
168 "Run parser with noop callbacks (for timings)"),
169 clEnumValN(ParseSyntaxOnly, "fsyntax-only",
170 "Run parser and perform semantic analysis"),
171 clEnumValN(ParsePrintCallbacks, "parse-print-callbacks",
172 "Run parser and print each callback invoked"),
Ted Kremenek6a340832008-03-18 21:19:49 +0000173 clEnumValN(EmitHTML, "emit-html",
174 "Output input source as HTML"),
Chris Lattner3b427b32007-10-11 00:18:28 +0000175 clEnumValN(ASTPrint, "ast-print",
176 "Build ASTs and then pretty-print them"),
Douglas Gregoree75c052009-05-21 20:55:50 +0000177 clEnumValN(ASTPrintXML, "ast-print-xml",
178 "Build ASTs and then print them in XML format"),
Chris Lattner3b427b32007-10-11 00:18:28 +0000179 clEnumValN(ASTDump, "ast-dump",
180 "Build ASTs and then debug dump them"),
Chris Lattnerea254db2007-10-11 00:37:43 +0000181 clEnumValN(ASTView, "ast-view",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000182 "Build ASTs and view them with GraphViz"),
Zhongxing Xu2d75d6f2009-01-13 01:29:24 +0000183 clEnumValN(PrintDeclContext, "print-decl-contexts",
Ted Kremenek08478eb2009-04-01 00:23:28 +0000184 "Print DeclContexts and their Decls"),
Anders Carlsson78762eb2009-09-24 18:54:49 +0000185 clEnumValN(DumpRecordLayouts, "dump-record-layouts",
186 "Dump record layout information"),
Douglas Gregorbf1bd6e2009-04-02 23:43:50 +0000187 clEnumValN(GeneratePTH, "emit-pth",
Ted Kremenek08478eb2009-04-01 00:23:28 +0000188 "Generate pre-tokenized header file"),
Douglas Gregor2cf26342009-04-09 22:27:44 +0000189 clEnumValN(GeneratePCH, "emit-pch",
190 "Generate pre-compiled header file"),
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000191 clEnumValN(EmitAssembly, "S",
192 "Emit native assembly code"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000193 clEnumValN(EmitLLVM, "emit-llvm",
Ted Kremenek27b07c52007-09-06 21:26:58 +0000194 "Build ASTs then convert to LLVM, emit .ll file"),
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +0000195 clEnumValN(EmitBC, "emit-llvm-bc",
196 "Build ASTs then convert to LLVM, emit .bc file"),
Daniel Dunbare8e26002009-02-26 22:39:37 +0000197 clEnumValN(EmitLLVMOnly, "emit-llvm-only",
198 "Build ASTs and convert to LLVM, discarding output"),
Chris Lattnerb13c5ee2008-10-12 05:29:20 +0000199 clEnumValN(RewriteTest, "rewrite-test",
200 "Rewriter playground"),
Steve Naroffb29b4272008-04-14 22:03:09 +0000201 clEnumValN(RewriteObjC, "rewrite-objc",
Chris Lattnerb57e3d42008-05-08 06:52:13 +0000202 "Rewrite ObjC into C (code rewriter example)"),
203 clEnumValN(RewriteMacros, "rewrite-macros",
204 "Expand macros without full preprocessing"),
Steve Naroff13188952008-09-18 14:10:13 +0000205 clEnumValN(RewriteBlocks, "rewrite-blocks",
206 "Rewrite Blocks to C"),
Douglas Gregor558cb562009-04-02 01:08:08 +0000207 clEnumValN(FixIt, "fixit",
208 "Apply fix-it advice to the input source"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000209 clEnumValEnd));
210
Ted Kremenekccc76472007-12-19 19:47:59 +0000211
212static llvm::cl::opt<std::string>
213OutputFile("o",
Ted Kremenek50b56412007-12-19 19:50:41 +0000214 llvm::cl::value_desc("path"),
Douglas Gregor370187c2009-04-22 21:45:53 +0000215 llvm::cl::desc("Specify output file"));
Ted Kremenek55af98c2008-04-14 18:40:58 +0000216
Ted Kremenekc2e72992008-12-02 19:57:31 +0000217
Douglas Gregorb657f112009-09-22 21:11:38 +0000218static llvm::cl::opt<ParsedSourceLocation>
219CodeCompletionAt("code-completion-at",
220 llvm::cl::value_desc("file:line:column"),
221 llvm::cl::desc("Dump code-completion information at a location"));
Douglas Gregor81b747b2009-09-17 21:32:03 +0000222
223/// \brief Buld a new code-completion consumer that prints the results of
224/// code completion to standard output.
225static CodeCompleteConsumer *BuildPrintingCodeCompleter(Sema &S, void *) {
226 return new PrintingCodeCompleteConsumer(S, llvm::outs());
227}
228
Ted Kremenekc2e72992008-12-02 19:57:31 +0000229//===----------------------------------------------------------------------===//
230// PTH.
231//===----------------------------------------------------------------------===//
232
233static llvm::cl::opt<std::string>
234TokenCache("token-cache", llvm::cl::value_desc("path"),
235 llvm::cl::desc("Use specified token cache file"));
236
Sanjiv Guptae8b9f5b2008-05-08 08:54:20 +0000237//===----------------------------------------------------------------------===//
Ted Kremenek55af98c2008-04-14 18:40:58 +0000238// Diagnostic Options
239//===----------------------------------------------------------------------===//
240
Daniel Dunbareace8742009-11-04 06:24:30 +0000241static DiagnosticOptions DiagOpts;
242
Ted Kremenek41193e42007-09-26 19:42:19 +0000243static llvm::cl::opt<bool>
244VerifyDiagnostics("verify",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000245 llvm::cl::desc("Verify emitted diagnostics and warnings"));
Ted Kremenek41193e42007-09-26 19:42:19 +0000246
Nico Weberfd54ebc2008-08-05 23:33:20 +0000247static llvm::cl::opt<bool>
248NoShowColumn("fno-show-column",
249 llvm::cl::desc("Do not include column number on diagnostics"));
250
251static llvm::cl::opt<bool>
Chris Lattner65f5e642009-01-30 19:01:41 +0000252NoShowLocation("fno-show-source-location",
253 llvm::cl::desc("Do not include source location information with"
254 " diagnostics"));
255
256static llvm::cl::opt<bool>
Nico Weberfd54ebc2008-08-05 23:33:20 +0000257NoCaretDiagnostics("fno-caret-diagnostics",
258 llvm::cl::desc("Do not include source line and caret with"
259 " diagnostics"));
260
Chris Lattner1fbee5d2009-03-13 01:08:23 +0000261static llvm::cl::opt<bool>
Chris Lattneraa5bf2e2009-04-19 07:44:08 +0000262NoDiagnosticsFixIt("fno-diagnostics-fixit-info",
263 llvm::cl::desc("Do not include fixit information in"
264 " diagnostics"));
265
266static llvm::cl::opt<bool>
Chris Lattner182e0922009-04-21 05:34:31 +0000267PrintSourceRangeInfo("fdiagnostics-print-source-range-info",
268 llvm::cl::desc("Print source range spans in numeric form"));
269
Chris Lattnerd51d74a2009-04-16 05:44:38 +0000270static llvm::cl::opt<bool>
271PrintDiagnosticOption("fdiagnostics-show-option",
272 llvm::cl::desc("Print diagnostic name with mappable diagnostics"));
Nico Weberfd54ebc2008-08-05 23:33:20 +0000273
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000274static llvm::cl::opt<unsigned>
275MessageLength("fmessage-length",
Mike Stump1eb44332009-09-09 15:08:12 +0000276 llvm::cl::desc("Format message diagnostics so that they fit "
277 "within N columns or fewer, when possible."),
278 llvm::cl::value_desc("N"));
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000279
Torok Edwin603fca72009-06-04 07:18:23 +0000280static llvm::cl::opt<bool>
Daniel Dunbar838be482009-11-04 06:24:57 +0000281PrintColorDiagnostic("fcolor-diagnostics",
282 llvm::cl::desc("Use colors in diagnostics"));
283
Reid Spencer5f016e22007-07-11 17:01:13 +0000284//===----------------------------------------------------------------------===//
Ted Kremenek7cae2f62008-10-23 23:36:29 +0000285// C++ Visualization.
286//===----------------------------------------------------------------------===//
287
288static llvm::cl::opt<std::string>
289InheritanceViewCls("cxx-inheritance-view",
290 llvm::cl::value_desc("class name"),
Daniel Dunbard77b2512009-01-14 18:56:36 +0000291 llvm::cl::desc("View C++ inheritance for a specified class"));
Ted Kremenek7cae2f62008-10-23 23:36:29 +0000292
293//===----------------------------------------------------------------------===//
Douglas Gregor3573c0c2009-02-14 20:49:29 +0000294// Builtin Options
295//===----------------------------------------------------------------------===//
Chris Lattnerb2509e12009-02-18 01:12:43 +0000296
297static llvm::cl::opt<bool>
298TimeReport("ftime-report",
299 llvm::cl::desc("Print the amount of time each "
300 "phase of compilation takes"));
301
Douglas Gregor3573c0c2009-02-14 20:49:29 +0000302static llvm::cl::opt<bool>
303Freestanding("ffreestanding",
Daniel Dunbaref2abfe2009-02-16 22:43:43 +0000304 llvm::cl::desc("Assert that the compilation takes place in a "
Douglas Gregor3573c0c2009-02-14 20:49:29 +0000305 "freestanding environment"));
306
Daniel Dunbaref2abfe2009-02-16 22:43:43 +0000307static llvm::cl::opt<bool>
Daniel Dunbar48d1ef72009-04-07 21:16:11 +0000308AllowBuiltins("fbuiltin", llvm::cl::init(true),
309 llvm::cl::desc("Disable implicit builtin knowledge of functions"));
Chris Lattner7644f072009-03-13 22:38:49 +0000310
311
312static llvm::cl::opt<bool>
Daniel Dunbar48d1ef72009-04-07 21:16:11 +0000313MathErrno("fmath-errno", llvm::cl::init(true),
314 llvm::cl::desc("Require math functions to respect errno"));
Daniel Dunbaref2abfe2009-02-16 22:43:43 +0000315
Douglas Gregor3573c0c2009-02-14 20:49:29 +0000316//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +0000317// Language Options
318//===----------------------------------------------------------------------===//
319
320enum LangKind {
321 langkind_unspecified,
322 langkind_c,
323 langkind_c_cpp,
Chris Lattnera778d7d2008-10-22 17:29:21 +0000324 langkind_asm_cpp,
Reid Spencer5f016e22007-07-11 17:01:13 +0000325 langkind_cxx,
326 langkind_cxx_cpp,
327 langkind_objc,
328 langkind_objc_cpp,
329 langkind_objcxx,
Nate Begeman4e3629e2009-06-25 22:43:10 +0000330 langkind_objcxx_cpp,
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +0000331 langkind_ocl,
332 langkind_ast
Reid Spencer5f016e22007-07-11 17:01:13 +0000333};
334
Reid Spencer5f016e22007-07-11 17:01:13 +0000335static llvm::cl::opt<LangKind>
336BaseLang("x", llvm::cl::desc("Base language to compile"),
337 llvm::cl::init(langkind_unspecified),
338 llvm::cl::values(clEnumValN(langkind_c, "c", "C"),
Nate Begeman4e3629e2009-06-25 22:43:10 +0000339 clEnumValN(langkind_ocl, "cl", "OpenCL C"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000340 clEnumValN(langkind_cxx, "c++", "C++"),
341 clEnumValN(langkind_objc, "objective-c", "Objective C"),
342 clEnumValN(langkind_objcxx,"objective-c++","Objective C++"),
Daniel Dunbard2ea3862009-01-29 23:50:47 +0000343 clEnumValN(langkind_c_cpp, "cpp-output",
Reid Spencer5f016e22007-07-11 17:01:13 +0000344 "Preprocessed C"),
Chris Lattnera778d7d2008-10-22 17:29:21 +0000345 clEnumValN(langkind_asm_cpp, "assembler-with-cpp",
346 "Preprocessed asm"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000347 clEnumValN(langkind_cxx_cpp, "c++-cpp-output",
Chris Lattnerc76d8072009-02-06 06:19:20 +0000348 "Preprocessed C++"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000349 clEnumValN(langkind_objc_cpp, "objective-c-cpp-output",
350 "Preprocessed Objective C"),
Chris Lattnerc76d8072009-02-06 06:19:20 +0000351 clEnumValN(langkind_objcxx_cpp, "objective-c++-cpp-output",
Reid Spencer5f016e22007-07-11 17:01:13 +0000352 "Preprocessed Objective C++"),
Daniel Dunbar0b5b0da2009-04-01 05:09:09 +0000353 clEnumValN(langkind_c, "c-header",
354 "C header"),
355 clEnumValN(langkind_objc, "objective-c-header",
356 "Objective-C header"),
357 clEnumValN(langkind_cxx, "c++-header",
358 "C++ header"),
359 clEnumValN(langkind_objcxx, "objective-c++-header",
360 "Objective-C++ header"),
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +0000361 clEnumValN(langkind_ast, "ast",
362 "Clang AST"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000363 clEnumValEnd));
364
365static llvm::cl::opt<bool>
Chris Lattner2c78b872009-04-14 23:22:57 +0000366ObjCExclusiveGC("fobjc-gc-only",
367 llvm::cl::desc("Use GC exclusively for Objective-C related "
368 "memory management"));
369
David Chisnall8a5a9aa2009-08-31 16:41:57 +0000370static llvm::cl::opt<std::string>
371ObjCConstantStringClass("fconstant-string-class",
372 llvm::cl::value_desc("class name"),
373 llvm::cl::desc("Specify the class to use for constant "
374 "Objective-C string objects."));
375
Chris Lattner2c78b872009-04-14 23:22:57 +0000376static llvm::cl::opt<bool>
377ObjCEnableGC("fobjc-gc",
378 llvm::cl::desc("Enable Objective-C garbage collection"));
379
Fariborz Jahanian448f5e62009-04-17 03:04:15 +0000380static llvm::cl::opt<bool>
381ObjCEnableGCBitmapPrint("print-ivar-layout",
382 llvm::cl::desc("Enable Objective-C Ivar layout bitmap print trace"));
383
Chris Lattner2c78b872009-04-14 23:22:57 +0000384static llvm::cl::opt<LangOptions::VisibilityMode>
385SymbolVisibility("fvisibility",
386 llvm::cl::desc("Set the default symbol visibility:"),
387 llvm::cl::init(LangOptions::Default),
388 llvm::cl::values(clEnumValN(LangOptions::Default, "default",
389 "Use default symbol visibility"),
390 clEnumValN(LangOptions::Hidden, "hidden",
391 "Use hidden symbol visibility"),
392 clEnumValN(LangOptions::Protected,"protected",
393 "Use protected symbol visibility"),
394 clEnumValEnd));
395
396static llvm::cl::opt<bool>
397OverflowChecking("ftrapv",
398 llvm::cl::desc("Trap on integer overflow"),
399 llvm::cl::init(false));
400
Fariborz Jahanian34e65772009-05-22 20:17:16 +0000401static llvm::cl::opt<bool>
Nate Begeman2ef13e52009-08-10 23:49:36 +0000402AltiVec("faltivec", llvm::cl::desc("Enable AltiVec vector initializer syntax"),
403 llvm::cl::init(false));
404
405static llvm::cl::opt<bool>
Daniel Dunbar5345c392009-09-03 04:54:28 +0000406PThread("pthread", llvm::cl::desc("Support POSIX threads in generated code"),
407 llvm::cl::init(false));
408
Daniel Dunbar13fdf282009-09-17 00:47:46 +0000409static LangKind GetLanguage(llvm::StringRef Filename) {
Ted Kremenek8904f152007-12-05 23:49:08 +0000410 if (BaseLang != langkind_unspecified)
411 return BaseLang;
Mike Stump1eb44332009-09-09 15:08:12 +0000412
Daniel Dunbar13fdf282009-09-17 00:47:46 +0000413 llvm::StringRef Ext = Filename.rsplit('.').second;
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +0000414 if (Ext == "ast")
415 return langkind_ast;
416 else if (Ext == "c")
Ted Kremenek8904f152007-12-05 23:49:08 +0000417 return langkind_c;
Daniel Dunbar9f435342009-09-17 00:47:27 +0000418 else if (Ext == "S" || Ext == "s")
Chris Lattnera778d7d2008-10-22 17:29:21 +0000419 return langkind_asm_cpp;
Ted Kremenek8904f152007-12-05 23:49:08 +0000420 else if (Ext == "i")
421 return langkind_c_cpp;
422 else if (Ext == "ii")
423 return langkind_cxx_cpp;
424 else if (Ext == "m")
425 return langkind_objc;
426 else if (Ext == "mi")
427 return langkind_objc_cpp;
428 else if (Ext == "mm" || Ext == "M")
429 return langkind_objcxx;
430 else if (Ext == "mii")
431 return langkind_objcxx_cpp;
432 else if (Ext == "C" || Ext == "cc" || Ext == "cpp" || Ext == "CPP" ||
433 Ext == "c++" || Ext == "cp" || Ext == "cxx")
434 return langkind_cxx;
Nate Begeman4e3629e2009-06-25 22:43:10 +0000435 else if (Ext == "cl")
436 return langkind_ocl;
Ted Kremenek8904f152007-12-05 23:49:08 +0000437 else
438 return langkind_c;
439}
440
441
Ted Kremenek85888962008-10-21 00:54:44 +0000442static void InitializeCOptions(LangOptions &Options) {
443 // Do nothing.
444}
445
446static void InitializeObjCOptions(LangOptions &Options) {
447 Options.ObjC1 = Options.ObjC2 = 1;
448}
Mike Stump1eb44332009-09-09 15:08:12 +0000449
Ted Kremenek85888962008-10-21 00:54:44 +0000450
Daniel Dunbar0b5b0da2009-04-01 05:09:09 +0000451static void InitializeLangOptions(LangOptions &Options, LangKind LK){
Reid Spencer5f016e22007-07-11 17:01:13 +0000452 // FIXME: implement -fpreprocessed mode.
453 bool NoPreprocess = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000454
Ted Kremenek8904f152007-12-05 23:49:08 +0000455 switch (LK) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000456 default: assert(0 && "Unknown language kind!");
Chris Lattnera778d7d2008-10-22 17:29:21 +0000457 case langkind_asm_cpp:
Daniel Dunbarc1571452008-12-01 18:55:22 +0000458 Options.AsmPreprocessor = 1;
Chris Lattnera778d7d2008-10-22 17:29:21 +0000459 // FALLTHROUGH
Reid Spencer5f016e22007-07-11 17:01:13 +0000460 case langkind_c_cpp:
461 NoPreprocess = true;
462 // FALLTHROUGH
463 case langkind_c:
Ted Kremenek85888962008-10-21 00:54:44 +0000464 InitializeCOptions(Options);
Reid Spencer5f016e22007-07-11 17:01:13 +0000465 break;
466 case langkind_cxx_cpp:
467 NoPreprocess = true;
468 // FALLTHROUGH
469 case langkind_cxx:
470 Options.CPlusPlus = 1;
471 break;
472 case langkind_objc_cpp:
473 NoPreprocess = true;
474 // FALLTHROUGH
475 case langkind_objc:
Ted Kremenek85888962008-10-21 00:54:44 +0000476 InitializeObjCOptions(Options);
Reid Spencer5f016e22007-07-11 17:01:13 +0000477 break;
478 case langkind_objcxx_cpp:
479 NoPreprocess = true;
480 // FALLTHROUGH
481 case langkind_objcxx:
482 Options.ObjC1 = Options.ObjC2 = 1;
483 Options.CPlusPlus = 1;
484 break;
Nate Begeman4e3629e2009-06-25 22:43:10 +0000485 case langkind_ocl:
486 Options.OpenCL = 1;
487 Options.AltiVec = 1;
488 Options.CXXOperatorNames = 1;
489 Options.LaxVectorConversions = 1;
490 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000491 }
Mike Stump1eb44332009-09-09 15:08:12 +0000492
Chris Lattner2c78b872009-04-14 23:22:57 +0000493 if (ObjCExclusiveGC)
494 Options.setGCMode(LangOptions::GCOnly);
495 else if (ObjCEnableGC)
496 Options.setGCMode(LangOptions::HybridGC);
Mike Stump1eb44332009-09-09 15:08:12 +0000497
Fariborz Jahanian448f5e62009-04-17 03:04:15 +0000498 if (ObjCEnableGCBitmapPrint)
499 Options.ObjCGCBitmapPrint = 1;
Mike Stump1eb44332009-09-09 15:08:12 +0000500
Nate Begeman2ef13e52009-08-10 23:49:36 +0000501 if (AltiVec)
502 Options.AltiVec = 1;
Daniel Dunbar5345c392009-09-03 04:54:28 +0000503
504 if (PThread)
505 Options.POSIXThreads = 1;
Mike Stump1eb44332009-09-09 15:08:12 +0000506
Chris Lattner2c78b872009-04-14 23:22:57 +0000507 Options.setVisibilityMode(SymbolVisibility);
508 Options.OverflowChecking = OverflowChecking;
Reid Spencer5f016e22007-07-11 17:01:13 +0000509}
510
511/// LangStds - Language standards we support.
512enum LangStds {
Mike Stump1eb44332009-09-09 15:08:12 +0000513 lang_unspecified,
Reid Spencer5f016e22007-07-11 17:01:13 +0000514 lang_c89, lang_c94, lang_c99,
Douglas Gregor214904e2009-09-29 14:42:43 +0000515 lang_gnu89, lang_gnu99,
Chris Lattnerd4b80f12007-07-16 04:18:29 +0000516 lang_cxx98, lang_gnucxx98,
517 lang_cxx0x, lang_gnucxx0x
Reid Spencer5f016e22007-07-11 17:01:13 +0000518};
519
520static llvm::cl::opt<LangStds>
521LangStd("std", llvm::cl::desc("Language standard to compile for"),
522 llvm::cl::init(lang_unspecified),
523 llvm::cl::values(clEnumValN(lang_c89, "c89", "ISO C 1990"),
524 clEnumValN(lang_c89, "c90", "ISO C 1990"),
525 clEnumValN(lang_c89, "iso9899:1990", "ISO C 1990"),
526 clEnumValN(lang_c94, "iso9899:199409",
527 "ISO C 1990 with amendment 1"),
528 clEnumValN(lang_c99, "c99", "ISO C 1999"),
Chris Lattner50748f42009-04-06 17:17:55 +0000529 clEnumValN(lang_c99, "c9x", "ISO C 1999"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000530 clEnumValN(lang_c99, "iso9899:1999", "ISO C 1999"),
Chris Lattner50748f42009-04-06 17:17:55 +0000531 clEnumValN(lang_c99, "iso9899:199x", "ISO C 1999"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000532 clEnumValN(lang_gnu89, "gnu89",
Gabor Greif10b26142009-02-28 09:22:15 +0000533 "ISO C 1990 with GNU extensions"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000534 clEnumValN(lang_gnu99, "gnu99",
Gabor Greif10b26142009-02-28 09:22:15 +0000535 "ISO C 1999 with GNU extensions (default for C)"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000536 clEnumValN(lang_gnu99, "gnu9x",
537 "ISO C 1999 with GNU extensions"),
538 clEnumValN(lang_cxx98, "c++98",
539 "ISO C++ 1998 with amendments"),
540 clEnumValN(lang_gnucxx98, "gnu++98",
541 "ISO C++ 1998 with amendments and GNU "
542 "extensions (default for C++)"),
Chris Lattnerd4b80f12007-07-16 04:18:29 +0000543 clEnumValN(lang_cxx0x, "c++0x",
544 "Upcoming ISO C++ 200x with amendments"),
545 clEnumValN(lang_gnucxx0x, "gnu++0x",
546 "Upcoming ISO C++ 200x with amendments and GNU "
Gabor Greif5f8d1db2009-03-11 23:07:18 +0000547 "extensions"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000548 clEnumValEnd));
549
550static llvm::cl::opt<bool>
551NoOperatorNames("fno-operator-names",
552 llvm::cl::desc("Do not treat C++ operator name keywords as "
553 "synonyms for operators"));
554
Anders Carlssonee98ac52007-10-15 02:50:23 +0000555static llvm::cl::opt<bool>
556PascalStrings("fpascal-strings",
557 llvm::cl::desc("Recognize and construct Pascal-style "
558 "string literals"));
Mike Stump1eb44332009-09-09 15:08:12 +0000559
Steve Naroffd62701b2008-02-07 03:50:06 +0000560static llvm::cl::opt<bool>
561MSExtensions("fms-extensions",
562 llvm::cl::desc("Accept some non-standard constructs used in "
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000563 "Microsoft header files "));
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000564
565static llvm::cl::opt<bool>
566WritableStrings("fwritable-strings",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000567 llvm::cl::desc("Store string literals as writable data"));
Anders Carlsson695dbb62007-11-30 04:21:22 +0000568
569static llvm::cl::opt<bool>
Anders Carlssonad53eff2009-01-30 23:26:40 +0000570NoLaxVectorConversions("fno-lax-vector-conversions",
Anders Carlssonb0f90cc2009-01-30 23:17:46 +0000571 llvm::cl::desc("Disallow implicit conversions between "
572 "vectors with a different number of "
573 "elements or different element types"));
Chris Lattnerae0ee032008-12-04 23:20:07 +0000574
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000575static llvm::cl::opt<bool>
Daniel Dunbar48d1ef72009-04-07 21:16:11 +0000576EnableBlocks("fblocks", llvm::cl::desc("enable the 'blocks' language feature"));
Mike Stumpa0f02aa2009-02-02 22:57:57 +0000577
578static llvm::cl::opt<bool>
Chris Lattner810f6d52009-03-13 17:38:01 +0000579EnableHeinousExtensions("fheinous-gnu-extensions",
580 llvm::cl::desc("enable GNU extensions that you really really shouldn't use"),
581 llvm::cl::ValueDisallowed, llvm::cl::Hidden);
582
583static llvm::cl::opt<bool>
Mike Stumpa0f02aa2009-02-02 22:57:57 +0000584ObjCNonFragileABI("fobjc-nonfragile-abi",
585 llvm::cl::desc("enable objective-c's nonfragile abi"));
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000586
Daniel Dunbard6884a02009-05-04 05:16:21 +0000587
588static llvm::cl::opt<bool>
Daniel Dunbard604c402009-02-04 21:19:06 +0000589EmitAllDecls("femit-all-decls",
590 llvm::cl::desc("Emit all declarations, even if unused"));
Ted Kremenek01d9dbf2008-04-29 04:37:03 +0000591
Daniel Dunbar6379a7a2008-08-11 17:36:14 +0000592static llvm::cl::opt<bool>
593Exceptions("fexceptions",
Chris Lattnerf5db8f82009-04-19 07:00:02 +0000594 llvm::cl::desc("Enable support for exception handling"));
Daniel Dunbar6379a7a2008-08-11 17:36:14 +0000595
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000596static llvm::cl::opt<bool>
Mike Stump738f8c22009-07-31 23:15:31 +0000597Rtti("frtti", llvm::cl::init(true),
598 llvm::cl::desc("Enable generation of rtti information"));
599
600static llvm::cl::opt<bool>
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000601GNURuntime("fgnu-runtime",
Ted Kremenek85888962008-10-21 00:54:44 +0000602 llvm::cl::desc("Generate output compatible with the standard GNU "
Chris Lattnerf5db8f82009-04-19 07:00:02 +0000603 "Objective-C runtime"));
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000604
605static llvm::cl::opt<bool>
606NeXTRuntime("fnext-runtime",
Ted Kremenek85888962008-10-21 00:54:44 +0000607 llvm::cl::desc("Generate output compatible with the NeXT "
Chris Lattnerf5db8f82009-04-19 07:00:02 +0000608 "runtime"));
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000609
Eli Friedmanc4757bd2009-06-05 07:12:17 +0000610static llvm::cl::opt<bool>
611CharIsSigned("fsigned-char",
612 llvm::cl::desc("Force char to be a signed/unsigned type"));
Ted Kremenekea644d82008-09-03 21:22:16 +0000613
614
615static llvm::cl::opt<bool>
Chris Lattnerf5db8f82009-04-19 07:00:02 +0000616Trigraphs("trigraphs", llvm::cl::desc("Process trigraph sequences"));
Ted Kremenekea644d82008-09-03 21:22:16 +0000617
Douglas Gregor26dce442009-03-10 00:06:19 +0000618static llvm::cl::opt<unsigned>
619TemplateDepth("ftemplate-depth", llvm::cl::init(99),
620 llvm::cl::desc("Maximum depth of recursive template "
621 "instantiation"));
Chris Lattnerf5db8f82009-04-19 07:00:02 +0000622static llvm::cl::opt<bool>
623DollarsInIdents("fdollars-in-identifiers",
624 llvm::cl::desc("Allow '$' in identifiers"));
Chris Lattner16167a62009-03-02 22:11:07 +0000625
Anders Carlsson4ca076f2009-04-06 17:37:10 +0000626
627static llvm::cl::opt<bool>
628OptSize("Os", llvm::cl::desc("Optimize for size"));
629
630static llvm::cl::opt<bool>
Mike Stump1eb44332009-09-09 15:08:12 +0000631DisableLLVMOptimizations("disable-llvm-optzns",
Daniel Dunbar877db382009-06-02 22:07:45 +0000632 llvm::cl::desc("Don't run LLVM optimization passes"));
633
634static llvm::cl::opt<bool>
Anders Carlsson4ca076f2009-04-06 17:37:10 +0000635NoCommon("fno-common",
636 llvm::cl::desc("Compile common globals like normal definitions"),
637 llvm::cl::ValueDisallowed);
638
Daniel Dunbarc9abc042009-04-08 05:11:16 +0000639static llvm::cl::opt<std::string>
640MainFileName("main-file-name",
641 llvm::cl::desc("Main file name to use for debug info"));
Anders Carlsson4ca076f2009-04-06 17:37:10 +0000642
Anders Carlssona33d9b42009-05-13 19:49:53 +0000643// FIXME: Also add an "-fno-access-control" option.
644static llvm::cl::opt<bool>
Mike Stump1eb44332009-09-09 15:08:12 +0000645AccessControl("faccess-control",
Anders Carlssona33d9b42009-05-13 19:49:53 +0000646 llvm::cl::desc("Enable C++ access control"));
647
Anders Carlsson92f58222009-08-22 22:30:33 +0000648static llvm::cl::opt<bool>
649NoElideConstructors("fno-elide-constructors",
650 llvm::cl::desc("Disable C++ copy constructor elision"));
651
Tanya Lattner59876c22009-11-04 01:18:09 +0000652static llvm::cl::opt<bool>
653NoMergeConstants("fno-merge-all-constants",
654 llvm::cl::desc("Disallow merging of constants."));
655
Daniel Dunbar73b79592009-09-14 00:02:12 +0000656static llvm::cl::opt<std::string>
657TargetABI("target-abi",
658 llvm::cl::desc("Target a particular ABI type"));
659
Daniel Dunbar7c15e712009-10-30 18:12:31 +0000660static llvm::cl::opt<std::string>
661TargetTriple("triple",
662 llvm::cl::desc("Specify target triple (e.g. i686-apple-darwin9)"));
663
Anders Carlsson92f58222009-08-22 22:30:33 +0000664
Anders Carlsson4ca076f2009-04-06 17:37:10 +0000665// It might be nice to add bounds to the CommandLine library directly.
666struct OptLevelParser : public llvm::cl::parser<unsigned> {
Chris Lattner59b21722009-09-20 00:39:15 +0000667 bool parse(llvm::cl::Option &O, llvm::StringRef ArgName,
668 llvm::StringRef Arg, unsigned &Val) {
Anders Carlsson4ca076f2009-04-06 17:37:10 +0000669 if (llvm::cl::parser<unsigned>::parse(O, ArgName, Arg, Val))
670 return true;
Anders Carlsson4ca076f2009-04-06 17:37:10 +0000671 if (Val > 3)
Benjamin Kramer21fde992009-08-02 12:12:11 +0000672 return O.error("'" + Arg + "' invalid optimization level!");
Anders Carlsson4ca076f2009-04-06 17:37:10 +0000673 return false;
674 }
675};
676static llvm::cl::opt<unsigned, false, OptLevelParser>
677OptLevel("O", llvm::cl::Prefix,
678 llvm::cl::desc("Optimization level"),
679 llvm::cl::init(0));
680
Daniel Dunbar9fd0b1f2009-04-08 03:03:23 +0000681static llvm::cl::opt<unsigned>
Daniel Dunbar3bbc7532009-04-08 18:03:55 +0000682PICLevel("pic-level", llvm::cl::desc("Value for __PIC__"));
683
684static llvm::cl::opt<bool>
685StaticDefine("static-define", llvm::cl::desc("Should __STATIC__ be defined"));
Daniel Dunbar9fd0b1f2009-04-08 03:03:23 +0000686
Bill Wendling45483f72009-06-28 07:36:13 +0000687static llvm::cl::opt<int>
688StackProtector("stack-protector",
689 llvm::cl::desc("Enable stack protectors"),
690 llvm::cl::init(-1));
691
Daniel Dunbardcb4a1a2008-08-23 08:43:39 +0000692static void InitializeLanguageStandard(LangOptions &Options, LangKind LK,
Daniel Dunbar868bd0a2009-05-06 03:16:41 +0000693 TargetInfo *Target,
694 const llvm::StringMap<bool> &Features) {
Chris Lattner8fc4dfb2008-12-04 22:54:33 +0000695 // Allow the target to set the default the langauge options as it sees fit.
696 Target->getDefaultLangOptions(Options);
Daniel Dunbar868bd0a2009-05-06 03:16:41 +0000697
698 // Pass the map of target features to the target for validation and
699 // processing.
700 Target->HandleTargetFeatures(Features);
Mike Stump1eb44332009-09-09 15:08:12 +0000701
Reid Spencer5f016e22007-07-11 17:01:13 +0000702 if (LangStd == lang_unspecified) {
703 // Based on the base language, pick one.
Ted Kremenek8904f152007-12-05 23:49:08 +0000704 switch (LK) {
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +0000705 case langkind_ast: assert(0 && "Invalid call for AST inputs");
Ted Kremenekf2a17b12009-03-19 19:02:20 +0000706 case lang_unspecified: assert(0 && "Unknown base language");
Nate Begeman4e3629e2009-06-25 22:43:10 +0000707 case langkind_ocl:
708 LangStd = lang_c99;
709 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000710 case langkind_c:
Chris Lattnera778d7d2008-10-22 17:29:21 +0000711 case langkind_asm_cpp:
Reid Spencer5f016e22007-07-11 17:01:13 +0000712 case langkind_c_cpp:
713 case langkind_objc:
714 case langkind_objc_cpp:
715 LangStd = lang_gnu99;
716 break;
717 case langkind_cxx:
718 case langkind_cxx_cpp:
719 case langkind_objcxx:
720 case langkind_objcxx_cpp:
721 LangStd = lang_gnucxx98;
722 break;
723 }
724 }
Mike Stump1eb44332009-09-09 15:08:12 +0000725
Reid Spencer5f016e22007-07-11 17:01:13 +0000726 switch (LangStd) {
727 default: assert(0 && "Unknown language standard!");
728
729 // Fall through from newer standards to older ones. This isn't really right.
730 // FIXME: Enable specifically the right features based on the language stds.
Chris Lattnerd4b80f12007-07-16 04:18:29 +0000731 case lang_gnucxx0x:
732 case lang_cxx0x:
733 Options.CPlusPlus0x = 1;
734 // FALL THROUGH
Reid Spencer5f016e22007-07-11 17:01:13 +0000735 case lang_gnucxx98:
736 case lang_cxx98:
737 Options.CPlusPlus = 1;
738 Options.CXXOperatorNames = !NoOperatorNames;
739 // FALL THROUGH.
740 case lang_gnu99:
741 case lang_c99:
Reid Spencer5f016e22007-07-11 17:01:13 +0000742 Options.C99 = 1;
743 Options.HexFloats = 1;
744 // FALL THROUGH.
745 case lang_gnu89:
746 Options.BCPLComment = 1; // Only for C99/C++.
747 // FALL THROUGH.
748 case lang_c94:
Chris Lattner3426b9b2008-02-25 04:01:39 +0000749 Options.Digraphs = 1; // C94, C99, C++.
750 // FALL THROUGH.
Reid Spencer5f016e22007-07-11 17:01:13 +0000751 case lang_c89:
752 break;
753 }
Argyrios Kyrtzidisd1465522008-09-11 04:21:06 +0000754
Chris Lattner7e9c90b2009-03-20 15:44:26 +0000755 // GNUMode - Set if we're in gnu99, gnu89, gnucxx98, etc.
Douglas Gregor214904e2009-09-29 14:42:43 +0000756 switch (LangStd) {
757 default: assert(0 && "Unknown language standard!");
758 case lang_gnucxx0x:
759 case lang_gnucxx98:
760 case lang_gnu99:
761 case lang_gnu89:
762 Options.GNUMode = 1;
763 break;
764 case lang_cxx0x:
765 case lang_cxx98:
766 case lang_c99:
767 case lang_c94:
768 case lang_c89:
769 Options.GNUMode = 0;
770 break;
771 }
Mike Stump1eb44332009-09-09 15:08:12 +0000772
Argyrios Kyrtzidisd1465522008-09-11 04:21:06 +0000773 if (Options.CPlusPlus) {
774 Options.C99 = 0;
Eli Friedmanab24c8d2009-08-26 20:15:14 +0000775 Options.HexFloats = 0;
Argyrios Kyrtzidisd1465522008-09-11 04:21:06 +0000776 }
Mike Stump1eb44332009-09-09 15:08:12 +0000777
Chris Lattnerd658b562008-04-05 06:32:51 +0000778 if (LangStd == lang_c89 || LangStd == lang_c94 || LangStd == lang_gnu89)
779 Options.ImplicitInt = 1;
780 else
781 Options.ImplicitInt = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000782
Daniel Dunbard573d262009-04-07 22:13:21 +0000783 // Mimicing gcc's behavior, trigraphs are only enabled if -trigraphs
784 // is specified, or -std is set to a conforming mode.
Chris Lattner7e9c90b2009-03-20 15:44:26 +0000785 Options.Trigraphs = !Options.GNUMode;
Chris Lattner802db9b2008-12-05 00:10:44 +0000786 if (Trigraphs.getPosition())
Chris Lattner7e9c90b2009-03-20 15:44:26 +0000787 Options.Trigraphs = Trigraphs; // Command line option wins if specified.
Ted Kremenekea644d82008-09-03 21:22:16 +0000788
Chris Lattner802db9b2008-12-05 00:10:44 +0000789 // If in a conformant language mode (e.g. -std=c99) Blocks defaults to off
790 // even if they are normally on for the target. In GNU modes (e.g.
791 // -std=gnu99) the default for blocks depends on the target settings.
Anders Carlssone56f6ff2009-01-21 18:47:36 +0000792 // However, blocks are not turned off when compiling Obj-C or Obj-C++ code.
Chris Lattner7e9c90b2009-03-20 15:44:26 +0000793 if (!Options.ObjC1 && !Options.GNUMode)
Chris Lattner802db9b2008-12-05 00:10:44 +0000794 Options.Blocks = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000795
Chris Lattner01638a62009-04-19 07:06:52 +0000796 // Default to not accepting '$' in identifiers when preprocessing assembler,
797 // but do accept when preprocessing C. FIXME: these defaults are right for
798 // darwin, are they right everywhere?
799 Options.DollarIdents = LK != langkind_asm_cpp;
800 if (DollarsInIdents.getPosition()) // Explicit setting overrides default.
Chris Lattnerf5db8f82009-04-19 07:00:02 +0000801 Options.DollarIdents = DollarsInIdents;
Mike Stump1eb44332009-09-09 15:08:12 +0000802
Chris Lattnerae0ee032008-12-04 23:20:07 +0000803 if (PascalStrings.getPosition())
804 Options.PascalStrings = PascalStrings;
Eli Friedmanabc4e322009-06-08 06:11:14 +0000805 if (MSExtensions.getPosition())
806 Options.Microsoft = MSExtensions;
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000807 Options.WritableStrings = WritableStrings;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +0000808 if (NoLaxVectorConversions.getPosition())
809 Options.LaxVectorConversions = 0;
Daniel Dunbar6379a7a2008-08-11 17:36:14 +0000810 Options.Exceptions = Exceptions;
Mike Stump738f8c22009-07-31 23:15:31 +0000811 Options.Rtti = Rtti;
Mike Stumpa0f02aa2009-02-02 22:57:57 +0000812 if (EnableBlocks.getPosition())
Chris Lattnerae0ee032008-12-04 23:20:07 +0000813 Options.Blocks = EnableBlocks;
Eli Friedmanc4757bd2009-06-05 07:12:17 +0000814 if (CharIsSigned.getPosition())
815 Options.CharIsSigned = CharIsSigned;
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000816
Daniel Dunbar9f9768c2009-03-20 23:49:28 +0000817 if (!AllowBuiltins)
Chris Lattner7644f072009-03-13 22:38:49 +0000818 Options.NoBuiltin = 1;
Douglas Gregor3573c0c2009-02-14 20:49:29 +0000819 if (Freestanding)
Chris Lattner7644f072009-03-13 22:38:49 +0000820 Options.Freestanding = Options.NoBuiltin = 1;
Mike Stump1eb44332009-09-09 15:08:12 +0000821
Chris Lattner810f6d52009-03-13 17:38:01 +0000822 if (EnableHeinousExtensions)
823 Options.HeinousExtensions = 1;
Douglas Gregor3573c0c2009-02-14 20:49:29 +0000824
Anders Carlssona33d9b42009-05-13 19:49:53 +0000825 if (AccessControl)
826 Options.AccessControl = 1;
Mike Stump1eb44332009-09-09 15:08:12 +0000827
Anders Carlsson92f58222009-08-22 22:30:33 +0000828 Options.ElideConstructors = !NoElideConstructors;
Mike Stump1eb44332009-09-09 15:08:12 +0000829
Chris Lattnere4f21422009-06-30 01:26:17 +0000830 // OpenCL and C++ both have bool, true, false keywords.
831 Options.Bool = Options.OpenCL | Options.CPlusPlus;
Mike Stump1eb44332009-09-09 15:08:12 +0000832
Daniel Dunbaref2abfe2009-02-16 22:43:43 +0000833 Options.MathErrno = MathErrno;
834
Douglas Gregor26dce442009-03-10 00:06:19 +0000835 Options.InstantiationDepth = TemplateDepth;
836
Chris Lattner8fc4dfb2008-12-04 22:54:33 +0000837 // Override the default runtime if the user requested it.
838 if (NeXTRuntime)
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000839 Options.NeXTRuntime = 1;
Chris Lattner8fc4dfb2008-12-04 22:54:33 +0000840 else if (GNURuntime)
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000841 Options.NeXTRuntime = 0;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000842
David Chisnall8a5a9aa2009-08-31 16:41:57 +0000843 if (!ObjCConstantStringClass.empty())
844 Options.ObjCConstantStringClass = ObjCConstantStringClass.c_str();
845
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000846 if (ObjCNonFragileABI)
847 Options.ObjCNonFragileABI = 1;
Fariborz Jahanian34e65772009-05-22 20:17:16 +0000848
Daniel Dunbard604c402009-02-04 21:19:06 +0000849 if (EmitAllDecls)
850 Options.EmitAllDecls = 1;
Anders Carlsson4ca076f2009-04-06 17:37:10 +0000851
Daniel Dunbar3bbc7532009-04-08 18:03:55 +0000852 // The __OPTIMIZE_SIZE__ define is tied to -Oz, which we don't
853 // support.
854 Options.OptimizeSize = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000855
Anders Carlsson4ca076f2009-04-06 17:37:10 +0000856 // -Os implies -O2
Daniel Dunbar3bbc7532009-04-08 18:03:55 +0000857 if (OptSize || OptLevel)
Anders Carlsson4ca076f2009-04-06 17:37:10 +0000858 Options.Optimize = 1;
Daniel Dunbar9fd0b1f2009-04-08 03:03:23 +0000859
860 assert(PICLevel <= 2 && "Invalid value for -pic-level");
861 Options.PICLevel = PICLevel;
Daniel Dunbarc9abc042009-04-08 05:11:16 +0000862
Daniel Dunbar3bbc7532009-04-08 18:03:55 +0000863 Options.GNUInline = !Options.C99;
Mike Stump1eb44332009-09-09 15:08:12 +0000864 // FIXME: This is affected by other options (-fno-inline).
Daniel Dunbar3bbc7532009-04-08 18:03:55 +0000865 Options.NoInline = !OptSize && !OptLevel;
866
867 Options.Static = StaticDefine;
868
Bill Wendling4ebe3e42009-06-28 23:01:01 +0000869 switch (StackProtector) {
870 default:
871 assert(StackProtector <= 2 && "Invalid value for -stack-protector");
872 case -1: break;
873 case 0: Options.setStackProtectorMode(LangOptions::SSPOff); break;
874 case 1: Options.setStackProtectorMode(LangOptions::SSPOn); break;
875 case 2: Options.setStackProtectorMode(LangOptions::SSPReq); break;
876 }
Bill Wendling45483f72009-06-28 07:36:13 +0000877
Daniel Dunbarc9abc042009-04-08 05:11:16 +0000878 if (MainFileName.getPosition())
879 Options.setMainFileName(MainFileName.c_str());
Reid Spencer5f016e22007-07-11 17:01:13 +0000880}
881
882//===----------------------------------------------------------------------===//
Chris Lattnere116ccf2009-04-21 05:40:52 +0000883// SourceManager initialization.
Reid Spencer5f016e22007-07-11 17:01:13 +0000884//===----------------------------------------------------------------------===//
885
Douglas Gregore1d918e2009-04-10 23:10:45 +0000886static bool InitializeSourceManager(Preprocessor &PP,
887 const std::string &InFile) {
888 // Figure out where to get and map in the main file.
889 SourceManager &SourceMgr = PP.getSourceManager();
890 FileManager &FileMgr = PP.getFileManager();
Daniel Dunbar57cbfc02009-04-27 21:19:07 +0000891
892 if (EmptyInputOnly) {
893 const char *EmptyStr = "";
Mike Stump1eb44332009-09-09 15:08:12 +0000894 llvm::MemoryBuffer *SB =
Daniel Dunbar57cbfc02009-04-27 21:19:07 +0000895 llvm::MemoryBuffer::getMemBuffer(EmptyStr, EmptyStr, "<empty input>");
896 SourceMgr.createMainFileIDForMemBuffer(SB);
897 } else if (InFile != "-") {
Douglas Gregore1d918e2009-04-10 23:10:45 +0000898 const FileEntry *File = FileMgr.getFile(InFile);
899 if (File) SourceMgr.createMainFileID(File, SourceLocation());
900 if (SourceMgr.getMainFileID().isInvalid()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000901 PP.getDiagnostics().Report(FullSourceLoc(), diag::err_fe_error_reading)
Douglas Gregore1d918e2009-04-10 23:10:45 +0000902 << InFile.c_str();
903 return true;
904 }
905 } else {
906 llvm::MemoryBuffer *SB = llvm::MemoryBuffer::getSTDIN();
907
908 // If stdin was empty, SB is null. Cons up an empty memory
909 // buffer now.
910 if (!SB) {
911 const char *EmptyStr = "";
912 SB = llvm::MemoryBuffer::getMemBuffer(EmptyStr, EmptyStr, "<stdin>");
913 }
914
915 SourceMgr.createMainFileIDForMemBuffer(SB);
916 if (SourceMgr.getMainFileID().isInvalid()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000917 PP.getDiagnostics().Report(FullSourceLoc(),
Douglas Gregore1d918e2009-04-10 23:10:45 +0000918 diag::err_fe_error_reading_stdin);
919 return true;
920 }
921 }
922
923 return false;
924}
925
Chris Lattneraa391972008-04-19 23:09:31 +0000926
Chris Lattnere116ccf2009-04-21 05:40:52 +0000927//===----------------------------------------------------------------------===//
928// Preprocessor Initialization
929//===----------------------------------------------------------------------===//
Sam Bishop1102d6b2008-04-14 14:41:57 +0000930
Chris Lattnere6113de2009-11-03 19:50:27 +0000931static llvm::cl::opt<bool>
Daniel Dunbar468fe242009-11-04 21:13:02 +0000932UndefMacros("undef", llvm::cl::value_desc("macro"),
933 llvm::cl::desc("undef all system defines"));
Chris Lattnere6113de2009-11-03 19:50:27 +0000934
Chris Lattnere116ccf2009-04-21 05:40:52 +0000935static llvm::cl::list<std::string>
936D_macros("D", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
937 llvm::cl::desc("Predefine the specified macro"));
938static llvm::cl::list<std::string>
939U_macros("U", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
940 llvm::cl::desc("Undefine the specified macro"));
Chris Lattnerb8e240e2009-04-08 18:24:34 +0000941
Chris Lattnere116ccf2009-04-21 05:40:52 +0000942static llvm::cl::list<std::string>
943ImplicitIncludes("include", llvm::cl::value_desc("file"),
944 llvm::cl::desc("Include file before parsing"));
945static llvm::cl::list<std::string>
946ImplicitMacroIncludes("imacros", llvm::cl::value_desc("file"),
947 llvm::cl::desc("Include macros from file before parsing"));
Chris Lattnerb8e240e2009-04-08 18:24:34 +0000948
Chris Lattnere116ccf2009-04-21 05:40:52 +0000949static llvm::cl::opt<std::string>
950ImplicitIncludePCH("include-pch", llvm::cl::value_desc("file"),
951 llvm::cl::desc("Include precompiled header file"));
952
953static llvm::cl::opt<std::string>
954ImplicitIncludePTH("include-pth", llvm::cl::value_desc("file"),
955 llvm::cl::desc("Include file before parsing"));
956
Douglas Gregore650c8c2009-07-07 00:12:59 +0000957static llvm::cl::opt<bool>
Mike Stump1eb44332009-09-09 15:08:12 +0000958RelocatablePCH("relocatable-pch",
Douglas Gregore650c8c2009-07-07 00:12:59 +0000959 llvm::cl::desc("Whether to build a relocatable precompiled "
960 "header"));
Reid Spencer5f016e22007-07-11 17:01:13 +0000961
962//===----------------------------------------------------------------------===//
963// Preprocessor include path information.
964//===----------------------------------------------------------------------===//
965
966// This tool exports a large number of command line options to control how the
967// preprocessor searches for header files. At root, however, the Preprocessor
968// object takes a very simple interface: a list of directories to search for
Mike Stump1eb44332009-09-09 15:08:12 +0000969//
Daniel Dunbarfb4ac7b2009-05-06 03:48:17 +0000970// FIXME: -nostdinc++
Chris Lattner0c946412007-08-26 17:47:35 +0000971// FIXME: -imultilib
Reid Spencer5f016e22007-07-11 17:01:13 +0000972//
Reid Spencer5f016e22007-07-11 17:01:13 +0000973
974static llvm::cl::opt<bool>
975nostdinc("nostdinc", llvm::cl::desc("Disable standard #include directories"));
976
Rafael Espindola1bb15a92009-10-05 13:12:17 +0000977static llvm::cl::opt<bool>
Rafael Espindola8d737cc2009-10-26 13:36:57 +0000978nobuiltininc("nobuiltininc",
979 llvm::cl::desc("Disable builtin #include directories"));
Rafael Espindola1bb15a92009-10-05 13:12:17 +0000980
Reid Spencer5f016e22007-07-11 17:01:13 +0000981// Various command line options. These four add directories to each chain.
982static llvm::cl::list<std::string>
983F_dirs("F", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
984 llvm::cl::desc("Add directory to framework include search path"));
985static llvm::cl::list<std::string>
986I_dirs("I", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
987 llvm::cl::desc("Add directory to include search path"));
988static llvm::cl::list<std::string>
989idirafter_dirs("idirafter", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
990 llvm::cl::desc("Add directory to AFTER include search path"));
991static llvm::cl::list<std::string>
992iquote_dirs("iquote", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
993 llvm::cl::desc("Add directory to QUOTE include search path"));
994static llvm::cl::list<std::string>
995isystem_dirs("isystem", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
996 llvm::cl::desc("Add directory to SYSTEM include search path"));
997
998// These handle -iprefix/-iwithprefix/-iwithprefixbefore.
999static llvm::cl::list<std::string>
1000iprefix_vals("iprefix", llvm::cl::value_desc("prefix"), llvm::cl::Prefix,
1001 llvm::cl::desc("Set the -iwithprefix/-iwithprefixbefore prefix"));
1002static llvm::cl::list<std::string>
1003iwithprefix_vals("iwithprefix", llvm::cl::value_desc("dir"), llvm::cl::Prefix,
1004 llvm::cl::desc("Set directory to SYSTEM include search path with prefix"));
1005static llvm::cl::list<std::string>
1006iwithprefixbefore_vals("iwithprefixbefore", llvm::cl::value_desc("dir"),
1007 llvm::cl::Prefix,
1008 llvm::cl::desc("Set directory to include search path with prefix"));
1009
Chris Lattner0c946412007-08-26 17:47:35 +00001010static llvm::cl::opt<std::string>
1011isysroot("isysroot", llvm::cl::value_desc("dir"), llvm::cl::init("/"),
1012 llvm::cl::desc("Set the system root directory (usually /)"));
1013
Reid Spencer5f016e22007-07-11 17:01:13 +00001014// Finally, implement the code that groks the options above.
Chris Lattner5f9eae52008-03-01 08:07:28 +00001015
Rafael Espindola1bb15a92009-10-05 13:12:17 +00001016// Add the clang headers, which are relative to the clang binary.
1017void AddClangIncludePaths(const char *Argv0, InitHeaderSearch *Init) {
Rafael Espindola1bb15a92009-10-05 13:12:17 +00001018 llvm::sys::Path MainExecutablePath =
1019 llvm::sys::Path::GetMainExecutable(Argv0,
1020 (void*)(intptr_t)AddClangIncludePaths);
1021 if (MainExecutablePath.isEmpty())
1022 return;
1023
1024 MainExecutablePath.eraseComponent(); // Remove /clang from foo/bin/clang
1025 MainExecutablePath.eraseComponent(); // Remove /bin from foo/bin
1026
1027 // Get foo/lib/clang/<version>/include
1028 MainExecutablePath.appendComponent("lib");
1029 MainExecutablePath.appendComponent("clang");
1030 MainExecutablePath.appendComponent(CLANG_VERSION_STRING);
1031 MainExecutablePath.appendComponent("include");
1032
1033 // We pass true to ignore sysroot so that we *always* look for clang headers
1034 // relative to our executable, never relative to -isysroot.
1035 Init->AddPath(MainExecutablePath.c_str(), InitHeaderSearch::System,
1036 false, false, false, true /*ignore sysroot*/);
1037}
1038
Reid Spencer5f016e22007-07-11 17:01:13 +00001039/// InitializeIncludePaths - Process the -I options and set them in the
1040/// HeaderSearch object.
Nico Weber0fca0222008-08-22 09:25:22 +00001041void InitializeIncludePaths(const char *Argv0, HeaderSearch &Headers,
Mike Stump43d81762009-10-08 23:29:47 +00001042 FileManager &FM, const LangOptions &Lang,
1043 llvm::Triple &triple) {
Nico Weber0fca0222008-08-22 09:25:22 +00001044 InitHeaderSearch Init(Headers, Verbose, isysroot);
1045
Ted Kremenekf3721112008-05-31 00:27:00 +00001046 // Handle -I... and -F... options, walking the lists in parallel.
1047 unsigned Iidx = 0, Fidx = 0;
1048 while (Iidx < I_dirs.size() && Fidx < F_dirs.size()) {
1049 if (I_dirs.getPosition(Iidx) < F_dirs.getPosition(Fidx)) {
Nico Weber0fca0222008-08-22 09:25:22 +00001050 Init.AddPath(I_dirs[Iidx], InitHeaderSearch::Angled, false, true, false);
Ted Kremenekf3721112008-05-31 00:27:00 +00001051 ++Iidx;
1052 } else {
Nico Weber0fca0222008-08-22 09:25:22 +00001053 Init.AddPath(F_dirs[Fidx], InitHeaderSearch::Angled, false, true, true);
Ted Kremenekf3721112008-05-31 00:27:00 +00001054 ++Fidx;
1055 }
1056 }
Mike Stump1eb44332009-09-09 15:08:12 +00001057
Ted Kremenekf3721112008-05-31 00:27:00 +00001058 // Consume what's left from whatever list was longer.
1059 for (; Iidx != I_dirs.size(); ++Iidx)
Nico Weber0fca0222008-08-22 09:25:22 +00001060 Init.AddPath(I_dirs[Iidx], InitHeaderSearch::Angled, false, true, false);
Ted Kremenekf3721112008-05-31 00:27:00 +00001061 for (; Fidx != F_dirs.size(); ++Fidx)
Nico Weber0fca0222008-08-22 09:25:22 +00001062 Init.AddPath(F_dirs[Fidx], InitHeaderSearch::Angled, false, true, true);
Mike Stump1eb44332009-09-09 15:08:12 +00001063
Reid Spencer5f016e22007-07-11 17:01:13 +00001064 // Handle -idirafter... options.
1065 for (unsigned i = 0, e = idirafter_dirs.size(); i != e; ++i)
Nico Weber0fca0222008-08-22 09:25:22 +00001066 Init.AddPath(idirafter_dirs[i], InitHeaderSearch::After,
1067 false, true, false);
Mike Stump1eb44332009-09-09 15:08:12 +00001068
Reid Spencer5f016e22007-07-11 17:01:13 +00001069 // Handle -iquote... options.
1070 for (unsigned i = 0, e = iquote_dirs.size(); i != e; ++i)
Nico Weber0fca0222008-08-22 09:25:22 +00001071 Init.AddPath(iquote_dirs[i], InitHeaderSearch::Quoted, false, true, false);
Mike Stump1eb44332009-09-09 15:08:12 +00001072
Reid Spencer5f016e22007-07-11 17:01:13 +00001073 // Handle -isystem... options.
1074 for (unsigned i = 0, e = isystem_dirs.size(); i != e; ++i)
Nico Weber0fca0222008-08-22 09:25:22 +00001075 Init.AddPath(isystem_dirs[i], InitHeaderSearch::System, false, true, false);
Reid Spencer5f016e22007-07-11 17:01:13 +00001076
1077 // Walk the -iprefix/-iwithprefix/-iwithprefixbefore argument lists in
1078 // parallel, processing the values in order of occurance to get the right
1079 // prefixes.
1080 {
1081 std::string Prefix = ""; // FIXME: this isn't the correct default prefix.
1082 unsigned iprefix_idx = 0;
1083 unsigned iwithprefix_idx = 0;
1084 unsigned iwithprefixbefore_idx = 0;
1085 bool iprefix_done = iprefix_vals.empty();
1086 bool iwithprefix_done = iwithprefix_vals.empty();
1087 bool iwithprefixbefore_done = iwithprefixbefore_vals.empty();
1088 while (!iprefix_done || !iwithprefix_done || !iwithprefixbefore_done) {
1089 if (!iprefix_done &&
Mike Stump1eb44332009-09-09 15:08:12 +00001090 (iwithprefix_done ||
1091 iprefix_vals.getPosition(iprefix_idx) <
Reid Spencer5f016e22007-07-11 17:01:13 +00001092 iwithprefix_vals.getPosition(iwithprefix_idx)) &&
Mike Stump1eb44332009-09-09 15:08:12 +00001093 (iwithprefixbefore_done ||
1094 iprefix_vals.getPosition(iprefix_idx) <
Reid Spencer5f016e22007-07-11 17:01:13 +00001095 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
1096 Prefix = iprefix_vals[iprefix_idx];
1097 ++iprefix_idx;
1098 iprefix_done = iprefix_idx == iprefix_vals.size();
1099 } else if (!iwithprefix_done &&
Mike Stump1eb44332009-09-09 15:08:12 +00001100 (iwithprefixbefore_done ||
1101 iwithprefix_vals.getPosition(iwithprefix_idx) <
Reid Spencer5f016e22007-07-11 17:01:13 +00001102 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
Mike Stump1eb44332009-09-09 15:08:12 +00001103 Init.AddPath(Prefix+iwithprefix_vals[iwithprefix_idx],
Nico Weber0fca0222008-08-22 09:25:22 +00001104 InitHeaderSearch::System, false, false, false);
Reid Spencer5f016e22007-07-11 17:01:13 +00001105 ++iwithprefix_idx;
1106 iwithprefix_done = iwithprefix_idx == iwithprefix_vals.size();
1107 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00001108 Init.AddPath(Prefix+iwithprefixbefore_vals[iwithprefixbefore_idx],
Nico Weber0fca0222008-08-22 09:25:22 +00001109 InitHeaderSearch::Angled, false, false, false);
Reid Spencer5f016e22007-07-11 17:01:13 +00001110 ++iwithprefixbefore_idx;
Mike Stump1eb44332009-09-09 15:08:12 +00001111 iwithprefixbefore_done =
Reid Spencer5f016e22007-07-11 17:01:13 +00001112 iwithprefixbefore_idx == iwithprefixbefore_vals.size();
1113 }
1114 }
1115 }
Chris Lattner5f9eae52008-03-01 08:07:28 +00001116
Nico Weber0fca0222008-08-22 09:25:22 +00001117 Init.AddDefaultEnvVarPaths(Lang);
Chris Lattner5f9eae52008-03-01 08:07:28 +00001118
Rafael Espindola8d737cc2009-10-26 13:36:57 +00001119 if (!nobuiltininc)
Daniel Dunbar8b88ca62009-10-17 09:04:56 +00001120 AddClangIncludePaths(Argv0, &Init);
Mike Stump1eb44332009-09-09 15:08:12 +00001121
1122 if (!nostdinc)
Mike Stump43d81762009-10-08 23:29:47 +00001123 Init.AddDefaultSystemIncludePaths(Lang, triple);
Reid Spencer5f016e22007-07-11 17:01:13 +00001124
1125 // Now that we have collected all of the include paths, merge them all
1126 // together and tell the preprocessor about them.
Mike Stump1eb44332009-09-09 15:08:12 +00001127
Nico Weber0fca0222008-08-22 09:25:22 +00001128 Init.Realize();
Reid Spencer5f016e22007-07-11 17:01:13 +00001129}
1130
Mike Stump1eb44332009-09-09 15:08:12 +00001131void InitializePreprocessorInitOptions(PreprocessorInitOptions &InitOpts) {
Daniel Dunbar468fe242009-11-04 21:13:02 +00001132 // Use predefines?
1133 InitOpts.setUsePredefines(!UndefMacros);
1134
Chris Lattnere116ccf2009-04-21 05:40:52 +00001135 // Add macros from the command line.
1136 unsigned d = 0, D = D_macros.size();
1137 unsigned u = 0, U = U_macros.size();
1138 while (d < D || u < U) {
1139 if (u == U || (d < D && D_macros.getPosition(d) < U_macros.getPosition(u)))
1140 InitOpts.addMacroDef(D_macros[d++]);
1141 else
1142 InitOpts.addMacroUndef(U_macros[u++]);
1143 }
1144
1145 // If -imacros are specified, include them now. These are processed before
1146 // any -include directives.
1147 for (unsigned i = 0, e = ImplicitMacroIncludes.size(); i != e; ++i)
1148 InitOpts.addMacroInclude(ImplicitMacroIncludes[i]);
1149
Douglas Gregorb64c1932009-05-12 01:31:05 +00001150 if (!ImplicitIncludePTH.empty() || !ImplicitIncludes.empty() ||
1151 (!ImplicitIncludePCH.empty() && ProgAction == PrintPreprocessedInput)) {
Chris Lattnere116ccf2009-04-21 05:40:52 +00001152 // We want to add these paths to the predefines buffer in order, make a
1153 // temporary vector to sort by their occurrence.
1154 llvm::SmallVector<std::pair<unsigned, std::string*>, 8> OrderedPaths;
1155
1156 if (!ImplicitIncludePTH.empty())
1157 OrderedPaths.push_back(std::make_pair(ImplicitIncludePTH.getPosition(),
1158 &ImplicitIncludePTH));
Douglas Gregorb64c1932009-05-12 01:31:05 +00001159 if (!ImplicitIncludePCH.empty() && ProgAction == PrintPreprocessedInput)
1160 OrderedPaths.push_back(std::make_pair(ImplicitIncludePCH.getPosition(),
1161 &ImplicitIncludePCH));
Chris Lattnere116ccf2009-04-21 05:40:52 +00001162 for (unsigned i = 0, e = ImplicitIncludes.size(); i != e; ++i)
1163 OrderedPaths.push_back(std::make_pair(ImplicitIncludes.getPosition(i),
1164 &ImplicitIncludes[i]));
1165 llvm::array_pod_sort(OrderedPaths.begin(), OrderedPaths.end());
1166
1167
1168 // Now that they are ordered by position, add to the predefines buffer.
1169 for (unsigned i = 0, e = OrderedPaths.size(); i != e; ++i) {
1170 std::string *Ptr = OrderedPaths[i].second;
1171 if (!ImplicitIncludes.empty() &&
1172 Ptr >= &ImplicitIncludes[0] &&
1173 Ptr <= &ImplicitIncludes[ImplicitIncludes.size()-1]) {
1174 InitOpts.addInclude(*Ptr, false);
Douglas Gregorb64c1932009-05-12 01:31:05 +00001175 } else if (Ptr == &ImplicitIncludePTH) {
Chris Lattnere116ccf2009-04-21 05:40:52 +00001176 InitOpts.addInclude(*Ptr, true);
Douglas Gregorb64c1932009-05-12 01:31:05 +00001177 } else {
1178 // We end up here when we're producing preprocessed output and
1179 // we loaded a PCH file. In this case, just include the header
1180 // file that was used to build the precompiled header.
1181 assert(Ptr == &ImplicitIncludePCH);
1182 std::string OriginalFile = PCHReader::getOriginalSourceFile(*Ptr);
1183 if (!OriginalFile.empty()) {
1184 InitOpts.addInclude(OriginalFile, false);
1185 ImplicitIncludePCH.clear();
1186 }
Chris Lattnere116ccf2009-04-21 05:40:52 +00001187 }
1188 }
1189 }
1190}
1191
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001192//===----------------------------------------------------------------------===//
Daniel Dunbar90b18272009-11-04 23:56:25 +00001193// Preprocessor construction
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001194//===----------------------------------------------------------------------===//
1195
Daniel Dunbar90b18272009-11-04 23:56:25 +00001196static Preprocessor *
1197CreatePreprocessor(Diagnostic &Diags,const LangOptions &LangInfo,
1198 TargetInfo &Target, SourceManager &SourceMgr,
1199 HeaderSearch &HeaderInfo) {
1200 PTHManager *PTHMgr = 0;
1201 if (!TokenCache.empty() && !ImplicitIncludePTH.empty()) {
1202 fprintf(stderr, "error: cannot use both -token-cache and -include-pth "
1203 "options\n");
1204 exit(1);
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001205 }
Daniel Dunbar90b18272009-11-04 23:56:25 +00001206
1207 // Use PTH?
1208 if (!TokenCache.empty() || !ImplicitIncludePTH.empty()) {
1209 const std::string& x = TokenCache.empty() ? ImplicitIncludePTH:TokenCache;
1210 PTHMgr = PTHManager::Create(x, &Diags,
1211 TokenCache.empty() ? Diagnostic::Error
1212 : Diagnostic::Warning);
1213 }
1214
1215 if (Diags.hasErrorOccurred())
1216 exit(1);
1217
1218 // Create the Preprocessor.
1219 Preprocessor *PP = new Preprocessor(Diags, LangInfo, Target,
1220 SourceMgr, HeaderInfo, PTHMgr);
1221
1222 // Note that this is different then passing PTHMgr to Preprocessor's ctor.
1223 // That argument is used as the IdentifierInfoLookup argument to
1224 // IdentifierTable's ctor.
1225 if (PTHMgr) {
1226 PTHMgr->setPreprocessor(PP);
1227 PP->setPTHManager(PTHMgr);
1228 }
1229
1230 PreprocessorInitOptions InitOpts;
1231 InitializePreprocessorInitOptions(InitOpts);
1232 InitializePreprocessor(*PP, InitOpts);
1233
1234 return PP;
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001235}
Reid Spencer5f016e22007-07-11 17:01:13 +00001236
Reid Spencer5f016e22007-07-11 17:01:13 +00001237//===----------------------------------------------------------------------===//
1238// Basic Parser driver
1239//===----------------------------------------------------------------------===//
1240
Chris Lattner51574ea2008-04-19 23:25:44 +00001241static void ParseFile(Preprocessor &PP, MinimalAction *PA) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001242 Parser P(PP, *PA);
Ted Kremenek95041a22007-12-19 22:51:13 +00001243 PP.EnterMainSourceFile();
Mike Stump1eb44332009-09-09 15:08:12 +00001244
Reid Spencer5f016e22007-07-11 17:01:13 +00001245 // Parsing the specified input file.
1246 P.ParseTranslationUnit();
1247 delete PA;
1248}
1249
1250//===----------------------------------------------------------------------===//
Daniel Dunbar70f92432008-10-23 05:50:47 +00001251// Code generation options
1252//===----------------------------------------------------------------------===//
1253
1254static llvm::cl::opt<bool>
Chris Lattner15104882009-03-09 22:05:03 +00001255GenerateDebugInfo("g",
1256 llvm::cl::desc("Generate source level debug information"));
1257
Daniel Dunbara034ba82009-02-17 19:47:34 +00001258static llvm::cl::opt<std::string>
1259TargetCPU("mcpu",
1260 llvm::cl::desc("Target a specific cpu type (-mcpu=help for details)"));
1261
Daniel Dunbar868bd0a2009-05-06 03:16:41 +00001262static llvm::cl::list<std::string>
1263TargetFeatures("target-feature", llvm::cl::desc("Target specific attributes"));
1264
Devang Patel24095da2009-06-04 23:32:02 +00001265
1266static llvm::cl::opt<bool>
1267DisableRedZone("disable-red-zone",
1268 llvm::cl::desc("Do not emit code that uses the red zone."),
1269 llvm::cl::init(false));
1270
Devang Patelacebb392009-06-05 22:05:48 +00001271static llvm::cl::opt<bool>
1272NoImplicitFloat("no-implicit-float",
1273 llvm::cl::desc("Don't generate implicit floating point instructions (x86-only)"),
1274 llvm::cl::init(false));
1275
Daniel Dunbar868bd0a2009-05-06 03:16:41 +00001276/// ComputeTargetFeatures - Recompute the target feature list to only
1277/// be the list of things that are enabled, based on the target cpu
1278/// and feature list.
1279static void ComputeFeatureMap(TargetInfo *Target,
1280 llvm::StringMap<bool> &Features) {
Mike Stump1eb44332009-09-09 15:08:12 +00001281 assert(Features.empty() && "invalid map");
Daniel Dunbar868bd0a2009-05-06 03:16:41 +00001282
1283 // Initialize the feature map based on the target.
1284 Target->getDefaultFeatures(TargetCPU, Features);
1285
1286 // Apply the user specified deltas.
Mike Stump1eb44332009-09-09 15:08:12 +00001287 for (llvm::cl::list<std::string>::iterator it = TargetFeatures.begin(),
Daniel Dunbar868bd0a2009-05-06 03:16:41 +00001288 ie = TargetFeatures.end(); it != ie; ++it) {
1289 const char *Name = it->c_str();
Mike Stump1eb44332009-09-09 15:08:12 +00001290
Daniel Dunbar868bd0a2009-05-06 03:16:41 +00001291 // FIXME: Don't handle errors like this.
1292 if (Name[0] != '-' && Name[0] != '+') {
Mike Stump1eb44332009-09-09 15:08:12 +00001293 fprintf(stderr, "error: clang-cc: invalid target feature string: %s\n",
Daniel Dunbar868bd0a2009-05-06 03:16:41 +00001294 Name);
1295 exit(1);
1296 }
Daniel Dunbar17ca3632009-05-06 21:07:50 +00001297 if (!Target->setFeatureEnabled(Features, Name + 1, (Name[0] == '+'))) {
Mike Stump1eb44332009-09-09 15:08:12 +00001298 fprintf(stderr, "error: clang-cc: invalid target feature name: %s\n",
Daniel Dunbar17ca3632009-05-06 21:07:50 +00001299 Name + 1);
Daniel Dunbar868bd0a2009-05-06 03:16:41 +00001300 exit(1);
1301 }
Daniel Dunbar868bd0a2009-05-06 03:16:41 +00001302 }
1303}
1304
Chris Lattner7afae712009-03-16 18:41:18 +00001305static void InitializeCompileOptions(CompileOptions &Opts,
Daniel Dunbar868bd0a2009-05-06 03:16:41 +00001306 const LangOptions &LangOpts,
1307 const llvm::StringMap<bool> &Features) {
Daniel Dunbar70f92432008-10-23 05:50:47 +00001308 Opts.OptimizeSize = OptSize;
Chris Lattner20126042009-03-09 22:00:34 +00001309 Opts.DebugInfo = GenerateDebugInfo;
Daniel Dunbar877db382009-06-02 22:07:45 +00001310
1311 if (DisableLLVMOptimizations) {
1312 Opts.OptimizationLevel = 0;
1313 Opts.Inlining = CompileOptions::NoInlining;
Daniel Dunbarac7ffe02008-10-29 07:56:11 +00001314 } else {
Daniel Dunbar877db382009-06-02 22:07:45 +00001315 if (OptSize) {
1316 // -Os implies -O2
1317 Opts.OptimizationLevel = 2;
1318 } else {
1319 Opts.OptimizationLevel = OptLevel;
1320 }
1321
1322 // We must always run at least the always inlining pass.
1323 if (Opts.OptimizationLevel > 1)
1324 Opts.Inlining = CompileOptions::NormalInlining;
1325 else
1326 Opts.Inlining = CompileOptions::OnlyAlwaysInlining;
Daniel Dunbarac7ffe02008-10-29 07:56:11 +00001327 }
Daniel Dunbar8e8f3b72008-10-29 03:42:18 +00001328
1329 // FIXME: There are llvm-gcc options to control these selectively.
Daniel Dunbar8e8f3b72008-10-29 03:42:18 +00001330 Opts.UnrollLoops = (Opts.OptimizationLevel > 1 && !OptSize);
Chris Lattner7afae712009-03-16 18:41:18 +00001331 Opts.SimplifyLibCalls = !LangOpts.NoBuiltin;
Daniel Dunbardd913e52008-10-31 09:34:21 +00001332
1333#ifdef NDEBUG
1334 Opts.VerifyModule = 0;
1335#endif
Daniel Dunbara034ba82009-02-17 19:47:34 +00001336
1337 Opts.CPU = TargetCPU;
Daniel Dunbar868bd0a2009-05-06 03:16:41 +00001338 Opts.Features.clear();
Mike Stump1eb44332009-09-09 15:08:12 +00001339 for (llvm::StringMap<bool>::const_iterator it = Features.begin(),
Daniel Dunbar868bd0a2009-05-06 03:16:41 +00001340 ie = Features.end(); it != ie; ++it) {
1341 // FIXME: If we are completely confident that we have the right
1342 // set, we only need to pass the minuses.
1343 std::string Name(it->second ? "+" : "-");
1344 Name += it->first();
1345 Opts.Features.push_back(Name);
1346 }
Mike Stump1eb44332009-09-09 15:08:12 +00001347
Chris Lattnerbd360642009-03-26 05:00:52 +00001348 Opts.NoCommon = NoCommon | LangOpts.CPlusPlus;
Mike Stump1eb44332009-09-09 15:08:12 +00001349
Chris Lattner44502662009-02-18 01:23:44 +00001350 // Handle -ftime-report.
1351 Opts.TimePasses = TimeReport;
Devang Patel24095da2009-06-04 23:32:02 +00001352
1353 Opts.DisableRedZone = DisableRedZone;
Devang Patelacebb392009-06-05 22:05:48 +00001354 Opts.NoImplicitFloat = NoImplicitFloat;
Tanya Lattner59876c22009-11-04 01:18:09 +00001355
1356 Opts.MergeAllConstants = !NoMergeConstants;
Daniel Dunbar70f92432008-10-23 05:50:47 +00001357}
1358
1359//===----------------------------------------------------------------------===//
Douglas Gregor26df2f02009-04-02 19:05:20 +00001360// Fix-It Options
1361//===----------------------------------------------------------------------===//
1362static llvm::cl::list<ParsedSourceLocation>
1363FixItAtLocations("fixit-at", llvm::cl::value_desc("source-location"),
1364 llvm::cl::desc("Perform Fix-It modifications at the given source location"));
1365
1366//===----------------------------------------------------------------------===//
Eli Friedmanc6d656e2009-05-18 22:39:16 +00001367// ObjC Rewriter Options
1368//===----------------------------------------------------------------------===//
1369static llvm::cl::opt<bool>
1370SilenceRewriteMacroWarning("Wno-rewrite-macros", llvm::cl::init(false),
1371 llvm::cl::desc("Silence ObjC rewriting warnings"));
1372
1373//===----------------------------------------------------------------------===//
Eli Friedman0eeb86e2009-05-19 01:17:04 +00001374// Warning Options
1375//===----------------------------------------------------------------------===//
1376
1377// This gets all -W options, including -Werror, -W[no-]system-headers, etc. The
1378// driver has stripped off -Wa,foo etc. The driver has also translated -W to
1379// -Wextra, so we don't need to worry about it.
1380static llvm::cl::list<std::string>
1381OptWarnings("W", llvm::cl::Prefix, llvm::cl::ValueOptional);
1382
1383static llvm::cl::opt<bool> OptPedantic("pedantic");
1384static llvm::cl::opt<bool> OptPedanticErrors("pedantic-errors");
1385static llvm::cl::opt<bool> OptNoWarnings("w");
1386
1387//===----------------------------------------------------------------------===//
Eli Friedman12d3b1d2009-05-19 03:06:47 +00001388// Preprocessing (-E mode) Options
1389//===----------------------------------------------------------------------===//
1390static llvm::cl::opt<bool>
1391DisableLineMarkers("P", llvm::cl::desc("Disable linemarker output in -E mode"));
1392static llvm::cl::opt<bool>
1393EnableCommentOutput("C", llvm::cl::desc("Enable comment output in -E mode"));
1394static llvm::cl::opt<bool>
1395EnableMacroCommentOutput("CC",
1396 llvm::cl::desc("Enable comment output in -E mode, "
1397 "even from macro expansions"));
1398static llvm::cl::opt<bool>
1399DumpMacros("dM", llvm::cl::desc("Print macro definitions in -E mode instead of"
1400 " normal output"));
1401static llvm::cl::opt<bool>
1402DumpDefines("dD", llvm::cl::desc("Print macro definitions in -E mode in "
1403 "addition to normal output"));
Eli Friedmanb5c8f8b2009-05-19 03:35:57 +00001404
1405//===----------------------------------------------------------------------===//
1406// Dependency file options
1407//===----------------------------------------------------------------------===//
1408static llvm::cl::opt<std::string>
1409DependencyFile("dependency-file",
1410 llvm::cl::desc("Filename (or -) to write dependency output to"));
1411
1412static llvm::cl::opt<bool>
1413DependenciesIncludeSystemHeaders("sys-header-deps",
1414 llvm::cl::desc("Include system headers in dependency output"));
1415
1416static llvm::cl::list<std::string>
1417DependencyTargets("MT",
1418 llvm::cl::desc("Specify target for dependency"));
1419
1420// FIXME: Implement feature
1421static llvm::cl::opt<bool>
1422PhonyDependencyTarget("MP",
1423 llvm::cl::desc("Create phony target for each dependency "
1424 "(other than main file)"));
1425
Eli Friedman12d3b1d2009-05-19 03:06:47 +00001426//===----------------------------------------------------------------------===//
Eli Friedmane71b85f2009-05-19 10:18:02 +00001427// Analysis options
1428//===----------------------------------------------------------------------===//
1429
1430static llvm::cl::list<Analyses>
1431AnalysisList(llvm::cl::desc("Source Code Analysis - Checks and Analyses"),
1432llvm::cl::values(
1433#define ANALYSIS(NAME, CMDFLAG, DESC, SCOPE)\
1434clEnumValN(NAME, CMDFLAG, DESC),
Eli Friedman0ec78fa2009-05-19 21:10:40 +00001435#include "clang/Frontend/Analyses.def"
Eli Friedmane71b85f2009-05-19 10:18:02 +00001436clEnumValEnd));
1437
Mike Stump1eb44332009-09-09 15:08:12 +00001438static llvm::cl::opt<AnalysisStores>
Eli Friedmane71b85f2009-05-19 10:18:02 +00001439AnalysisStoreOpt("analyzer-store",
1440 llvm::cl::desc("Source Code Analysis - Abstract Memory Store Models"),
1441 llvm::cl::init(BasicStoreModel),
1442 llvm::cl::values(
1443#define ANALYSIS_STORE(NAME, CMDFLAG, DESC, CREATFN)\
1444clEnumValN(NAME##Model, CMDFLAG, DESC),
Eli Friedman0ec78fa2009-05-19 21:10:40 +00001445#include "clang/Frontend/Analyses.def"
Eli Friedmane71b85f2009-05-19 10:18:02 +00001446clEnumValEnd));
1447
Mike Stump1eb44332009-09-09 15:08:12 +00001448static llvm::cl::opt<AnalysisConstraints>
Eli Friedmane71b85f2009-05-19 10:18:02 +00001449AnalysisConstraintsOpt("analyzer-constraints",
1450 llvm::cl::desc("Source Code Analysis - Symbolic Constraint Engines"),
1451 llvm::cl::init(RangeConstraintsModel),
1452 llvm::cl::values(
1453#define ANALYSIS_CONSTRAINTS(NAME, CMDFLAG, DESC, CREATFN)\
1454clEnumValN(NAME##Model, CMDFLAG, DESC),
Eli Friedman0ec78fa2009-05-19 21:10:40 +00001455#include "clang/Frontend/Analyses.def"
Eli Friedmane71b85f2009-05-19 10:18:02 +00001456clEnumValEnd));
1457
1458static llvm::cl::opt<AnalysisDiagClients>
1459AnalysisDiagOpt("analyzer-output",
1460 llvm::cl::desc("Source Code Analysis - Output Options"),
1461 llvm::cl::init(PD_HTML),
1462 llvm::cl::values(
1463#define ANALYSIS_DIAGNOSTICS(NAME, CMDFLAG, DESC, CREATFN, AUTOCREATE)\
1464clEnumValN(PD_##NAME, CMDFLAG, DESC),
Eli Friedman0ec78fa2009-05-19 21:10:40 +00001465#include "clang/Frontend/Analyses.def"
Eli Friedmane71b85f2009-05-19 10:18:02 +00001466clEnumValEnd));
1467
1468static llvm::cl::opt<bool>
1469VisualizeEGDot("analyzer-viz-egraph-graphviz",
1470 llvm::cl::desc("Display exploded graph using GraphViz"));
1471
1472static llvm::cl::opt<bool>
1473VisualizeEGUbi("analyzer-viz-egraph-ubigraph",
1474 llvm::cl::desc("Display exploded graph using Ubigraph"));
1475
1476static llvm::cl::opt<bool>
1477AnalyzeAll("analyzer-opt-analyze-headers",
1478 llvm::cl::desc("Force the static analyzer to analyze "
1479 "functions defined in header files"));
1480
1481static llvm::cl::opt<bool>
1482AnalyzerDisplayProgress("analyzer-display-progress",
1483 llvm::cl::desc("Emit verbose output about the analyzer's progress."));
1484
1485static llvm::cl::opt<bool>
1486PurgeDead("analyzer-purge-dead",
1487 llvm::cl::init(true),
1488 llvm::cl::desc("Remove dead symbols, bindings, and constraints before"
1489 " processing a statement."));
1490
1491static llvm::cl::opt<bool>
1492EagerlyAssume("analyzer-eagerly-assume",
1493 llvm::cl::init(false),
1494 llvm::cl::desc("Eagerly assume the truth/falseness of some "
1495 "symbolic constraints."));
1496
1497static llvm::cl::opt<std::string>
1498AnalyzeSpecificFunction("analyze-function",
1499 llvm::cl::desc("Run analysis on specific function"));
1500
1501static llvm::cl::opt<bool>
1502TrimGraph("trim-egraph",
1503 llvm::cl::desc("Only show error-related paths in the analysis graph"));
1504
1505static AnalyzerOptions ReadAnalyzerOptions() {
1506 AnalyzerOptions Opts;
1507 Opts.AnalysisList = AnalysisList;
1508 Opts.AnalysisStoreOpt = AnalysisStoreOpt;
1509 Opts.AnalysisConstraintsOpt = AnalysisConstraintsOpt;
1510 Opts.AnalysisDiagOpt = AnalysisDiagOpt;
1511 Opts.VisualizeEGDot = VisualizeEGDot;
1512 Opts.VisualizeEGUbi = VisualizeEGUbi;
1513 Opts.AnalyzeAll = AnalyzeAll;
1514 Opts.AnalyzerDisplayProgress = AnalyzerDisplayProgress;
1515 Opts.PurgeDead = PurgeDead;
1516 Opts.EagerlyAssume = EagerlyAssume;
1517 Opts.AnalyzeSpecificFunction = AnalyzeSpecificFunction;
1518 Opts.TrimGraph = TrimGraph;
1519 return Opts;
1520}
1521
1522//===----------------------------------------------------------------------===//
Chris Lattner75a97cb2009-04-17 21:05:01 +00001523// -dump-build-information Stuff
1524//===----------------------------------------------------------------------===//
1525
1526static llvm::cl::opt<std::string>
1527DumpBuildInformation("dump-build-information",
1528 llvm::cl::value_desc("filename"),
1529 llvm::cl::desc("output a dump of some build information to a file"));
1530
1531static llvm::raw_ostream *BuildLogFile = 0;
1532
1533/// LoggingDiagnosticClient - This is a simple diagnostic client that forwards
1534/// all diagnostics to both BuildLogFile and a chained DiagnosticClient.
1535namespace {
1536class LoggingDiagnosticClient : public DiagnosticClient {
1537 llvm::OwningPtr<DiagnosticClient> Chain1;
1538 llvm::OwningPtr<DiagnosticClient> Chain2;
1539public:
Mike Stump1eb44332009-09-09 15:08:12 +00001540
Chris Lattner75a97cb2009-04-17 21:05:01 +00001541 LoggingDiagnosticClient(DiagnosticClient *Normal) {
1542 // Output diags both where requested...
1543 Chain1.reset(Normal);
1544 // .. and to our log file.
Daniel Dunbareace8742009-11-04 06:24:30 +00001545 Chain2.reset(new TextDiagnosticPrinter(*BuildLogFile, DiagOpts));
Chris Lattner75a97cb2009-04-17 21:05:01 +00001546 }
Mike Stump1eb44332009-09-09 15:08:12 +00001547
Chris Lattner75a97cb2009-04-17 21:05:01 +00001548 virtual void setLangOptions(const LangOptions *LO) {
1549 Chain1->setLangOptions(LO);
1550 Chain2->setLangOptions(LO);
1551 }
Mike Stump1eb44332009-09-09 15:08:12 +00001552
Chris Lattner75a97cb2009-04-17 21:05:01 +00001553 virtual bool IncludeInDiagnosticCounts() const {
1554 return Chain1->IncludeInDiagnosticCounts();
1555 }
1556
1557 virtual void HandleDiagnostic(Diagnostic::Level DiagLevel,
1558 const DiagnosticInfo &Info) {
1559 Chain1->HandleDiagnostic(DiagLevel, Info);
1560 Chain2->HandleDiagnostic(DiagLevel, Info);
1561 }
1562};
1563} // end anonymous namespace.
1564
1565static void SetUpBuildDumpLog(unsigned argc, char **argv,
1566 llvm::OwningPtr<DiagnosticClient> &DiagClient) {
Mike Stump1eb44332009-09-09 15:08:12 +00001567
Chris Lattner75a97cb2009-04-17 21:05:01 +00001568 std::string ErrorInfo;
Chris Lattner92bcc272009-08-23 02:59:41 +00001569 BuildLogFile = new llvm::raw_fd_ostream(DumpBuildInformation.c_str(),
Dan Gohmanb044c472009-08-25 15:36:09 +00001570 ErrorInfo);
Mike Stump1eb44332009-09-09 15:08:12 +00001571
Chris Lattner75a97cb2009-04-17 21:05:01 +00001572 if (!ErrorInfo.empty()) {
1573 llvm::errs() << "error opening -dump-build-information file '"
1574 << DumpBuildInformation << "', option ignored!\n";
1575 delete BuildLogFile;
1576 BuildLogFile = 0;
1577 DumpBuildInformation = "";
1578 return;
1579 }
1580
1581 (*BuildLogFile) << "clang-cc command line arguments: ";
1582 for (unsigned i = 0; i != argc; ++i)
1583 (*BuildLogFile) << argv[i] << ' ';
1584 (*BuildLogFile) << '\n';
Mike Stump1eb44332009-09-09 15:08:12 +00001585
Chris Lattner75a97cb2009-04-17 21:05:01 +00001586 // LoggingDiagnosticClient - Insert a new logging diagnostic client in between
1587 // the diagnostic producers and the normal receiver.
1588 DiagClient.reset(new LoggingDiagnosticClient(DiagClient.take()));
1589}
1590
1591
1592
1593//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +00001594// Main driver
1595//===----------------------------------------------------------------------===//
1596
Chris Lattner92bcc272009-08-23 02:59:41 +00001597static llvm::raw_ostream *ComputeOutFile(const std::string &InFile,
1598 const char *Extension,
Eli Friedman66d6f042009-05-18 22:20:00 +00001599 bool Binary,
1600 llvm::sys::Path& OutPath) {
Chris Lattner92bcc272009-08-23 02:59:41 +00001601 llvm::raw_ostream *Ret;
Eli Friedman66d6f042009-05-18 22:20:00 +00001602 std::string OutFile;
Chris Lattner92bcc272009-08-23 02:59:41 +00001603 if (!OutputFile.empty())
Eli Friedman66d6f042009-05-18 22:20:00 +00001604 OutFile = OutputFile;
Chris Lattner92bcc272009-08-23 02:59:41 +00001605 else if (InFile == "-") {
1606 OutFile = "-";
Eli Friedman66d6f042009-05-18 22:20:00 +00001607 } else if (Extension) {
1608 llvm::sys::Path Path(InFile);
1609 Path.eraseSuffix();
1610 Path.appendSuffix(Extension);
Chris Lattnerd57a7ef2009-08-23 22:45:33 +00001611 OutFile = Path.str();
Eli Friedman66d6f042009-05-18 22:20:00 +00001612 } else {
Chris Lattner92bcc272009-08-23 02:59:41 +00001613 OutFile = "-";
Chris Lattner8a5c8092009-02-18 01:20:05 +00001614 }
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +00001615
Chris Lattner92bcc272009-08-23 02:59:41 +00001616 std::string Error;
1617 Ret = new llvm::raw_fd_ostream(OutFile.c_str(), Error,
Dan Gohmanb044c472009-08-25 15:36:09 +00001618 (Binary ? llvm::raw_fd_ostream::F_Binary : 0));
Chris Lattner92bcc272009-08-23 02:59:41 +00001619 if (!Error.empty()) {
1620 // FIXME: Don't fail this way.
1621 llvm::errs() << "ERROR: " << Error << "\n";
1622 ::exit(1);
Ted Kremenekdb094a22007-12-05 18:27:04 +00001623 }
Mike Stump1eb44332009-09-09 15:08:12 +00001624
Chris Lattner92bcc272009-08-23 02:59:41 +00001625 if (OutFile != "-")
1626 OutPath = OutFile;
Eli Friedman66d6f042009-05-18 22:20:00 +00001627
1628 return Ret;
Ted Kremenekdb094a22007-12-05 18:27:04 +00001629}
1630
Daniel Dunbar0794d8d2009-09-17 00:48:00 +00001631static ASTConsumer *CreateConsumerAction(Preprocessor &PP,
1632 const std::string &InFile,
1633 ProgActions PA,
1634 llvm::OwningPtr<llvm::raw_ostream> &OS,
1635 llvm::sys::Path &OutPath,
1636 const llvm::StringMap<bool> &Features,
1637 llvm::LLVMContext& Context) {
Ted Kremenek85888962008-10-21 00:54:44 +00001638 switch (PA) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001639 default:
Daniel Dunbar0794d8d2009-09-17 00:48:00 +00001640 return 0;
Eli Friedman66d6f042009-05-18 22:20:00 +00001641
1642 case ASTPrint:
1643 OS.reset(ComputeOutFile(InFile, 0, false, OutPath));
Daniel Dunbar0794d8d2009-09-17 00:48:00 +00001644 return CreateASTPrinter(OS.get());
Mike Stump1eb44332009-09-09 15:08:12 +00001645
Douglas Gregoree75c052009-05-21 20:55:50 +00001646 case ASTPrintXML:
1647 OS.reset(ComputeOutFile(InFile, "xml", false, OutPath));
Daniel Dunbar0794d8d2009-09-17 00:48:00 +00001648 return CreateASTPrinterXML(OS.get());
Douglas Gregoree75c052009-05-21 20:55:50 +00001649
Eli Friedman66d6f042009-05-18 22:20:00 +00001650 case ASTDump:
Daniel Dunbar0794d8d2009-09-17 00:48:00 +00001651 return CreateASTDumper();
Eli Friedman66d6f042009-05-18 22:20:00 +00001652
Eli Friedman66d6f042009-05-18 22:20:00 +00001653 case ASTView:
Daniel Dunbar0794d8d2009-09-17 00:48:00 +00001654 return CreateASTViewer();
Eli Friedman66d6f042009-05-18 22:20:00 +00001655
1656 case PrintDeclContext:
Daniel Dunbar0794d8d2009-09-17 00:48:00 +00001657 return CreateDeclContextPrinter();
Eli Friedman66d6f042009-05-18 22:20:00 +00001658
Anders Carlsson78762eb2009-09-24 18:54:49 +00001659 case DumpRecordLayouts:
1660 return CreateRecordLayoutDumper();
1661
Eli Friedman66d6f042009-05-18 22:20:00 +00001662 case InheritanceView:
Daniel Dunbar0794d8d2009-09-17 00:48:00 +00001663 return CreateInheritanceViewer(InheritanceViewCls);
Eli Friedman66d6f042009-05-18 22:20:00 +00001664
1665 case EmitAssembly:
1666 case EmitLLVM:
Mike Stump1eb44332009-09-09 15:08:12 +00001667 case EmitBC:
Eli Friedman66d6f042009-05-18 22:20:00 +00001668 case EmitLLVMOnly: {
1669 BackendAction Act;
1670 if (ProgAction == EmitAssembly) {
1671 Act = Backend_EmitAssembly;
1672 OS.reset(ComputeOutFile(InFile, "s", true, OutPath));
1673 } else if (ProgAction == EmitLLVM) {
1674 Act = Backend_EmitLL;
1675 OS.reset(ComputeOutFile(InFile, "ll", true, OutPath));
1676 } else if (ProgAction == EmitLLVMOnly) {
1677 Act = Backend_EmitNothing;
1678 } else {
1679 Act = Backend_EmitBC;
1680 OS.reset(ComputeOutFile(InFile, "bc", true, OutPath));
Ted Kremenekdb094a22007-12-05 18:27:04 +00001681 }
Ted Kremenekfdfc1982007-12-19 22:24:34 +00001682
Eli Friedman66d6f042009-05-18 22:20:00 +00001683 CompileOptions Opts;
1684 InitializeCompileOptions(Opts, PP.getLangOptions(), Features);
Daniel Dunbar0794d8d2009-09-17 00:48:00 +00001685 return CreateBackendConsumer(Act, PP.getDiagnostics(), PP.getLangOptions(),
1686 Opts, InFile, OS.get(), Context);
Eli Friedman66d6f042009-05-18 22:20:00 +00001687 }
1688
Daniel Dunbar0794d8d2009-09-17 00:48:00 +00001689 case RewriteObjC:
1690 OS.reset(ComputeOutFile(InFile, "cpp", true, OutPath));
1691 return CreateObjCRewriter(InFile, OS.get(), PP.getDiagnostics(),
1692 PP.getLangOptions(), SilenceRewriteMacroWarning);
1693
1694 case RewriteBlocks:
1695 return CreateBlockRewriter(InFile, PP.getDiagnostics(),
1696 PP.getLangOptions());
1697 }
1698}
1699
1700/// ProcessInputFile - Process a single input file with the specified state.
1701///
Daniel Dunbar90b18272009-11-04 23:56:25 +00001702static void ProcessInputFile(Preprocessor &PP, const std::string &InFile,
1703 ProgActions PA,
Daniel Dunbar0794d8d2009-09-17 00:48:00 +00001704 const llvm::StringMap<bool> &Features,
1705 llvm::LLVMContext& Context) {
1706 llvm::OwningPtr<llvm::raw_ostream> OS;
1707 llvm::OwningPtr<ASTConsumer> Consumer;
1708 bool ClearSourceMgr = false;
1709 FixItRewriter *FixItRewrite = 0;
1710 bool CompleteTranslationUnit = true;
1711 llvm::sys::Path OutPath;
1712
1713 switch (PA) {
1714 default:
1715 Consumer.reset(CreateConsumerAction(PP, InFile, PA, OS, OutPath,
1716 Features, Context));
1717
1718 if (!Consumer.get()) {
Daniel Dunbar8cb65622009-10-29 21:05:18 +00001719 PP.getDiagnostics().Report(FullSourceLoc(),
1720 diag::err_fe_invalid_ast_action);
Daniel Dunbar0794d8d2009-09-17 00:48:00 +00001721 return;
1722 }
1723
1724 break;;
1725
1726 case EmitHTML:
1727 OS.reset(ComputeOutFile(InFile, 0, true, OutPath));
Daniel Dunbar90b18272009-11-04 23:56:25 +00001728 Consumer.reset(CreateHTMLPrinter(OS.get(), PP));
Daniel Dunbar0794d8d2009-09-17 00:48:00 +00001729 break;
1730
1731 case RunAnalysis:
Daniel Dunbarefceabd2009-11-05 02:41:58 +00001732 Consumer.reset(CreateAnalysisConsumer(PP, OutputFile,
Daniel Dunbar0794d8d2009-09-17 00:48:00 +00001733 ReadAnalyzerOptions()));
1734 break;
1735
Eli Friedman66d6f042009-05-18 22:20:00 +00001736 case GeneratePCH:
Douglas Gregore650c8c2009-07-07 00:12:59 +00001737 if (RelocatablePCH.getValue() && !isysroot.getNumOccurrences()) {
1738 PP.Diag(SourceLocation(), diag::err_relocatable_without_without_isysroot);
1739 RelocatablePCH.setValue(false);
1740 }
Mike Stump1eb44332009-09-09 15:08:12 +00001741
Eli Friedman66d6f042009-05-18 22:20:00 +00001742 OS.reset(ComputeOutFile(InFile, 0, true, OutPath));
Douglas Gregore650c8c2009-07-07 00:12:59 +00001743 if (RelocatablePCH.getValue())
1744 Consumer.reset(CreatePCHGenerator(PP, OS.get(), isysroot.c_str()));
1745 else
1746 Consumer.reset(CreatePCHGenerator(PP, OS.get()));
Eli Friedman66d6f042009-05-18 22:20:00 +00001747 CompleteTranslationUnit = false;
1748 break;
1749
Chris Lattnerc106c102008-10-12 05:03:36 +00001750 case DumpRawTokens: {
Chris Lattner47099742009-02-18 01:51:21 +00001751 llvm::TimeRegion Timer(ClangFrontendTimer);
Chris Lattnerc106c102008-10-12 05:03:36 +00001752 SourceManager &SM = PP.getSourceManager();
Chris Lattnerc106c102008-10-12 05:03:36 +00001753 // Start lexing the specified input file.
Chris Lattner025c3a62009-01-17 07:35:14 +00001754 Lexer RawLex(SM.getMainFileID(), SM, PP.getLangOptions());
Chris Lattnerc106c102008-10-12 05:03:36 +00001755 RawLex.SetKeepWhitespaceMode(true);
1756
1757 Token RawTok;
Chris Lattnerc106c102008-10-12 05:03:36 +00001758 RawLex.LexFromRawLexer(RawTok);
1759 while (RawTok.isNot(tok::eof)) {
1760 PP.DumpToken(RawTok, true);
1761 fprintf(stderr, "\n");
1762 RawLex.LexFromRawLexer(RawTok);
1763 }
1764 ClearSourceMgr = true;
1765 break;
1766 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001767 case DumpTokens: { // Token dump mode.
Chris Lattner47099742009-02-18 01:51:21 +00001768 llvm::TimeRegion Timer(ClangFrontendTimer);
Chris Lattnerd2177732007-07-20 16:59:19 +00001769 Token Tok;
Chris Lattnerc106c102008-10-12 05:03:36 +00001770 // Start preprocessing the specified input file.
Ted Kremenek95041a22007-12-19 22:51:13 +00001771 PP.EnterMainSourceFile();
Reid Spencer5f016e22007-07-11 17:01:13 +00001772 do {
1773 PP.Lex(Tok);
1774 PP.DumpToken(Tok, true);
1775 fprintf(stderr, "\n");
Chris Lattner057aaf62007-10-09 18:03:42 +00001776 } while (Tok.isNot(tok::eof));
Chris Lattnerbd247762007-07-22 06:05:44 +00001777 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001778 break;
1779 }
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001780 case RunPreprocessorOnly:
Reid Spencer5f016e22007-07-11 17:01:13 +00001781 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001782
Douglas Gregorbf1bd6e2009-04-02 23:43:50 +00001783 case GeneratePTH: {
Chris Lattner47099742009-02-18 01:51:21 +00001784 llvm::TimeRegion Timer(ClangFrontendTimer);
Eli Friedmanf54fce82009-05-19 01:02:07 +00001785 if (OutputFile.empty() || OutputFile == "-") {
1786 // FIXME: Don't fail this way.
1787 // FIXME: Verify that we can actually seek in the given file.
Chris Lattner92bcc272009-08-23 02:59:41 +00001788 llvm::errs() << "ERROR: PTH requires an seekable file for output!\n";
Eli Friedmanf54fce82009-05-19 01:02:07 +00001789 ::exit(1);
1790 }
1791 OS.reset(ComputeOutFile(InFile, 0, true, OutPath));
1792 CacheTokens(PP, static_cast<llvm::raw_fd_ostream*>(OS.get()));
Ted Kremenek85888962008-10-21 00:54:44 +00001793 ClearSourceMgr = true;
1794 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001795 }
Douglas Gregor6ab35242009-04-09 21:40:53 +00001796
Chris Lattnercc7dea82009-04-27 22:02:30 +00001797 case PrintPreprocessedInput:
Eli Friedmanf54fce82009-05-19 01:02:07 +00001798 OS.reset(ComputeOutFile(InFile, 0, true, OutPath));
Reid Spencer5f016e22007-07-11 17:01:13 +00001799 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001800
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001801 case ParseNoop:
Reid Spencer5f016e22007-07-11 17:01:13 +00001802 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001803
Chris Lattner47099742009-02-18 01:51:21 +00001804 case ParsePrintCallbacks: {
1805 llvm::TimeRegion Timer(ClangFrontendTimer);
Eli Friedmanf54fce82009-05-19 01:02:07 +00001806 OS.reset(ComputeOutFile(InFile, 0, true, OutPath));
1807 ParseFile(PP, CreatePrintParserActionsAction(PP, OS.get()));
Chris Lattnerbd247762007-07-22 06:05:44 +00001808 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001809 break;
Chris Lattner47099742009-02-18 01:51:21 +00001810 }
1811
1812 case ParseSyntaxOnly: { // -fsyntax-only
1813 llvm::TimeRegion Timer(ClangFrontendTimer);
Ted Kremenek7e7e6252008-08-08 02:46:37 +00001814 Consumer.reset(new ASTConsumer());
Ted Kremenek2bf55142007-09-17 20:49:30 +00001815 break;
Chris Lattner47099742009-02-18 01:51:21 +00001816 }
Mike Stump1eb44332009-09-09 15:08:12 +00001817
Chris Lattnerb57e3d42008-05-08 06:52:13 +00001818 case RewriteMacros:
Eli Friedmanf54fce82009-05-19 01:02:07 +00001819 OS.reset(ComputeOutFile(InFile, 0, true, OutPath));
1820 RewriteMacrosInInput(PP, OS.get());
Chris Lattnerb57e3d42008-05-08 06:52:13 +00001821 ClearSourceMgr = true;
1822 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001823
Eli Friedmanf54fce82009-05-19 01:02:07 +00001824 case RewriteTest:
1825 OS.reset(ComputeOutFile(InFile, 0, true, OutPath));
1826 DoRewriteTest(PP, OS.get());
Chris Lattnerb13c5ee2008-10-12 05:29:20 +00001827 ClearSourceMgr = true;
1828 break;
Douglas Gregor558cb562009-04-02 01:08:08 +00001829
1830 case FixIt:
1831 llvm::TimeRegion Timer(ClangFrontendTimer);
1832 Consumer.reset(new ASTConsumer());
Douglas Gregorde4bf6a2009-04-02 17:13:00 +00001833 FixItRewrite = new FixItRewriter(PP.getDiagnostics(),
Chris Lattner2c78b872009-04-14 23:22:57 +00001834 PP.getSourceManager(),
1835 PP.getLangOptions());
Douglas Gregor558cb562009-04-02 01:08:08 +00001836 break;
Chris Lattner47099742009-02-18 01:51:21 +00001837 }
Ted Kremenek46157b52009-01-28 04:29:29 +00001838
Chris Lattner1aee61a2009-04-27 21:25:27 +00001839 if (FixItAtLocations.size() > 0) {
1840 // Even without the "-fixit" flag, with may have some specific
1841 // locations where the user has requested fixes. Process those
1842 // locations now.
1843 if (!FixItRewrite)
1844 FixItRewrite = new FixItRewriter(PP.getDiagnostics(),
1845 PP.getSourceManager(),
1846 PP.getLangOptions());
Chris Lattner9ecd26a2009-03-28 01:37:17 +00001847
Chris Lattner1aee61a2009-04-27 21:25:27 +00001848 bool AddedFixitLocation = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001849 for (unsigned Idx = 0, Last = FixItAtLocations.size();
Chris Lattner1aee61a2009-04-27 21:25:27 +00001850 Idx != Last; ++Idx) {
1851 RequestedSourceLocation Requested;
Argyrios Kyrtzidis34d25d82009-06-23 22:01:39 +00001852 if (ResolveParsedLocation(FixItAtLocations[Idx],
1853 PP.getFileManager(), Requested)) {
Chris Lattner1aee61a2009-04-27 21:25:27 +00001854 fprintf(stderr, "FIX-IT could not find file \"%s\"\n",
1855 FixItAtLocations[Idx].FileName.c_str());
1856 } else {
1857 FixItRewrite->addFixItLocation(Requested);
1858 AddedFixitLocation = true;
Douglas Gregor26df2f02009-04-02 19:05:20 +00001859 }
1860 }
1861
Chris Lattner1aee61a2009-04-27 21:25:27 +00001862 if (!AddedFixitLocation) {
1863 // All of the fix-it locations were bad. Don't fix anything.
1864 delete FixItRewrite;
1865 FixItRewrite = 0;
1866 }
1867 }
1868
1869 llvm::OwningPtr<ASTContext> ContextOwner;
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001870 if (Consumer)
Chris Lattner9ecd26a2009-03-28 01:37:17 +00001871 ContextOwner.reset(new ASTContext(PP.getLangOptions(),
1872 PP.getSourceManager(),
1873 PP.getTargetInfo(),
1874 PP.getIdentifierTable(),
1875 PP.getSelectorTable(),
Chris Lattner1b63e4f2009-06-14 01:54:56 +00001876 PP.getBuiltinInfo(),
Douglas Gregor2deaea32009-04-22 18:49:13 +00001877 /* FreeMemory = */ !DisableFree,
Chris Lattner1b63e4f2009-06-14 01:54:56 +00001878 /* size_reserve = */0));
Mike Stump1eb44332009-09-09 15:08:12 +00001879
Chris Lattnercc7dea82009-04-27 22:02:30 +00001880 llvm::OwningPtr<PCHReader> Reader;
1881 llvm::OwningPtr<ExternalASTSource> Source;
Mike Stump1eb44332009-09-09 15:08:12 +00001882
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001883 if (!ImplicitIncludePCH.empty()) {
Douglas Gregore650c8c2009-07-07 00:12:59 +00001884 // If the user specified -isysroot, it will be used for relocatable PCH
1885 // files.
1886 const char *isysrootPCH = 0;
1887 if (isysroot.getNumOccurrences() != 0)
1888 isysrootPCH = isysroot.c_str();
Mike Stump1eb44332009-09-09 15:08:12 +00001889
Douglas Gregore650c8c2009-07-07 00:12:59 +00001890 Reader.reset(new PCHReader(PP, ContextOwner.get(), isysrootPCH));
Mike Stump1eb44332009-09-09 15:08:12 +00001891
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001892 // The user has asked us to include a precompiled header. Load
1893 // the precompiled header into the AST context.
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001894 switch (Reader->ReadPCH(ImplicitIncludePCH)) {
1895 case PCHReader::Success: {
Douglas Gregore721f952009-04-28 18:58:38 +00001896 // Set the predefines buffer as suggested by the PCH
1897 // reader. Typically, the predefines buffer will be empty.
1898 PP.setPredefines(Reader->getSuggestedPredefines());
1899
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001900 // Attach the PCH reader to the AST context as an external AST
1901 // source, so that declarations will be deserialized from the
1902 // PCH file as needed.
Chris Lattnercc7dea82009-04-27 22:02:30 +00001903 if (ContextOwner) {
1904 Source.reset(Reader.take());
Douglas Gregore1d918e2009-04-10 23:10:45 +00001905 ContextOwner->setExternalSource(Source);
Chris Lattnercc7dea82009-04-27 22:02:30 +00001906 }
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001907 break;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001908 }
1909
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001910 case PCHReader::Failure:
1911 // Unrecoverable failure: don't even try to process the input
1912 // file.
1913 return;
1914
1915 case PCHReader::IgnorePCH:
Douglas Gregor1ab86ac2009-04-28 22:01:16 +00001916 // No suitable PCH file could be found. Return an error.
1917 return;
1918
1919#if 0
1920 // FIXME: We can recover from failed attempts to load PCH
1921 // files. This code will do so, if we ever want to enable it.
1922
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001923 // We delayed the initialization of builtins in the hope of
1924 // loading the PCH file. Since the PCH file could not be
1925 // loaded, initialize builtins now.
1926 if (ContextOwner)
1927 ContextOwner->InitializeBuiltins(PP.getIdentifierTable());
Douglas Gregor1ab86ac2009-04-28 22:01:16 +00001928#endif
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001929 }
1930
1931 // Finish preprocessor initialization. We do this now (rather
1932 // than earlier) because this initialization creates new source
1933 // location entries in the source manager, which must come after
1934 // the source location entries for the PCH file.
1935 if (InitializeSourceManager(PP, InFile))
1936 return;
Ted Kremenek46157b52009-01-28 04:29:29 +00001937 }
Daniel Dunbarbea5a842009-10-29 01:53:18 +00001938
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001939 // If we have an ASTConsumer, run the parser with it.
Douglas Gregor81b747b2009-09-17 21:32:03 +00001940 if (Consumer) {
1941 CodeCompleteConsumer *(*CreateCodeCompleter)(Sema &, void *) = 0;
1942 void *CreateCodeCompleterData = 0;
Daniel Dunbarbea5a842009-10-29 01:53:18 +00001943
Douglas Gregorb657f112009-09-22 21:11:38 +00001944 if (!CodeCompletionAt.FileName.empty()) {
1945 // Tell the source manager to chop off the given file at a specific
1946 // line and column.
Daniel Dunbarbea5a842009-10-29 01:53:18 +00001947 if (const FileEntry *Entry
Douglas Gregorb657f112009-09-22 21:11:38 +00001948 = PP.getFileManager().getFile(CodeCompletionAt.FileName)) {
1949 // Truncate the named file at the given line/column.
1950 PP.getSourceManager().truncateFileAt(Entry, CodeCompletionAt.Line,
1951 CodeCompletionAt.Column);
Daniel Dunbarbea5a842009-10-29 01:53:18 +00001952
Douglas Gregorb657f112009-09-22 21:11:38 +00001953 // Set up the creation routine for code-completion.
1954 CreateCodeCompleter = BuildPrintingCodeCompleter;
1955 } else {
Daniel Dunbarbea5a842009-10-29 01:53:18 +00001956 PP.getDiagnostics().Report(FullSourceLoc(),
Douglas Gregorb657f112009-09-22 21:11:38 +00001957 diag::err_fe_invalid_code_complete_file)
1958 << CodeCompletionAt.FileName;
1959 }
Douglas Gregor81b747b2009-09-17 21:32:03 +00001960 }
1961
Mike Stump1eb44332009-09-09 15:08:12 +00001962 ParseAST(PP, Consumer.get(), *ContextOwner.get(), Stats,
Douglas Gregor81b747b2009-09-17 21:32:03 +00001963 CompleteTranslationUnit,
1964 CreateCodeCompleter, CreateCodeCompleterData);
1965 }
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001966
Daniel Dunbar593c41f2009-11-04 23:41:40 +00001967 // Perform post processing actions and actions which don't use a consumer.
1968 switch (PA) {
1969 default: break;
1970
1971 case RunPreprocessorOnly: { // Just lex as fast as we can, no output.
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001972 llvm::TimeRegion Timer(ClangFrontendTimer);
1973 Token Tok;
1974 // Start parsing the specified input file.
1975 PP.EnterMainSourceFile();
1976 do {
1977 PP.Lex(Tok);
1978 } while (Tok.isNot(tok::eof));
1979 ClearSourceMgr = true;
Daniel Dunbar593c41f2009-11-04 23:41:40 +00001980 break;
1981 }
1982
1983 case ParseNoop: {
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001984 llvm::TimeRegion Timer(ClangFrontendTimer);
1985 ParseFile(PP, new MinimalAction(PP));
1986 ClearSourceMgr = true;
Daniel Dunbar593c41f2009-11-04 23:41:40 +00001987 break;
1988 }
1989
1990 case PrintPreprocessedInput: {
Chris Lattnercc7dea82009-04-27 22:02:30 +00001991 llvm::TimeRegion Timer(ClangFrontendTimer);
Eli Friedman12d3b1d2009-05-19 03:06:47 +00001992 if (DumpMacros)
1993 DoPrintMacros(PP, OS.get());
1994 else
1995 DoPrintPreprocessedInput(PP, OS.get(), EnableCommentOutput,
1996 EnableMacroCommentOutput,
1997 DisableLineMarkers, DumpDefines);
Chris Lattnercc7dea82009-04-27 22:02:30 +00001998 ClearSourceMgr = true;
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001999 }
Mike Stump1eb44332009-09-09 15:08:12 +00002000
Daniel Dunbar593c41f2009-11-04 23:41:40 +00002001 }
2002
Chris Lattner1aee61a2009-04-27 21:25:27 +00002003 if (FixItRewrite)
2004 FixItRewrite->WriteFixedFile(InFile, OutputFile);
Daniel Dunbar70186ab2009-07-29 02:40:09 +00002005
2006 // Disable the consumer prior to the context, the consumer may perform actions
2007 // in its destructor which require the context.
2008 if (DisableFree)
2009 Consumer.take();
2010 else
2011 Consumer.reset();
Mike Stump1eb44332009-09-09 15:08:12 +00002012
Chris Lattner1aee61a2009-04-27 21:25:27 +00002013 // If in -disable-free mode, don't deallocate ASTContext.
2014 if (DisableFree)
2015 ContextOwner.take();
2016 else
2017 ContextOwner.reset(); // Delete ASTContext
Eli Friedman66d6f042009-05-18 22:20:00 +00002018
Daniel Dunbar879c3ea2008-10-27 22:03:52 +00002019 if (VerifyDiagnostics)
Daniel Dunbar276373d2008-10-27 22:10:13 +00002020 if (CheckDiagnostics(PP))
2021 exit(1);
Chris Lattnere66b65c2008-02-06 01:42:25 +00002022
Reid Spencer5f016e22007-07-11 17:01:13 +00002023 if (Stats) {
Ted Kremenekfdfc1982007-12-19 22:24:34 +00002024 fprintf(stderr, "\nSTATISTICS FOR '%s':\n", InFile.c_str());
Reid Spencer5f016e22007-07-11 17:01:13 +00002025 PP.PrintStats();
2026 PP.getIdentifierTable().PrintStats();
Chris Lattnerdee73592007-12-15 20:48:40 +00002027 PP.getHeaderSearchInfo().PrintStats();
Ted Kremenek1b95a652009-01-09 18:20:21 +00002028 PP.getSourceManager().PrintStats();
Reid Spencer5f016e22007-07-11 17:01:13 +00002029 fprintf(stderr, "\n");
2030 }
Chris Lattnerbd247762007-07-22 06:05:44 +00002031
Mike Stump1eb44332009-09-09 15:08:12 +00002032 // For a multi-file compilation, some things are ok with nuking the source
Chris Lattnerbd247762007-07-22 06:05:44 +00002033 // manager tables, other require stable fileid/macroid's across multiple
2034 // files.
Chris Lattnerdee73592007-12-15 20:48:40 +00002035 if (ClearSourceMgr)
2036 PP.getSourceManager().clearIDTables();
Daniel Dunbard68ba0e2008-11-11 06:35:39 +00002037
Eli Friedman66d6f042009-05-18 22:20:00 +00002038 // Always delete the output stream because we don't want to leak file
2039 // handles. Also, we don't want to try to erase an open file.
2040 OS.reset();
2041
Daniel Dunbar8cb65622009-10-29 21:05:18 +00002042 // If we had errors, try to erase the output file.
2043 if (PP.getDiagnostics().getNumErrors() && !OutPath.isEmpty())
Eli Friedman66d6f042009-05-18 22:20:00 +00002044 OutPath.eraseFromDisk();
Reid Spencer5f016e22007-07-11 17:01:13 +00002045}
2046
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +00002047/// ProcessInputFile - Process a single AST input file with the specified state.
2048///
2049static void ProcessASTInputFile(const std::string &InFile, ProgActions PA,
2050 const llvm::StringMap<bool> &Features,
2051 Diagnostic &Diags, FileManager &FileMgr,
2052 llvm::LLVMContext& Context) {
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +00002053 std::string Error;
Steve Naroff36c44642009-10-19 14:34:22 +00002054 llvm::OwningPtr<ASTUnit> AST(ASTUnit::LoadFromPCHFile(InFile, &Error));
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +00002055 if (!AST) {
2056 Diags.Report(FullSourceLoc(), diag::err_fe_invalid_ast_file) << Error;
2057 return;
2058 }
2059
2060 Preprocessor &PP = AST->getPreprocessor();
2061
2062 llvm::OwningPtr<llvm::raw_ostream> OS;
2063 llvm::sys::Path OutPath;
2064 llvm::OwningPtr<ASTConsumer> Consumer(CreateConsumerAction(PP, InFile, PA, OS,
2065 OutPath, Features,
2066 Context));
2067
2068 if (!Consumer.get()) {
2069 Diags.Report(FullSourceLoc(), diag::err_fe_invalid_ast_action);
2070 return;
2071 }
2072
Daniel Dunbara674bf42009-09-21 03:03:56 +00002073 // Set the main file ID to an empty file.
2074 //
2075 // FIXME: We probably shouldn't need this, but for now this is the simplest
2076 // way to reuse the logic in ParseAST.
2077 const char *EmptyStr = "";
2078 llvm::MemoryBuffer *SB =
2079 llvm::MemoryBuffer::getMemBuffer(EmptyStr, EmptyStr, "<dummy input>");
2080 AST->getSourceManager().createMainFileIDForMemBuffer(SB);
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +00002081
Daniel Dunbara674bf42009-09-21 03:03:56 +00002082 // Stream the input AST to the consumer.
2083 ParseAST(PP, Consumer.get(), AST->getASTContext(), Stats);
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +00002084
2085 // Release the consumer and the AST, in that order since the consumer may
2086 // perform actions in its destructor which require the context.
2087 if (DisableFree) {
2088 Consumer.take();
2089 AST.take();
2090 } else {
2091 Consumer.reset();
2092 AST.reset();
2093 }
2094
2095 // 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())
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +00002101 OutPath.eraseFromDisk();
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +00002102}
2103
Reid Spencer5f016e22007-07-11 17:01:13 +00002104static llvm::cl::list<std::string>
2105InputFilenames(llvm::cl::Positional, llvm::cl::desc("<input files>"));
2106
Daniel Dunbar70121eb2009-08-10 03:40:28 +00002107static void LLVMErrorHandler(void *UserData, const std::string &Message) {
2108 Diagnostic &Diags = *static_cast<Diagnostic*>(UserData);
2109
2110 Diags.Report(FullSourceLoc(), diag::err_fe_error_backend) << Message;
2111
2112 // We cannot recover from llvm errors.
2113 exit(1);
2114}
2115
Reid Spencer5f016e22007-07-11 17:01:13 +00002116int main(int argc, char **argv) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002117 llvm::sys::PrintStackTraceOnErrorSignal();
Chris Lattner09e94a32009-03-04 21:41:39 +00002118 llvm::PrettyStackTraceProgram X(argc, argv);
Owen Andersond7200462009-07-16 00:14:12 +00002119 llvm::LLVMContext &Context = llvm::getGlobalContext();
Daniel Dunbard6970812009-09-02 23:20:15 +00002120
Daniel Dunbar4d861512009-09-03 04:54:12 +00002121 // Initialize targets first, so that --version shows registered targets.
Chris Lattner2fe11942009-06-17 17:25:50 +00002122 llvm::InitializeAllTargets();
2123 llvm::InitializeAllAsmPrinters();
Daniel Dunbard6970812009-09-02 23:20:15 +00002124
2125 llvm::cl::ParseCommandLineOptions(argc, argv,
2126 "LLVM 'Clang' Compiler: http://clang.llvm.org\n");
Mike Stump1eb44332009-09-09 15:08:12 +00002127
Chris Lattner47099742009-02-18 01:51:21 +00002128 if (TimeReport)
2129 ClangFrontendTimer = new llvm::Timer("Clang front-end time");
Mike Stump1eb44332009-09-09 15:08:12 +00002130
Daniel Dunbar08e6dc62009-05-28 16:37:33 +00002131 if (Verbose)
Mike Stump3cbf5a02009-09-15 21:49:22 +00002132 llvm::errs() << "clang-cc version " CLANG_VERSION_STRING
2133 << " based upon " << PACKAGE_STRING
Daniel Dunbar2e30e592009-09-04 17:43:10 +00002134 << " hosted on " << llvm::sys::getHostTriple() << "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00002135
Reid Spencer5f016e22007-07-11 17:01:13 +00002136 // If no input was specified, read from stdin.
2137 if (InputFilenames.empty())
2138 InputFilenames.push_back("-");
Douglas Gregor68a0d782009-05-02 00:03:46 +00002139
Daniel Dunbareace8742009-11-04 06:24:30 +00002140 // Initialize the diagnostic options.
2141 DiagOpts.ShowColumn = !NoShowColumn;
2142 DiagOpts.ShowLocation = !NoShowLocation;
2143 DiagOpts.ShowCarets = !NoCaretDiagnostics;
2144 DiagOpts.ShowFixits = !NoDiagnosticsFixIt;
2145 DiagOpts.ShowSourceRanges = PrintSourceRangeInfo;
2146 DiagOpts.ShowOptionNames = PrintDiagnosticOption;
Daniel Dunbar838be482009-11-04 06:24:57 +00002147 DiagOpts.ShowColors = PrintColorDiagnostic;
Daniel Dunbareace8742009-11-04 06:24:30 +00002148 DiagOpts.MessageLength = MessageLength;
2149
Ted Kremenek31e703b2007-12-11 23:28:38 +00002150 // Create the diagnostic client for reporting errors or for
2151 // implementing -verify.
Chris Lattner409d4e72009-04-17 20:40:01 +00002152 llvm::OwningPtr<DiagnosticClient> DiagClient;
2153 if (VerifyDiagnostics) {
2154 // When checking diagnostics, just buffer them up.
2155 DiagClient.reset(new TextDiagnosticBuffer());
2156 if (InputFilenames.size() != 1) {
2157 fprintf(stderr, "-verify only works on single input files for now.\n");
2158 return 1;
2159 }
Ted Kremenekb4398aa2008-08-07 17:49:57 +00002160 } else {
Daniel Dunbarad451cc2009-11-05 02:11:37 +00002161 DiagClient.reset(new TextDiagnosticPrinter(llvm::errs(), DiagOpts));
Reid Spencer5f016e22007-07-11 17:01:13 +00002162 }
Mike Stump1eb44332009-09-09 15:08:12 +00002163
Daniel Dunbarad451cc2009-11-05 02:11:37 +00002164 if (!DumpBuildInformation.empty())
Chris Lattner75a97cb2009-04-17 21:05:01 +00002165 SetUpBuildDumpLog(argc, argv, DiagClient);
Ted Kremenekb4398aa2008-08-07 17:49:57 +00002166
Reid Spencer5f016e22007-07-11 17:01:13 +00002167 // Configure our handling of diagnostics.
Ted Kremenekb4398aa2008-08-07 17:49:57 +00002168 Diagnostic Diags(DiagClient.get());
Eli Friedman0eeb86e2009-05-19 01:17:04 +00002169 if (ProcessWarningOptions(Diags, OptWarnings, OptPedantic, OptPedanticErrors,
2170 OptNoWarnings))
Sebastian Redl63a9e0f2009-03-06 17:41:35 +00002171 return 1;
Ted Kremenek31e703b2007-12-11 23:28:38 +00002172
Daniel Dunbar70121eb2009-08-10 03:40:28 +00002173 // Set an error handler, so that any LLVM backend diagnostics go through our
2174 // error handler.
2175 llvm::llvm_install_error_handler(LLVMErrorHandler,
2176 static_cast<void*>(&Diags));
2177
Daniel Dunbar7c15e712009-10-30 18:12:31 +00002178 // Initialize base triple. If a -triple option has been specified, use
2179 // that triple. Otherwise, default to the host triple.
2180 llvm::Triple Triple(TargetTriple);
2181 if (Triple.getTriple().empty())
2182 Triple = llvm::Triple(llvm::sys::getHostTriple());
2183
Chris Lattner11215192008-03-14 06:12:05 +00002184 // Get information about the target being compiled for.
Daniel Dunbarbea5a842009-10-29 01:53:18 +00002185 llvm::OwningPtr<TargetInfo>
Chris Lattner2f60af72009-09-12 22:45:58 +00002186 Target(TargetInfo::CreateTargetInfo(Triple.getTriple()));
Mike Stump1eb44332009-09-09 15:08:12 +00002187
Chris Lattner11215192008-03-14 06:12:05 +00002188 if (Target == 0) {
Mike Stump1eb44332009-09-09 15:08:12 +00002189 Diags.Report(FullSourceLoc(), diag::err_fe_unknown_triple)
Chris Lattner2f60af72009-09-12 22:45:58 +00002190 << Triple.getTriple().c_str();
Sebastian Redlc5613db2009-03-07 12:09:25 +00002191 return 1;
Chris Lattner11215192008-03-14 06:12:05 +00002192 }
Mike Stump1eb44332009-09-09 15:08:12 +00002193
Daniel Dunbar73b79592009-09-14 00:02:12 +00002194 // Set the target ABI if specified.
2195 if (!TargetABI.empty()) {
2196 if (!Target->setABI(TargetABI)) {
2197 Diags.Report(FullSourceLoc(), diag::err_fe_unknown_target_abi)
2198 << TargetABI;
2199 return 1;
2200 }
2201 }
2202
Daniel Dunbard4270232009-01-20 23:17:32 +00002203 if (!InheritanceViewCls.empty()) // C++ visualization?
Ted Kremenek7cae2f62008-10-23 23:36:29 +00002204 ProgAction = InheritanceView;
Mike Stump1eb44332009-09-09 15:08:12 +00002205
Daniel Dunbar4cc1a252009-11-05 01:53:23 +00002206 // Create the source manager.
2207 SourceManager SourceMgr;
Mike Stump1eb44332009-09-09 15:08:12 +00002208
Chris Lattner2c78b872009-04-14 23:22:57 +00002209 // Create a file manager object to provide access to and cache the filesystem.
2210 FileManager FileMgr;
Douglas Gregor4fed3f42009-04-27 18:38:38 +00002211
Daniel Dunbar868bd0a2009-05-06 03:16:41 +00002212 // Compute the feature set, unfortunately this effects the language!
2213 llvm::StringMap<bool> Features;
2214 ComputeFeatureMap(Target.get(), Features);
2215
Reid Spencer5f016e22007-07-11 17:01:13 +00002216 for (unsigned i = 0, e = InputFilenames.size(); i != e; ++i) {
Ted Kremenek31e703b2007-12-11 23:28:38 +00002217 const std::string &InFile = InputFilenames[i];
Mike Stump1eb44332009-09-09 15:08:12 +00002218
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +00002219 LangKind LK = GetLanguage(InFile);
2220 // AST inputs are handled specially.
2221 if (LK == langkind_ast) {
2222 ProcessASTInputFile(InFile, ProgAction, Features,
2223 Diags, FileMgr, Context);
2224 continue;
2225 }
2226
Daniel Dunbar4cc1a252009-11-05 01:53:23 +00002227 // Reset the ID tables if we are reusing the SourceManager.
2228 if (i)
2229 SourceMgr.clearIDTables();
Mike Stump1eb44332009-09-09 15:08:12 +00002230
Chris Lattnerf63aea32009-03-04 21:40:56 +00002231 // Initialize language options, inferring file types from input filenames.
2232 LangOptions LangInfo;
Chris Lattner409d4e72009-04-17 20:40:01 +00002233 DiagClient->setLangOptions(&LangInfo);
Mike Stump1eb44332009-09-09 15:08:12 +00002234
Daniel Dunbar0b5b0da2009-04-01 05:09:09 +00002235 InitializeLangOptions(LangInfo, LK);
Daniel Dunbar868bd0a2009-05-06 03:16:41 +00002236 InitializeLanguageStandard(LangInfo, LK, Target.get(), Features);
Mike Stump1eb44332009-09-09 15:08:12 +00002237
Chris Lattnerf63aea32009-03-04 21:40:56 +00002238 // Process the -I options and set them in the HeaderInfo.
2239 HeaderSearch HeaderInfo(FileMgr);
Mike Stump1eb44332009-09-09 15:08:12 +00002240
2241
Mike Stump43d81762009-10-08 23:29:47 +00002242 InitializeIncludePaths(argv[0], HeaderInfo, FileMgr, LangInfo, Triple);
Mike Stump1eb44332009-09-09 15:08:12 +00002243
Chris Lattnerf63aea32009-03-04 21:40:56 +00002244 // Set up the preprocessor with these options.
Daniel Dunbar90b18272009-11-04 23:56:25 +00002245 llvm::OwningPtr<Preprocessor> PP(CreatePreprocessor(Diags, LangInfo,
Daniel Dunbar4cc1a252009-11-05 01:53:23 +00002246 *Target, SourceMgr,
Daniel Dunbar90b18272009-11-04 23:56:25 +00002247 HeaderInfo));
Ted Kremenekb4398aa2008-08-07 17:49:57 +00002248
Daniel Dunbar8cb65622009-10-29 21:05:18 +00002249 // Handle generating dependencies, if requested.
Eli Friedmanb5c8f8b2009-05-19 03:35:57 +00002250 if (!DependencyFile.empty()) {
Eli Friedmanb5c8f8b2009-05-19 03:35:57 +00002251 if (DependencyTargets.empty()) {
Daniel Dunbar8cb65622009-10-29 21:05:18 +00002252 Diags.Report(FullSourceLoc(), diag::err_fe_dependency_file_requires_MT);
Eli Friedmanb5c8f8b2009-05-19 03:35:57 +00002253 continue;
2254 }
2255 std::string ErrStr;
Daniel Dunbar8cb65622009-10-29 21:05:18 +00002256 llvm::raw_ostream *DependencyOS =
Dan Gohmanb044c472009-08-25 15:36:09 +00002257 new llvm::raw_fd_ostream(DependencyFile.c_str(), ErrStr);
Eli Friedmanb5c8f8b2009-05-19 03:35:57 +00002258 if (!ErrStr.empty()) {
Daniel Dunbar8cb65622009-10-29 21:05:18 +00002259 Diags.Report(FullSourceLoc(), diag::err_fe_error_opening)
2260 << DependencyFile << ErrStr;
Eli Friedmanb5c8f8b2009-05-19 03:35:57 +00002261 continue;
2262 }
2263
2264 AttachDependencyFileGen(PP.get(), DependencyOS, DependencyTargets,
2265 DependenciesIncludeSystemHeaders,
2266 PhonyDependencyTarget);
2267 }
2268
Chris Lattner1b63e4f2009-06-14 01:54:56 +00002269 if (ImplicitIncludePCH.empty()) {
2270 if (InitializeSourceManager(*PP.get(), InFile))
2271 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00002272
Chris Lattner1b63e4f2009-06-14 01:54:56 +00002273 // Initialize builtin info.
2274 PP->getBuiltinInfo().InitializeBuiltins(PP->getIdentifierTable(),
Chris Lattner1b63e4f2009-06-14 01:54:56 +00002275 PP->getLangOptions().NoBuiltin);
2276 }
Douglas Gregor14f79002009-04-10 03:52:48 +00002277
Chris Lattnerf63aea32009-03-04 21:40:56 +00002278 // Process the source file.
Daniel Dunbar90b18272009-11-04 23:56:25 +00002279 ProcessInputFile(*PP, InFile, ProgAction, Features, Context);
Mike Stump1eb44332009-09-09 15:08:12 +00002280
Chris Lattner40469652009-04-17 20:16:08 +00002281 HeaderInfo.ClearFileInfo();
Chris Lattner409d4e72009-04-17 20:40:01 +00002282 DiagClient->setLangOptions(0);
Reid Spencer5f016e22007-07-11 17:01:13 +00002283 }
Chris Lattner11215192008-03-14 06:12:05 +00002284
Mike Stumpfc0fed32009-04-28 01:19:10 +00002285 if (!NoCaretDiagnostics)
2286 if (unsigned NumDiagnostics = Diags.getNumDiagnostics())
2287 fprintf(stderr, "%d diagnostic%s generated.\n", NumDiagnostics,
2288 (NumDiagnostics == 1 ? "" : "s"));
Mike Stump1eb44332009-09-09 15:08:12 +00002289
Reid Spencer5f016e22007-07-11 17:01:13 +00002290 if (Stats) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002291 FileMgr.PrintStats();
2292 fprintf(stderr, "\n");
2293 }
Chris Lattner75a97cb2009-04-17 21:05:01 +00002294
2295 delete ClangFrontendTimer;
2296 delete BuildLogFile;
Mike Stump1eb44332009-09-09 15:08:12 +00002297
Daniel Dunbar276373d2008-10-27 22:10:13 +00002298 // If verifying diagnostics and we reached here, all is well.
2299 if (VerifyDiagnostics)
2300 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002301
Daniel Dunbar524b86f2008-10-28 00:38:08 +00002302 // Managed static deconstruction. Useful for making things like
2303 // -time-passes usable.
2304 llvm::llvm_shutdown();
2305
Daniel Dunbar8cb65622009-10-29 21:05:18 +00002306 return (Diags.getNumErrors() != 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00002307}