blob: 641d1195c268848e641557ce887be85a34d71d17 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- clang.cpp - C-Language Front-end ---------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This utility may be invoked in the following manner:
11// clang --help - Output help info.
12// clang [options] - Read from stdin.
13// clang [options] file - Read from "file".
14// clang [options] file1 file2 - Read these files.
15//
16//===----------------------------------------------------------------------===//
17//
18// TODO: Options to support:
19//
Chris Lattnerdddaa9c2009-02-18 01:17:01 +000020// -Wfatal-errors
Reid Spencer5f016e22007-07-11 17:01:13 +000021// -ftabstop=width
22//
23//===----------------------------------------------------------------------===//
24
Eli Friedman0ec78fa2009-05-19 21:10:40 +000025#include "clang/Frontend/AnalysisConsumer.h"
Eli Friedman8ceb0d92009-05-18 23:02:01 +000026#include "clang/Frontend/ASTConsumers.h"
Daniel Dunbare1bd4e62009-03-02 06:16:29 +000027#include "clang/Frontend/CompileOptions.h"
Douglas Gregor558cb562009-04-02 01:08:08 +000028#include "clang/Frontend/FixItRewriter.h"
Daniel Dunbar50f4f462009-03-12 10:14:16 +000029#include "clang/Frontend/FrontendDiagnostic.h"
Daniel Dunbare1bd4e62009-03-02 06:16:29 +000030#include "clang/Frontend/InitHeaderSearch.h"
Chris Lattnere116ccf2009-04-21 05:40:52 +000031#include "clang/Frontend/InitPreprocessor.h"
Daniel Dunbar50f4f462009-03-12 10:14:16 +000032#include "clang/Frontend/PathDiagnosticClients.h"
Douglas Gregor2cf26342009-04-09 22:27:44 +000033#include "clang/Frontend/PCHReader.h"
Daniel Dunbare1bd4e62009-03-02 06:16:29 +000034#include "clang/Frontend/TextDiagnosticBuffer.h"
35#include "clang/Frontend/TextDiagnosticPrinter.h"
Argyrios Kyrtzidis34d25d82009-06-23 22:01:39 +000036#include "clang/Frontend/CommandLineSourceLoc.h"
Eli Friedmanb09f6e12009-05-19 04:14:29 +000037#include "clang/Frontend/Utils.h"
Ted Kremenek88f5cde2008-03-27 06:17:42 +000038#include "clang/Analysis/PathDiagnostic.h"
Chris Lattner8ee3c032008-02-06 02:01:47 +000039#include "clang/CodeGen/ModuleBuilder.h"
Chris Lattnere91c1342008-02-06 00:23:21 +000040#include "clang/Sema/ParseAST.h"
Chris Lattner88eccaf2009-01-29 06:55:46 +000041#include "clang/Sema/SemaDiagnostic.h"
Chris Lattner556beb72007-09-15 22:56:56 +000042#include "clang/AST/ASTConsumer.h"
Chris Lattner1266eca2009-03-28 04:31:31 +000043#include "clang/AST/ASTContext.h"
44#include "clang/AST/Decl.h"
Chris Lattner682bf922009-03-29 16:50:03 +000045#include "clang/AST/DeclGroup.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000046#include "clang/Parse/Parser.h"
47#include "clang/Lex/HeaderSearch.h"
Chris Lattnerdb766842009-02-06 04:16:41 +000048#include "clang/Lex/LexDiagnostic.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000049#include "clang/Basic/FileManager.h"
50#include "clang/Basic/SourceManager.h"
51#include "clang/Basic/TargetInfo.h"
Daniel Dunbaraa338bc2009-05-06 04:07:06 +000052#include "clang/Basic/Version.h"
Chris Lattnerba0f25f2008-09-30 20:16:56 +000053#include "llvm/ADT/OwningPtr.h"
Chris Lattner8f3dab82007-12-15 23:20:07 +000054#include "llvm/ADT/SmallPtrSet.h"
Chris Lattnerba0f25f2008-09-30 20:16:56 +000055#include "llvm/ADT/StringExtras.h"
Daniel Dunbar868bd0a2009-05-06 03:16:41 +000056#include "llvm/ADT/StringMap.h"
Chris Lattnerb8e240e2009-04-08 18:24:34 +000057#include "llvm/ADT/STLExtras.h"
Chris Lattnerba0f25f2008-09-30 20:16:56 +000058#include "llvm/Config/config.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000059#include "llvm/Support/CommandLine.h"
Daniel Dunbar524b86f2008-10-28 00:38:08 +000060#include "llvm/Support/ManagedStatic.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000061#include "llvm/Support/MemoryBuffer.h"
Zhongxing Xu20922362008-11-26 05:23:17 +000062#include "llvm/Support/PluginLoader.h"
Chris Lattner09e94a32009-03-04 21:41:39 +000063#include "llvm/Support/PrettyStackTrace.h"
Eli Friedman66d6f042009-05-18 22:20:00 +000064#include "llvm/Support/Streams.h"
Chris Lattner47099742009-02-18 01:51:21 +000065#include "llvm/Support/Timer.h"
Daniel Dunbare553a722008-10-02 01:21:33 +000066#include "llvm/System/Host.h"
Chris Lattnerdcaa0962008-03-03 03:16:03 +000067#include "llvm/System/Path.h"
Douglas Gregor44cf08e2009-05-03 03:52:38 +000068#include "llvm/System/Process.h"
Eli Friedman66d6f042009-05-18 22:20:00 +000069#include "llvm/System/Program.h"
Chris Lattnerba0f25f2008-09-30 20:16:56 +000070#include "llvm/System/Signals.h"
Chris Lattner2fe11942009-06-17 17:25:50 +000071#include "llvm/Target/TargetSelect.h"
Douglas Gregor26df2f02009-04-02 19:05:20 +000072#include <cstdlib>
Douglas Gregor44cf08e2009-05-03 03:52:38 +000073#if HAVE_SYS_TYPES_H
Douglas Gregor68a0d782009-05-02 00:03:46 +000074# include <sys/types.h>
75#endif
Douglas Gregor26df2f02009-04-02 19:05:20 +000076
Reid Spencer5f016e22007-07-11 17:01:13 +000077using namespace clang;
78
79//===----------------------------------------------------------------------===//
Douglas Gregor26df2f02009-04-02 19:05:20 +000080// Source Location Parser
81//===----------------------------------------------------------------------===//
82
Argyrios Kyrtzidis34d25d82009-06-23 22:01:39 +000083static bool ResolveParsedLocation(ParsedSourceLocation &ParsedLoc,
84 FileManager &FileMgr,
85 RequestedSourceLocation &Result) {
86 const FileEntry *File = FileMgr.getFile(ParsedLoc.FileName);
Douglas Gregor26df2f02009-04-02 19:05:20 +000087 if (!File)
88 return true;
89
90 Result.File = File;
Argyrios Kyrtzidis34d25d82009-06-23 22:01:39 +000091 Result.Line = ParsedLoc.Line;
92 Result.Column = ParsedLoc.Column;
Douglas Gregor26df2f02009-04-02 19:05:20 +000093 return false;
94}
95
Douglas Gregor26df2f02009-04-02 19:05:20 +000096//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +000097// Global options.
98//===----------------------------------------------------------------------===//
99
Chris Lattner47099742009-02-18 01:51:21 +0000100/// ClangFrontendTimer - The front-end activities should charge time to it with
101/// TimeRegion. The -ftime-report option controls whether this will do
102/// anything.
103llvm::Timer *ClangFrontendTimer = 0;
104
Daniel Dunbard3db4012008-10-16 16:54:18 +0000105static bool HadErrors = false;
Daniel Dunbarb0adbba2008-10-04 23:42:49 +0000106
Reid Spencer5f016e22007-07-11 17:01:13 +0000107static llvm::cl::opt<bool>
108Verbose("v", llvm::cl::desc("Enable verbose output"));
109static llvm::cl::opt<bool>
Nate Begemanaabbb122007-12-30 01:38:50 +0000110Stats("print-stats",
111 llvm::cl::desc("Print performance metrics and statistics"));
Daniel Dunbard3db4012008-10-16 16:54:18 +0000112static llvm::cl::opt<bool>
113DisableFree("disable-free",
114 llvm::cl::desc("Disable freeing of memory on exit"),
115 llvm::cl::init(false));
Daniel Dunbar57cbfc02009-04-27 21:19:07 +0000116static llvm::cl::opt<bool>
117EmptyInputOnly("empty-input-only",
118 llvm::cl::desc("Force running on an empty input file"));
Reid Spencer5f016e22007-07-11 17:01:13 +0000119
120enum ProgActions {
Steve Naroffb29b4272008-04-14 22:03:09 +0000121 RewriteObjC, // ObjC->C Rewriter.
Steve Naroff13188952008-09-18 14:10:13 +0000122 RewriteBlocks, // ObjC->C Rewriter for Blocks.
Chris Lattnerb57e3d42008-05-08 06:52:13 +0000123 RewriteMacros, // Expand macros but not #includes.
Chris Lattnerb13c5ee2008-10-12 05:29:20 +0000124 RewriteTest, // Rewriter playground
Douglas Gregor558cb562009-04-02 01:08:08 +0000125 FixIt, // Fix-It Rewriter
Ted Kremenek13e479b2008-03-19 07:53:42 +0000126 HTMLTest, // HTML displayer testing stuff.
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000127 EmitAssembly, // Emit a .s file.
Reid Spencer5f016e22007-07-11 17:01:13 +0000128 EmitLLVM, // Emit a .ll file.
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +0000129 EmitBC, // Emit a .bc file.
Daniel Dunbare8e26002009-02-26 22:39:37 +0000130 EmitLLVMOnly, // Generate LLVM IR, but do not
Ted Kremenek6a340832008-03-18 21:19:49 +0000131 EmitHTML, // Translate input source into HTML.
Chris Lattner3b427b32007-10-11 00:18:28 +0000132 ASTPrint, // Parse ASTs and print them.
Douglas Gregoree75c052009-05-21 20:55:50 +0000133 ASTPrintXML, // Parse ASTs and print them in XML.
Chris Lattner3b427b32007-10-11 00:18:28 +0000134 ASTDump, // Parse ASTs and dump them.
135 ASTView, // Parse ASTs and view them in Graphviz.
Zhongxing Xu2d75d6f2009-01-13 01:29:24 +0000136 PrintDeclContext, // Print DeclContext and their Decls.
Reid Spencer5f016e22007-07-11 17:01:13 +0000137 ParsePrintCallbacks, // Parse and print each callback.
138 ParseSyntaxOnly, // Parse and perform semantic analysis.
139 ParseNoop, // Parse with noop callbacks.
140 RunPreprocessorOnly, // Just lex, no output.
141 PrintPreprocessedInput, // -E mode.
Chris Lattnerc106c102008-10-12 05:03:36 +0000142 DumpTokens, // Dump out preprocessed tokens.
143 DumpRawTokens, // Dump out raw tokens.
Ted Kremenek85888962008-10-21 00:54:44 +0000144 RunAnalysis, // Run one or more source code analyses.
Douglas Gregorbf1bd6e2009-04-02 23:43:50 +0000145 GeneratePTH, // Generate pre-tokenized header.
Douglas Gregor2cf26342009-04-09 22:27:44 +0000146 GeneratePCH, // Generate pre-compiled header.
Ted Kremenek7cae2f62008-10-23 23:36:29 +0000147 InheritanceView // View C++ inheritance for a specified class.
Reid Spencer5f016e22007-07-11 17:01:13 +0000148};
149
150static llvm::cl::opt<ProgActions>
151ProgAction(llvm::cl::desc("Choose output type:"), llvm::cl::ZeroOrMore,
152 llvm::cl::init(ParseSyntaxOnly),
153 llvm::cl::values(
154 clEnumValN(RunPreprocessorOnly, "Eonly",
155 "Just run preprocessor, no output (for timings)"),
156 clEnumValN(PrintPreprocessedInput, "E",
157 "Run preprocessor, emit preprocessed file"),
Chris Lattnerc106c102008-10-12 05:03:36 +0000158 clEnumValN(DumpRawTokens, "dump-raw-tokens",
159 "Lex file in raw mode and dump raw tokens"),
Daniel Dunbard4270232009-01-20 23:17:32 +0000160 clEnumValN(RunAnalysis, "analyze",
161 "Run static analysis engine"),
Chris Lattnerc106c102008-10-12 05:03:36 +0000162 clEnumValN(DumpTokens, "dump-tokens",
Reid Spencer5f016e22007-07-11 17:01:13 +0000163 "Run preprocessor, dump internal rep of tokens"),
164 clEnumValN(ParseNoop, "parse-noop",
165 "Run parser with noop callbacks (for timings)"),
166 clEnumValN(ParseSyntaxOnly, "fsyntax-only",
167 "Run parser and perform semantic analysis"),
168 clEnumValN(ParsePrintCallbacks, "parse-print-callbacks",
169 "Run parser and print each callback invoked"),
Ted Kremenek6a340832008-03-18 21:19:49 +0000170 clEnumValN(EmitHTML, "emit-html",
171 "Output input source as HTML"),
Chris Lattner3b427b32007-10-11 00:18:28 +0000172 clEnumValN(ASTPrint, "ast-print",
173 "Build ASTs and then pretty-print them"),
Douglas Gregoree75c052009-05-21 20:55:50 +0000174 clEnumValN(ASTPrintXML, "ast-print-xml",
175 "Build ASTs and then print them in XML format"),
Chris Lattner3b427b32007-10-11 00:18:28 +0000176 clEnumValN(ASTDump, "ast-dump",
177 "Build ASTs and then debug dump them"),
Chris Lattnerea254db2007-10-11 00:37:43 +0000178 clEnumValN(ASTView, "ast-view",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000179 "Build ASTs and view them with GraphViz"),
Zhongxing Xu2d75d6f2009-01-13 01:29:24 +0000180 clEnumValN(PrintDeclContext, "print-decl-contexts",
Ted Kremenek08478eb2009-04-01 00:23:28 +0000181 "Print DeclContexts and their Decls"),
Douglas Gregorbf1bd6e2009-04-02 23:43:50 +0000182 clEnumValN(GeneratePTH, "emit-pth",
Ted Kremenek08478eb2009-04-01 00:23:28 +0000183 "Generate pre-tokenized header file"),
Douglas Gregor2cf26342009-04-09 22:27:44 +0000184 clEnumValN(GeneratePCH, "emit-pch",
185 "Generate pre-compiled header file"),
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000186 clEnumValN(EmitAssembly, "S",
187 "Emit native assembly code"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000188 clEnumValN(EmitLLVM, "emit-llvm",
Ted Kremenek27b07c52007-09-06 21:26:58 +0000189 "Build ASTs then convert to LLVM, emit .ll file"),
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +0000190 clEnumValN(EmitBC, "emit-llvm-bc",
191 "Build ASTs then convert to LLVM, emit .bc file"),
Daniel Dunbare8e26002009-02-26 22:39:37 +0000192 clEnumValN(EmitLLVMOnly, "emit-llvm-only",
193 "Build ASTs and convert to LLVM, discarding output"),
Chris Lattnerb13c5ee2008-10-12 05:29:20 +0000194 clEnumValN(RewriteTest, "rewrite-test",
195 "Rewriter playground"),
Steve Naroffb29b4272008-04-14 22:03:09 +0000196 clEnumValN(RewriteObjC, "rewrite-objc",
Chris Lattnerb57e3d42008-05-08 06:52:13 +0000197 "Rewrite ObjC into C (code rewriter example)"),
198 clEnumValN(RewriteMacros, "rewrite-macros",
199 "Expand macros without full preprocessing"),
Steve Naroff13188952008-09-18 14:10:13 +0000200 clEnumValN(RewriteBlocks, "rewrite-blocks",
201 "Rewrite Blocks to C"),
Douglas Gregor558cb562009-04-02 01:08:08 +0000202 clEnumValN(FixIt, "fixit",
203 "Apply fix-it advice to the input source"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000204 clEnumValEnd));
205
Ted Kremenekccc76472007-12-19 19:47:59 +0000206
207static llvm::cl::opt<std::string>
208OutputFile("o",
Ted Kremenek50b56412007-12-19 19:50:41 +0000209 llvm::cl::value_desc("path"),
Douglas Gregor370187c2009-04-22 21:45:53 +0000210 llvm::cl::desc("Specify output file"));
Ted Kremenek55af98c2008-04-14 18:40:58 +0000211
Ted Kremenekc2e72992008-12-02 19:57:31 +0000212
213//===----------------------------------------------------------------------===//
214// PTH.
215//===----------------------------------------------------------------------===//
216
217static llvm::cl::opt<std::string>
218TokenCache("token-cache", llvm::cl::value_desc("path"),
219 llvm::cl::desc("Use specified token cache file"));
220
Sanjiv Guptae8b9f5b2008-05-08 08:54:20 +0000221//===----------------------------------------------------------------------===//
Ted Kremenek55af98c2008-04-14 18:40:58 +0000222// Diagnostic Options
223//===----------------------------------------------------------------------===//
224
Ted Kremenek41193e42007-09-26 19:42:19 +0000225static llvm::cl::opt<bool>
226VerifyDiagnostics("verify",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000227 llvm::cl::desc("Verify emitted diagnostics and warnings"));
Ted Kremenek41193e42007-09-26 19:42:19 +0000228
Ted Kremenek88f5cde2008-03-27 06:17:42 +0000229static llvm::cl::opt<std::string>
230HTMLDiag("html-diags",
231 llvm::cl::desc("Generate HTML to report diagnostics"),
232 llvm::cl::value_desc("HTML directory"));
233
Nico Weberfd54ebc2008-08-05 23:33:20 +0000234static llvm::cl::opt<bool>
235NoShowColumn("fno-show-column",
236 llvm::cl::desc("Do not include column number on diagnostics"));
237
238static llvm::cl::opt<bool>
Chris Lattner65f5e642009-01-30 19:01:41 +0000239NoShowLocation("fno-show-source-location",
240 llvm::cl::desc("Do not include source location information with"
241 " diagnostics"));
242
243static llvm::cl::opt<bool>
Nico Weberfd54ebc2008-08-05 23:33:20 +0000244NoCaretDiagnostics("fno-caret-diagnostics",
245 llvm::cl::desc("Do not include source line and caret with"
246 " diagnostics"));
247
Chris Lattner1fbee5d2009-03-13 01:08:23 +0000248static llvm::cl::opt<bool>
Chris Lattneraa5bf2e2009-04-19 07:44:08 +0000249NoDiagnosticsFixIt("fno-diagnostics-fixit-info",
250 llvm::cl::desc("Do not include fixit information in"
251 " diagnostics"));
252
253static llvm::cl::opt<bool>
Chris Lattner182e0922009-04-21 05:34:31 +0000254PrintSourceRangeInfo("fdiagnostics-print-source-range-info",
255 llvm::cl::desc("Print source range spans in numeric form"));
256
Chris Lattnerd51d74a2009-04-16 05:44:38 +0000257static llvm::cl::opt<bool>
258PrintDiagnosticOption("fdiagnostics-show-option",
259 llvm::cl::desc("Print diagnostic name with mappable diagnostics"));
Nico Weberfd54ebc2008-08-05 23:33:20 +0000260
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000261static llvm::cl::opt<unsigned>
262MessageLength("fmessage-length",
263 llvm::cl::desc("Format message diagnostics so that they fit "
264 "within N columns or fewer, when possible."),
265 llvm::cl::value_desc("N"));
266
Torok Edwin603fca72009-06-04 07:18:23 +0000267static llvm::cl::opt<bool>
Torok Edwina46c71a2009-06-04 07:27:53 +0000268NoColorDiagnostic("fno-color-diagnostics",
Torok Edwin603fca72009-06-04 07:18:23 +0000269 llvm::cl::desc("Don't use colors when showing diagnostics "
270 "(automatically turned off if output is not a "
271 "terminal)."));
Reid Spencer5f016e22007-07-11 17:01:13 +0000272//===----------------------------------------------------------------------===//
Ted Kremenek7cae2f62008-10-23 23:36:29 +0000273// C++ Visualization.
274//===----------------------------------------------------------------------===//
275
276static llvm::cl::opt<std::string>
277InheritanceViewCls("cxx-inheritance-view",
278 llvm::cl::value_desc("class name"),
Daniel Dunbard77b2512009-01-14 18:56:36 +0000279 llvm::cl::desc("View C++ inheritance for a specified class"));
Ted Kremenek7cae2f62008-10-23 23:36:29 +0000280
281//===----------------------------------------------------------------------===//
Douglas Gregor3573c0c2009-02-14 20:49:29 +0000282// Builtin Options
283//===----------------------------------------------------------------------===//
Chris Lattnerb2509e12009-02-18 01:12:43 +0000284
285static llvm::cl::opt<bool>
286TimeReport("ftime-report",
287 llvm::cl::desc("Print the amount of time each "
288 "phase of compilation takes"));
289
Douglas Gregor3573c0c2009-02-14 20:49:29 +0000290static llvm::cl::opt<bool>
291Freestanding("ffreestanding",
Daniel Dunbaref2abfe2009-02-16 22:43:43 +0000292 llvm::cl::desc("Assert that the compilation takes place in a "
Douglas Gregor3573c0c2009-02-14 20:49:29 +0000293 "freestanding environment"));
294
Daniel Dunbaref2abfe2009-02-16 22:43:43 +0000295static llvm::cl::opt<bool>
Daniel Dunbar48d1ef72009-04-07 21:16:11 +0000296AllowBuiltins("fbuiltin", llvm::cl::init(true),
297 llvm::cl::desc("Disable implicit builtin knowledge of functions"));
Chris Lattner7644f072009-03-13 22:38:49 +0000298
299
300static llvm::cl::opt<bool>
Daniel Dunbar48d1ef72009-04-07 21:16:11 +0000301MathErrno("fmath-errno", llvm::cl::init(true),
302 llvm::cl::desc("Require math functions to respect errno"));
Daniel Dunbaref2abfe2009-02-16 22:43:43 +0000303
Douglas Gregor3573c0c2009-02-14 20:49:29 +0000304//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +0000305// Language Options
306//===----------------------------------------------------------------------===//
307
308enum LangKind {
309 langkind_unspecified,
310 langkind_c,
311 langkind_c_cpp,
Chris Lattnera778d7d2008-10-22 17:29:21 +0000312 langkind_asm_cpp,
Reid Spencer5f016e22007-07-11 17:01:13 +0000313 langkind_cxx,
314 langkind_cxx_cpp,
315 langkind_objc,
316 langkind_objc_cpp,
317 langkind_objcxx,
Nate Begeman4e3629e2009-06-25 22:43:10 +0000318 langkind_objcxx_cpp,
319 langkind_ocl
Reid Spencer5f016e22007-07-11 17:01:13 +0000320};
321
Reid Spencer5f016e22007-07-11 17:01:13 +0000322static llvm::cl::opt<LangKind>
323BaseLang("x", llvm::cl::desc("Base language to compile"),
324 llvm::cl::init(langkind_unspecified),
325 llvm::cl::values(clEnumValN(langkind_c, "c", "C"),
Nate Begeman4e3629e2009-06-25 22:43:10 +0000326 clEnumValN(langkind_ocl, "cl", "OpenCL C"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000327 clEnumValN(langkind_cxx, "c++", "C++"),
328 clEnumValN(langkind_objc, "objective-c", "Objective C"),
329 clEnumValN(langkind_objcxx,"objective-c++","Objective C++"),
Daniel Dunbard2ea3862009-01-29 23:50:47 +0000330 clEnumValN(langkind_c_cpp, "cpp-output",
Reid Spencer5f016e22007-07-11 17:01:13 +0000331 "Preprocessed C"),
Chris Lattnera778d7d2008-10-22 17:29:21 +0000332 clEnumValN(langkind_asm_cpp, "assembler-with-cpp",
333 "Preprocessed asm"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000334 clEnumValN(langkind_cxx_cpp, "c++-cpp-output",
Chris Lattnerc76d8072009-02-06 06:19:20 +0000335 "Preprocessed C++"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000336 clEnumValN(langkind_objc_cpp, "objective-c-cpp-output",
337 "Preprocessed Objective C"),
Chris Lattnerc76d8072009-02-06 06:19:20 +0000338 clEnumValN(langkind_objcxx_cpp, "objective-c++-cpp-output",
Reid Spencer5f016e22007-07-11 17:01:13 +0000339 "Preprocessed Objective C++"),
Daniel Dunbar0b5b0da2009-04-01 05:09:09 +0000340 clEnumValN(langkind_c, "c-header",
341 "C header"),
342 clEnumValN(langkind_objc, "objective-c-header",
343 "Objective-C header"),
344 clEnumValN(langkind_cxx, "c++-header",
345 "C++ header"),
346 clEnumValN(langkind_objcxx, "objective-c++-header",
347 "Objective-C++ header"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000348 clEnumValEnd));
349
350static llvm::cl::opt<bool>
351LangObjC("ObjC", llvm::cl::desc("Set base language to Objective-C"),
352 llvm::cl::Hidden);
353static llvm::cl::opt<bool>
354LangObjCXX("ObjC++", llvm::cl::desc("Set base language to Objective-C++"),
355 llvm::cl::Hidden);
356
Chris Lattner2c78b872009-04-14 23:22:57 +0000357static llvm::cl::opt<bool>
358ObjCExclusiveGC("fobjc-gc-only",
359 llvm::cl::desc("Use GC exclusively for Objective-C related "
360 "memory management"));
361
362static llvm::cl::opt<bool>
363ObjCEnableGC("fobjc-gc",
364 llvm::cl::desc("Enable Objective-C garbage collection"));
365
Fariborz Jahanian448f5e62009-04-17 03:04:15 +0000366static llvm::cl::opt<bool>
367ObjCEnableGCBitmapPrint("print-ivar-layout",
368 llvm::cl::desc("Enable Objective-C Ivar layout bitmap print trace"));
369
Chris Lattner2c78b872009-04-14 23:22:57 +0000370static llvm::cl::opt<LangOptions::VisibilityMode>
371SymbolVisibility("fvisibility",
372 llvm::cl::desc("Set the default symbol visibility:"),
373 llvm::cl::init(LangOptions::Default),
374 llvm::cl::values(clEnumValN(LangOptions::Default, "default",
375 "Use default symbol visibility"),
376 clEnumValN(LangOptions::Hidden, "hidden",
377 "Use hidden symbol visibility"),
378 clEnumValN(LangOptions::Protected,"protected",
379 "Use protected symbol visibility"),
380 clEnumValEnd));
381
382static llvm::cl::opt<bool>
383OverflowChecking("ftrapv",
384 llvm::cl::desc("Trap on integer overflow"),
385 llvm::cl::init(false));
386
Fariborz Jahanian34e65772009-05-22 20:17:16 +0000387static llvm::cl::opt<bool>
388ObjCSenderDispatch("fobjc-sender-dependent-dispatch",
389 llvm::cl::desc("Enable sender-dependent dispatch for"
390 "Objective-C messages"), llvm::cl::init(false));
Chris Lattner2c78b872009-04-14 23:22:57 +0000391
Ted Kremenek8904f152007-12-05 23:49:08 +0000392/// InitializeBaseLanguage - Handle the -x foo options.
393static void InitializeBaseLanguage() {
394 if (LangObjC)
395 BaseLang = langkind_objc;
396 else if (LangObjCXX)
397 BaseLang = langkind_objcxx;
398}
399
400static LangKind GetLanguage(const std::string &Filename) {
401 if (BaseLang != langkind_unspecified)
402 return BaseLang;
403
404 std::string::size_type DotPos = Filename.rfind('.');
405
406 if (DotPos == std::string::npos) {
407 BaseLang = langkind_c; // Default to C if no extension.
Chris Lattner9b2f6c42008-01-04 19:12:28 +0000408 return langkind_c;
Reid Spencer5f016e22007-07-11 17:01:13 +0000409 }
410
Ted Kremenek8904f152007-12-05 23:49:08 +0000411 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
412 // C header: .h
413 // C++ header: .hh or .H;
414 // assembler no preprocessing: .s
415 // assembler: .S
416 if (Ext == "c")
417 return langkind_c;
Chris Lattnerd9cd4c92009-03-23 16:24:37 +0000418 else if (Ext == "S" ||
419 // If the compiler is run on a .s file, preprocess it as .S
420 Ext == "s")
Chris Lattnera778d7d2008-10-22 17:29:21 +0000421 return langkind_asm_cpp;
Ted Kremenek8904f152007-12-05 23:49:08 +0000422 else if (Ext == "i")
423 return langkind_c_cpp;
424 else if (Ext == "ii")
425 return langkind_cxx_cpp;
426 else if (Ext == "m")
427 return langkind_objc;
428 else if (Ext == "mi")
429 return langkind_objc_cpp;
430 else if (Ext == "mm" || Ext == "M")
431 return langkind_objcxx;
432 else if (Ext == "mii")
433 return langkind_objcxx_cpp;
434 else if (Ext == "C" || Ext == "cc" || Ext == "cpp" || Ext == "CPP" ||
435 Ext == "c++" || Ext == "cp" || Ext == "cxx")
436 return langkind_cxx;
Nate Begeman4e3629e2009-06-25 22:43:10 +0000437 else if (Ext == "cl")
438 return langkind_ocl;
Ted Kremenek8904f152007-12-05 23:49:08 +0000439 else
440 return langkind_c;
441}
442
443
Ted Kremenek85888962008-10-21 00:54:44 +0000444static void InitializeCOptions(LangOptions &Options) {
445 // Do nothing.
446}
447
448static void InitializeObjCOptions(LangOptions &Options) {
449 Options.ObjC1 = Options.ObjC2 = 1;
450}
451
452
Daniel Dunbar0b5b0da2009-04-01 05:09:09 +0000453static void InitializeLangOptions(LangOptions &Options, LangKind LK){
Reid Spencer5f016e22007-07-11 17:01:13 +0000454 // FIXME: implement -fpreprocessed mode.
455 bool NoPreprocess = false;
456
Ted Kremenek8904f152007-12-05 23:49:08 +0000457 switch (LK) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000458 default: assert(0 && "Unknown language kind!");
Chris Lattnera778d7d2008-10-22 17:29:21 +0000459 case langkind_asm_cpp:
Daniel Dunbarc1571452008-12-01 18:55:22 +0000460 Options.AsmPreprocessor = 1;
Chris Lattnera778d7d2008-10-22 17:29:21 +0000461 // FALLTHROUGH
Reid Spencer5f016e22007-07-11 17:01:13 +0000462 case langkind_c_cpp:
463 NoPreprocess = true;
464 // FALLTHROUGH
465 case langkind_c:
Ted Kremenek85888962008-10-21 00:54:44 +0000466 InitializeCOptions(Options);
Reid Spencer5f016e22007-07-11 17:01:13 +0000467 break;
468 case langkind_cxx_cpp:
469 NoPreprocess = true;
470 // FALLTHROUGH
471 case langkind_cxx:
472 Options.CPlusPlus = 1;
473 break;
474 case langkind_objc_cpp:
475 NoPreprocess = true;
476 // FALLTHROUGH
477 case langkind_objc:
Ted Kremenek85888962008-10-21 00:54:44 +0000478 InitializeObjCOptions(Options);
Reid Spencer5f016e22007-07-11 17:01:13 +0000479 break;
480 case langkind_objcxx_cpp:
481 NoPreprocess = true;
482 // FALLTHROUGH
483 case langkind_objcxx:
484 Options.ObjC1 = Options.ObjC2 = 1;
485 Options.CPlusPlus = 1;
486 break;
Nate Begeman4e3629e2009-06-25 22:43:10 +0000487 case langkind_ocl:
488 Options.OpenCL = 1;
489 Options.AltiVec = 1;
490 Options.CXXOperatorNames = 1;
491 Options.LaxVectorConversions = 1;
492 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000493 }
Chris Lattner2c78b872009-04-14 23:22:57 +0000494
495 if (ObjCExclusiveGC)
496 Options.setGCMode(LangOptions::GCOnly);
497 else if (ObjCEnableGC)
498 Options.setGCMode(LangOptions::HybridGC);
499
Fariborz Jahanian448f5e62009-04-17 03:04:15 +0000500 if (ObjCEnableGCBitmapPrint)
501 Options.ObjCGCBitmapPrint = 1;
502
Chris Lattner2c78b872009-04-14 23:22:57 +0000503 Options.setVisibilityMode(SymbolVisibility);
504 Options.OverflowChecking = OverflowChecking;
Reid Spencer5f016e22007-07-11 17:01:13 +0000505}
506
507/// LangStds - Language standards we support.
508enum LangStds {
509 lang_unspecified,
510 lang_c89, lang_c94, lang_c99,
Ted Kremenekea644d82008-09-03 21:22:16 +0000511 lang_gnu_START,
512 lang_gnu89 = lang_gnu_START, lang_gnu99,
Chris Lattnerd4b80f12007-07-16 04:18:29 +0000513 lang_cxx98, lang_gnucxx98,
514 lang_cxx0x, lang_gnucxx0x
Reid Spencer5f016e22007-07-11 17:01:13 +0000515};
516
517static llvm::cl::opt<LangStds>
518LangStd("std", llvm::cl::desc("Language standard to compile for"),
519 llvm::cl::init(lang_unspecified),
520 llvm::cl::values(clEnumValN(lang_c89, "c89", "ISO C 1990"),
521 clEnumValN(lang_c89, "c90", "ISO C 1990"),
522 clEnumValN(lang_c89, "iso9899:1990", "ISO C 1990"),
523 clEnumValN(lang_c94, "iso9899:199409",
524 "ISO C 1990 with amendment 1"),
525 clEnumValN(lang_c99, "c99", "ISO C 1999"),
Chris Lattner50748f42009-04-06 17:17:55 +0000526 clEnumValN(lang_c99, "c9x", "ISO C 1999"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000527 clEnumValN(lang_c99, "iso9899:1999", "ISO C 1999"),
Chris Lattner50748f42009-04-06 17:17:55 +0000528 clEnumValN(lang_c99, "iso9899:199x", "ISO C 1999"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000529 clEnumValN(lang_gnu89, "gnu89",
Gabor Greif10b26142009-02-28 09:22:15 +0000530 "ISO C 1990 with GNU extensions"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000531 clEnumValN(lang_gnu99, "gnu99",
Gabor Greif10b26142009-02-28 09:22:15 +0000532 "ISO C 1999 with GNU extensions (default for C)"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000533 clEnumValN(lang_gnu99, "gnu9x",
534 "ISO C 1999 with GNU extensions"),
535 clEnumValN(lang_cxx98, "c++98",
536 "ISO C++ 1998 with amendments"),
537 clEnumValN(lang_gnucxx98, "gnu++98",
538 "ISO C++ 1998 with amendments and GNU "
539 "extensions (default for C++)"),
Chris Lattnerd4b80f12007-07-16 04:18:29 +0000540 clEnumValN(lang_cxx0x, "c++0x",
541 "Upcoming ISO C++ 200x with amendments"),
542 clEnumValN(lang_gnucxx0x, "gnu++0x",
543 "Upcoming ISO C++ 200x with amendments and GNU "
Gabor Greif5f8d1db2009-03-11 23:07:18 +0000544 "extensions"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000545 clEnumValEnd));
546
547static llvm::cl::opt<bool>
548NoOperatorNames("fno-operator-names",
549 llvm::cl::desc("Do not treat C++ operator name keywords as "
550 "synonyms for operators"));
551
Anders Carlssonee98ac52007-10-15 02:50:23 +0000552static llvm::cl::opt<bool>
553PascalStrings("fpascal-strings",
554 llvm::cl::desc("Recognize and construct Pascal-style "
555 "string literals"));
Steve Naroffd62701b2008-02-07 03:50:06 +0000556
557static llvm::cl::opt<bool>
558MSExtensions("fms-extensions",
559 llvm::cl::desc("Accept some non-standard constructs used in "
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000560 "Microsoft header files "));
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000561
562static llvm::cl::opt<bool>
563WritableStrings("fwritable-strings",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000564 llvm::cl::desc("Store string literals as writable data"));
Anders Carlsson695dbb62007-11-30 04:21:22 +0000565
566static llvm::cl::opt<bool>
Anders Carlssonad53eff2009-01-30 23:26:40 +0000567NoLaxVectorConversions("fno-lax-vector-conversions",
Anders Carlssonb0f90cc2009-01-30 23:17:46 +0000568 llvm::cl::desc("Disallow implicit conversions between "
569 "vectors with a different number of "
570 "elements or different element types"));
Chris Lattnerae0ee032008-12-04 23:20:07 +0000571
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000572static llvm::cl::opt<bool>
Daniel Dunbar48d1ef72009-04-07 21:16:11 +0000573EnableBlocks("fblocks", llvm::cl::desc("enable the 'blocks' language feature"));
Mike Stumpa0f02aa2009-02-02 22:57:57 +0000574
575static llvm::cl::opt<bool>
Chris Lattner810f6d52009-03-13 17:38:01 +0000576EnableHeinousExtensions("fheinous-gnu-extensions",
577 llvm::cl::desc("enable GNU extensions that you really really shouldn't use"),
578 llvm::cl::ValueDisallowed, llvm::cl::Hidden);
579
580static llvm::cl::opt<bool>
Mike Stumpa0f02aa2009-02-02 22:57:57 +0000581ObjCNonFragileABI("fobjc-nonfragile-abi",
582 llvm::cl::desc("enable objective-c's nonfragile abi"));
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000583
Daniel Dunbard6884a02009-05-04 05:16:21 +0000584
585static llvm::cl::opt<bool>
Daniel Dunbard604c402009-02-04 21:19:06 +0000586EmitAllDecls("femit-all-decls",
587 llvm::cl::desc("Emit all declarations, even if unused"));
Ted Kremenek01d9dbf2008-04-29 04:37:03 +0000588
Daniel Dunbar6379a7a2008-08-11 17:36:14 +0000589static llvm::cl::opt<bool>
590Exceptions("fexceptions",
Chris Lattnerf5db8f82009-04-19 07:00:02 +0000591 llvm::cl::desc("Enable support for exception handling"));
Daniel Dunbar6379a7a2008-08-11 17:36:14 +0000592
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000593static llvm::cl::opt<bool>
594GNURuntime("fgnu-runtime",
Ted Kremenek85888962008-10-21 00:54:44 +0000595 llvm::cl::desc("Generate output compatible with the standard GNU "
Chris Lattnerf5db8f82009-04-19 07:00:02 +0000596 "Objective-C runtime"));
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000597
598static llvm::cl::opt<bool>
599NeXTRuntime("fnext-runtime",
Ted Kremenek85888962008-10-21 00:54:44 +0000600 llvm::cl::desc("Generate output compatible with the NeXT "
Chris Lattnerf5db8f82009-04-19 07:00:02 +0000601 "runtime"));
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000602
Eli Friedmanc4757bd2009-06-05 07:12:17 +0000603static llvm::cl::opt<bool>
604CharIsSigned("fsigned-char",
605 llvm::cl::desc("Force char to be a signed/unsigned type"));
Ted Kremenekea644d82008-09-03 21:22:16 +0000606
607
608static llvm::cl::opt<bool>
Chris Lattnerf5db8f82009-04-19 07:00:02 +0000609Trigraphs("trigraphs", llvm::cl::desc("Process trigraph sequences"));
Ted Kremenekea644d82008-09-03 21:22:16 +0000610
Douglas Gregor26dce442009-03-10 00:06:19 +0000611static llvm::cl::opt<unsigned>
612TemplateDepth("ftemplate-depth", llvm::cl::init(99),
613 llvm::cl::desc("Maximum depth of recursive template "
614 "instantiation"));
Chris Lattnerf5db8f82009-04-19 07:00:02 +0000615static llvm::cl::opt<bool>
616DollarsInIdents("fdollars-in-identifiers",
617 llvm::cl::desc("Allow '$' in identifiers"));
Chris Lattner16167a62009-03-02 22:11:07 +0000618
Anders Carlsson4ca076f2009-04-06 17:37:10 +0000619
620static llvm::cl::opt<bool>
621OptSize("Os", llvm::cl::desc("Optimize for size"));
622
623static llvm::cl::opt<bool>
Daniel Dunbar877db382009-06-02 22:07:45 +0000624DisableLLVMOptimizations("disable-llvm-optzns",
625 llvm::cl::desc("Don't run LLVM optimization passes"));
626
627static llvm::cl::opt<bool>
Anders Carlsson4ca076f2009-04-06 17:37:10 +0000628NoCommon("fno-common",
629 llvm::cl::desc("Compile common globals like normal definitions"),
630 llvm::cl::ValueDisallowed);
631
Daniel Dunbarc9abc042009-04-08 05:11:16 +0000632static llvm::cl::opt<std::string>
633MainFileName("main-file-name",
634 llvm::cl::desc("Main file name to use for debug info"));
Anders Carlsson4ca076f2009-04-06 17:37:10 +0000635
Anders Carlssona33d9b42009-05-13 19:49:53 +0000636// FIXME: Also add an "-fno-access-control" option.
637static llvm::cl::opt<bool>
638AccessControl("faccess-control",
639 llvm::cl::desc("Enable C++ access control"));
640
Anders Carlsson4ca076f2009-04-06 17:37:10 +0000641// It might be nice to add bounds to the CommandLine library directly.
642struct OptLevelParser : public llvm::cl::parser<unsigned> {
643 bool parse(llvm::cl::Option &O, const char *ArgName,
644 const std::string &Arg, unsigned &Val) {
645 if (llvm::cl::parser<unsigned>::parse(O, ArgName, Arg, Val))
646 return true;
Anders Carlsson4ca076f2009-04-06 17:37:10 +0000647 if (Val > 3)
648 return O.error(": '" + Arg + "' invalid optimization level!");
649 return false;
650 }
651};
652static llvm::cl::opt<unsigned, false, OptLevelParser>
653OptLevel("O", llvm::cl::Prefix,
654 llvm::cl::desc("Optimization level"),
655 llvm::cl::init(0));
656
Daniel Dunbar9fd0b1f2009-04-08 03:03:23 +0000657static llvm::cl::opt<unsigned>
Daniel Dunbar3bbc7532009-04-08 18:03:55 +0000658PICLevel("pic-level", llvm::cl::desc("Value for __PIC__"));
659
660static llvm::cl::opt<bool>
661StaticDefine("static-define", llvm::cl::desc("Should __STATIC__ be defined"));
Daniel Dunbar9fd0b1f2009-04-08 03:03:23 +0000662
Bill Wendling45483f72009-06-28 07:36:13 +0000663static llvm::cl::opt<int>
664StackProtector("stack-protector",
665 llvm::cl::desc("Enable stack protectors"),
666 llvm::cl::init(-1));
667
Daniel Dunbardcb4a1a2008-08-23 08:43:39 +0000668static void InitializeLanguageStandard(LangOptions &Options, LangKind LK,
Daniel Dunbar868bd0a2009-05-06 03:16:41 +0000669 TargetInfo *Target,
670 const llvm::StringMap<bool> &Features) {
Chris Lattner8fc4dfb2008-12-04 22:54:33 +0000671 // Allow the target to set the default the langauge options as it sees fit.
672 Target->getDefaultLangOptions(Options);
Daniel Dunbar868bd0a2009-05-06 03:16:41 +0000673
674 // Pass the map of target features to the target for validation and
675 // processing.
676 Target->HandleTargetFeatures(Features);
Chris Lattner16167a62009-03-02 22:11:07 +0000677
Reid Spencer5f016e22007-07-11 17:01:13 +0000678 if (LangStd == lang_unspecified) {
679 // Based on the base language, pick one.
Ted Kremenek8904f152007-12-05 23:49:08 +0000680 switch (LK) {
Ted Kremenekf2a17b12009-03-19 19:02:20 +0000681 case lang_unspecified: assert(0 && "Unknown base language");
Nate Begeman4e3629e2009-06-25 22:43:10 +0000682 case langkind_ocl:
683 LangStd = lang_c99;
684 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000685 case langkind_c:
Chris Lattnera778d7d2008-10-22 17:29:21 +0000686 case langkind_asm_cpp:
Reid Spencer5f016e22007-07-11 17:01:13 +0000687 case langkind_c_cpp:
688 case langkind_objc:
689 case langkind_objc_cpp:
690 LangStd = lang_gnu99;
691 break;
692 case langkind_cxx:
693 case langkind_cxx_cpp:
694 case langkind_objcxx:
695 case langkind_objcxx_cpp:
696 LangStd = lang_gnucxx98;
697 break;
698 }
699 }
700
701 switch (LangStd) {
702 default: assert(0 && "Unknown language standard!");
703
704 // Fall through from newer standards to older ones. This isn't really right.
705 // FIXME: Enable specifically the right features based on the language stds.
Chris Lattnerd4b80f12007-07-16 04:18:29 +0000706 case lang_gnucxx0x:
707 case lang_cxx0x:
708 Options.CPlusPlus0x = 1;
709 // FALL THROUGH
Reid Spencer5f016e22007-07-11 17:01:13 +0000710 case lang_gnucxx98:
711 case lang_cxx98:
712 Options.CPlusPlus = 1;
713 Options.CXXOperatorNames = !NoOperatorNames;
714 // FALL THROUGH.
715 case lang_gnu99:
716 case lang_c99:
Reid Spencer5f016e22007-07-11 17:01:13 +0000717 Options.C99 = 1;
718 Options.HexFloats = 1;
719 // FALL THROUGH.
720 case lang_gnu89:
721 Options.BCPLComment = 1; // Only for C99/C++.
722 // FALL THROUGH.
723 case lang_c94:
Chris Lattner3426b9b2008-02-25 04:01:39 +0000724 Options.Digraphs = 1; // C94, C99, C++.
725 // FALL THROUGH.
Reid Spencer5f016e22007-07-11 17:01:13 +0000726 case lang_c89:
727 break;
728 }
Argyrios Kyrtzidisd1465522008-09-11 04:21:06 +0000729
Chris Lattner7e9c90b2009-03-20 15:44:26 +0000730 // GNUMode - Set if we're in gnu99, gnu89, gnucxx98, etc.
731 Options.GNUMode = LangStd >= lang_gnu_START;
732
Argyrios Kyrtzidisd1465522008-09-11 04:21:06 +0000733 if (Options.CPlusPlus) {
734 Options.C99 = 0;
Chris Lattner7e9c90b2009-03-20 15:44:26 +0000735 Options.HexFloats = Options.GNUMode;
Argyrios Kyrtzidisd1465522008-09-11 04:21:06 +0000736 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000737
Chris Lattnerd658b562008-04-05 06:32:51 +0000738 if (LangStd == lang_c89 || LangStd == lang_c94 || LangStd == lang_gnu89)
739 Options.ImplicitInt = 1;
740 else
741 Options.ImplicitInt = 0;
Ted Kremenekea644d82008-09-03 21:22:16 +0000742
Daniel Dunbard573d262009-04-07 22:13:21 +0000743 // Mimicing gcc's behavior, trigraphs are only enabled if -trigraphs
744 // is specified, or -std is set to a conforming mode.
Chris Lattner7e9c90b2009-03-20 15:44:26 +0000745 Options.Trigraphs = !Options.GNUMode;
Chris Lattner802db9b2008-12-05 00:10:44 +0000746 if (Trigraphs.getPosition())
Chris Lattner7e9c90b2009-03-20 15:44:26 +0000747 Options.Trigraphs = Trigraphs; // Command line option wins if specified.
Ted Kremenekea644d82008-09-03 21:22:16 +0000748
Chris Lattner802db9b2008-12-05 00:10:44 +0000749 // If in a conformant language mode (e.g. -std=c99) Blocks defaults to off
750 // even if they are normally on for the target. In GNU modes (e.g.
751 // -std=gnu99) the default for blocks depends on the target settings.
Anders Carlssone56f6ff2009-01-21 18:47:36 +0000752 // However, blocks are not turned off when compiling Obj-C or Obj-C++ code.
Chris Lattner7e9c90b2009-03-20 15:44:26 +0000753 if (!Options.ObjC1 && !Options.GNUMode)
Chris Lattner802db9b2008-12-05 00:10:44 +0000754 Options.Blocks = 0;
755
Chris Lattner01638a62009-04-19 07:06:52 +0000756 // Default to not accepting '$' in identifiers when preprocessing assembler,
757 // but do accept when preprocessing C. FIXME: these defaults are right for
758 // darwin, are they right everywhere?
759 Options.DollarIdents = LK != langkind_asm_cpp;
760 if (DollarsInIdents.getPosition()) // Explicit setting overrides default.
Chris Lattnerf5db8f82009-04-19 07:00:02 +0000761 Options.DollarIdents = DollarsInIdents;
762
Chris Lattnerae0ee032008-12-04 23:20:07 +0000763 if (PascalStrings.getPosition())
764 Options.PascalStrings = PascalStrings;
Eli Friedmanabc4e322009-06-08 06:11:14 +0000765 if (MSExtensions.getPosition())
766 Options.Microsoft = MSExtensions;
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000767 Options.WritableStrings = WritableStrings;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +0000768 if (NoLaxVectorConversions.getPosition())
769 Options.LaxVectorConversions = 0;
Daniel Dunbar6379a7a2008-08-11 17:36:14 +0000770 Options.Exceptions = Exceptions;
Mike Stumpa0f02aa2009-02-02 22:57:57 +0000771 if (EnableBlocks.getPosition())
Chris Lattnerae0ee032008-12-04 23:20:07 +0000772 Options.Blocks = EnableBlocks;
Eli Friedmanc4757bd2009-06-05 07:12:17 +0000773 if (CharIsSigned.getPosition())
774 Options.CharIsSigned = CharIsSigned;
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000775
Daniel Dunbar9f9768c2009-03-20 23:49:28 +0000776 if (!AllowBuiltins)
Chris Lattner7644f072009-03-13 22:38:49 +0000777 Options.NoBuiltin = 1;
Douglas Gregor3573c0c2009-02-14 20:49:29 +0000778 if (Freestanding)
Chris Lattner7644f072009-03-13 22:38:49 +0000779 Options.Freestanding = Options.NoBuiltin = 1;
780
Chris Lattner810f6d52009-03-13 17:38:01 +0000781 if (EnableHeinousExtensions)
782 Options.HeinousExtensions = 1;
Douglas Gregor3573c0c2009-02-14 20:49:29 +0000783
Anders Carlssona33d9b42009-05-13 19:49:53 +0000784 if (AccessControl)
785 Options.AccessControl = 1;
786
Daniel Dunbaref2abfe2009-02-16 22:43:43 +0000787 Options.MathErrno = MathErrno;
788
Douglas Gregor26dce442009-03-10 00:06:19 +0000789 Options.InstantiationDepth = TemplateDepth;
790
Chris Lattner8fc4dfb2008-12-04 22:54:33 +0000791 // Override the default runtime if the user requested it.
792 if (NeXTRuntime)
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000793 Options.NeXTRuntime = 1;
Chris Lattner8fc4dfb2008-12-04 22:54:33 +0000794 else if (GNURuntime)
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000795 Options.NeXTRuntime = 0;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000796
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000797 if (ObjCNonFragileABI)
798 Options.ObjCNonFragileABI = 1;
Fariborz Jahanian34e65772009-05-22 20:17:16 +0000799
800 Options.ObjCSenderDispatch = ObjCSenderDispatch;
Daniel Dunbard6884a02009-05-04 05:16:21 +0000801
Daniel Dunbard604c402009-02-04 21:19:06 +0000802 if (EmitAllDecls)
803 Options.EmitAllDecls = 1;
Anders Carlsson4ca076f2009-04-06 17:37:10 +0000804
Daniel Dunbar3bbc7532009-04-08 18:03:55 +0000805 // The __OPTIMIZE_SIZE__ define is tied to -Oz, which we don't
806 // support.
807 Options.OptimizeSize = 0;
Anders Carlsson4ca076f2009-04-06 17:37:10 +0000808
809 // -Os implies -O2
Daniel Dunbar3bbc7532009-04-08 18:03:55 +0000810 if (OptSize || OptLevel)
Anders Carlsson4ca076f2009-04-06 17:37:10 +0000811 Options.Optimize = 1;
Daniel Dunbar9fd0b1f2009-04-08 03:03:23 +0000812
813 assert(PICLevel <= 2 && "Invalid value for -pic-level");
814 Options.PICLevel = PICLevel;
Daniel Dunbarc9abc042009-04-08 05:11:16 +0000815
Daniel Dunbar3bbc7532009-04-08 18:03:55 +0000816 Options.GNUInline = !Options.C99;
Chris Lattner5aeb9e72009-05-06 04:38:30 +0000817 // FIXME: This is affected by other options (-fno-inline).
Daniel Dunbar3bbc7532009-04-08 18:03:55 +0000818 Options.NoInline = !OptSize && !OptLevel;
819
820 Options.Static = StaticDefine;
821
Bill Wendling4ebe3e42009-06-28 23:01:01 +0000822 switch (StackProtector) {
823 default:
824 assert(StackProtector <= 2 && "Invalid value for -stack-protector");
825 case -1: break;
826 case 0: Options.setStackProtectorMode(LangOptions::SSPOff); break;
827 case 1: Options.setStackProtectorMode(LangOptions::SSPOn); break;
828 case 2: Options.setStackProtectorMode(LangOptions::SSPReq); break;
829 }
Bill Wendling45483f72009-06-28 07:36:13 +0000830
Daniel Dunbarc9abc042009-04-08 05:11:16 +0000831 if (MainFileName.getPosition())
832 Options.setMainFileName(MainFileName.c_str());
Reid Spencer5f016e22007-07-11 17:01:13 +0000833}
834
835//===----------------------------------------------------------------------===//
Ted Kremenekae360762007-12-03 22:06:55 +0000836// Target Triple Processing.
837//===----------------------------------------------------------------------===//
838
839static llvm::cl::opt<std::string>
840TargetTriple("triple",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000841 llvm::cl::desc("Specify target triple (e.g. i686-apple-darwin9)"));
Ted Kremenekae360762007-12-03 22:06:55 +0000842
Chris Lattner42e67372008-03-05 01:18:20 +0000843static llvm::cl::opt<std::string>
Chris Lattner6a30c1f2008-09-30 01:13:12 +0000844MacOSVersionMin("mmacosx-version-min",
Daniel Dunbar8d33cd72009-04-10 19:52:24 +0000845 llvm::cl::desc("Specify target Mac OS X version (e.g. 10.5)"));
Chris Lattner6a30c1f2008-09-30 01:13:12 +0000846
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000847// If -mmacosx-version-min=10.3.9 is specified, change the triple from being
848// something like powerpc-apple-darwin9 to powerpc-apple-darwin7
Daniel Dunbar64ffc142009-03-31 20:10:05 +0000849
850// FIXME: We should have the driver do this instead.
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000851static void HandleMacOSVersionMin(std::string &Triple) {
852 std::string::size_type DarwinDashIdx = Triple.find("-darwin");
853 if (DarwinDashIdx == std::string::npos) {
854 fprintf(stderr,
Daniel Dunbar8d33cd72009-04-10 19:52:24 +0000855 "-mmacosx-version-min only valid for darwin (Mac OS X) targets\n");
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000856 exit(1);
857 }
858 unsigned DarwinNumIdx = DarwinDashIdx + strlen("-darwin");
859
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000860 // Remove the number.
861 Triple.resize(DarwinNumIdx);
862
863 // Validate that MacOSVersionMin is a 'version number', starting with 10.[3-9]
864 bool MacOSVersionMinIsInvalid = false;
865 int VersionNum = 0;
866 if (MacOSVersionMin.size() < 4 ||
867 MacOSVersionMin.substr(0, 3) != "10." ||
868 !isdigit(MacOSVersionMin[3])) {
869 MacOSVersionMinIsInvalid = true;
870 } else {
871 const char *Start = MacOSVersionMin.c_str()+3;
872 char *End = 0;
873 VersionNum = (int)strtol(Start, &End, 10);
874
Chris Lattner079f2c462008-09-30 20:30:12 +0000875 // The version number must be in the range 0-9.
876 MacOSVersionMinIsInvalid = (unsigned)VersionNum > 9;
877
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000878 // Turn MacOSVersionMin into a darwin number: e.g. 10.3.9 is 3 -> 7.
879 Triple += llvm::itostr(VersionNum+4);
880
Chris Lattner079f2c462008-09-30 20:30:12 +0000881 if (End[0] == '.' && isdigit(End[1]) && End[2] == '\0') { // 10.4.7 is ok.
882 // Add the period piece (.7) to the end of the triple. This gives us
883 // something like ...-darwin8.7
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000884 Triple += End;
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000885 } else if (End[0] != '\0') { // "10.4" is ok. 10.4x is not.
886 MacOSVersionMinIsInvalid = true;
887 }
888 }
889
890 if (MacOSVersionMinIsInvalid) {
891 fprintf(stderr,
Daniel Dunbaraf07f932009-03-31 17:35:15 +0000892 "-mmacosx-version-min=%s is invalid, expected something like '10.4'.\n",
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000893 MacOSVersionMin.c_str());
894 exit(1);
895 }
Fariborz Jahanian6a1284a2009-04-10 20:33:45 +0000896 else if (VersionNum <= 4 &&
897 !strncmp(Triple.c_str(), "x86_64", strlen("x86_64"))) {
898 fprintf(stderr,
899 "-mmacosx-version-min=%s is invalid with -arch x86_64.\n",
900 MacOSVersionMin.c_str());
901 exit(1);
902 }
903
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000904}
905
Daniel Dunbar8d33cd72009-04-10 19:52:24 +0000906static llvm::cl::opt<std::string>
907IPhoneOSVersionMin("miphoneos-version-min",
908 llvm::cl::desc("Specify target iPhone OS version (e.g. 2.0)"));
909
910// If -miphoneos-version-min=2.2 is specified, change the triple from being
911// something like armv6-apple-darwin10 to armv6-apple-darwin9.2.2. We use
912// 9 as the default major Darwin number, and encode the iPhone OS version
913// number in the minor version and revision.
914
915// FIXME: We should have the driver do this instead.
916static void HandleIPhoneOSVersionMin(std::string &Triple) {
917 std::string::size_type DarwinDashIdx = Triple.find("-darwin");
918 if (DarwinDashIdx == std::string::npos) {
919 fprintf(stderr,
920 "-miphoneos-version-min only valid for darwin (Mac OS X) targets\n");
921 exit(1);
922 }
923 unsigned DarwinNumIdx = DarwinDashIdx + strlen("-darwin");
924
925 // Remove the number.
926 Triple.resize(DarwinNumIdx);
927
928 // Validate that IPhoneOSVersionMin is a 'version number', starting with [2-9].[0-9]
929 bool IPhoneOSVersionMinIsInvalid = false;
930 int VersionNum = 0;
931 if (IPhoneOSVersionMin.size() < 3 ||
932 !isdigit(IPhoneOSVersionMin[0])) {
933 IPhoneOSVersionMinIsInvalid = true;
934 } else {
935 const char *Start = IPhoneOSVersionMin.c_str();
936 char *End = 0;
937 VersionNum = (int)strtol(Start, &End, 10);
938
939 // The version number must be in the range 0-9.
940 IPhoneOSVersionMinIsInvalid = (unsigned)VersionNum > 9;
941
942 // Turn IPhoneOSVersionMin into a darwin number: e.g. 2.0 is 2 -> 9.2.
943 Triple += "9." + llvm::itostr(VersionNum);
944
945 if (End[0] == '.' && isdigit(End[1]) && End[2] == '\0') { // 2.2 is ok.
946 // Add the period piece (.2) to the end of the triple. This gives us
947 // something like ...-darwin9.2.2
948 Triple += End;
949 } else if (End[0] != '\0') { // "2.2" is ok. 2x is not.
950 IPhoneOSVersionMinIsInvalid = true;
951 }
952 }
953
954 if (IPhoneOSVersionMinIsInvalid) {
955 fprintf(stderr,
956 "-miphoneos-version-min=%s is invalid, expected something like '2.0'.\n",
957 IPhoneOSVersionMin.c_str());
958 exit(1);
959 }
960}
961
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000962/// CreateTargetTriple - Process the various options that affect the target
963/// triple and build a final aggregate triple that we are compiling for.
Chris Lattner6fd9fa12008-03-09 01:35:13 +0000964static std::string CreateTargetTriple() {
Ted Kremenekae360762007-12-03 22:06:55 +0000965 // Initialize base triple. If a -triple option has been specified, use
966 // that triple. Otherwise, default to the host triple.
Chris Lattner6590d212007-12-12 05:01:48 +0000967 std::string Triple = TargetTriple;
Daniel Dunbaraf07f932009-03-31 17:35:15 +0000968 if (Triple.empty())
969 Triple = llvm::sys::getHostTriple();
Chris Lattner6a30c1f2008-09-30 01:13:12 +0000970
971 // If -mmacosx-version-min=10.3.9 is specified, change the triple from being
972 // something like powerpc-apple-darwin9 to powerpc-apple-darwin7
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000973 if (!MacOSVersionMin.empty())
974 HandleMacOSVersionMin(Triple);
Daniel Dunbar8d33cd72009-04-10 19:52:24 +0000975 else if (!IPhoneOSVersionMin.empty())
976 HandleIPhoneOSVersionMin(Triple);;
Ted Kremenekae360762007-12-03 22:06:55 +0000977
Chris Lattner6a30c1f2008-09-30 01:13:12 +0000978 return Triple;
Ted Kremenekae360762007-12-03 22:06:55 +0000979}
980
981//===----------------------------------------------------------------------===//
Chris Lattnere116ccf2009-04-21 05:40:52 +0000982// SourceManager initialization.
Reid Spencer5f016e22007-07-11 17:01:13 +0000983//===----------------------------------------------------------------------===//
984
Douglas Gregore1d918e2009-04-10 23:10:45 +0000985static bool InitializeSourceManager(Preprocessor &PP,
986 const std::string &InFile) {
987 // Figure out where to get and map in the main file.
988 SourceManager &SourceMgr = PP.getSourceManager();
989 FileManager &FileMgr = PP.getFileManager();
Daniel Dunbar57cbfc02009-04-27 21:19:07 +0000990
991 if (EmptyInputOnly) {
992 const char *EmptyStr = "";
993 llvm::MemoryBuffer *SB =
994 llvm::MemoryBuffer::getMemBuffer(EmptyStr, EmptyStr, "<empty input>");
995 SourceMgr.createMainFileIDForMemBuffer(SB);
996 } else if (InFile != "-") {
Douglas Gregore1d918e2009-04-10 23:10:45 +0000997 const FileEntry *File = FileMgr.getFile(InFile);
998 if (File) SourceMgr.createMainFileID(File, SourceLocation());
999 if (SourceMgr.getMainFileID().isInvalid()) {
1000 PP.getDiagnostics().Report(FullSourceLoc(), diag::err_fe_error_reading)
1001 << InFile.c_str();
1002 return true;
1003 }
1004 } else {
1005 llvm::MemoryBuffer *SB = llvm::MemoryBuffer::getSTDIN();
1006
1007 // If stdin was empty, SB is null. Cons up an empty memory
1008 // buffer now.
1009 if (!SB) {
1010 const char *EmptyStr = "";
1011 SB = llvm::MemoryBuffer::getMemBuffer(EmptyStr, EmptyStr, "<stdin>");
1012 }
1013
1014 SourceMgr.createMainFileIDForMemBuffer(SB);
1015 if (SourceMgr.getMainFileID().isInvalid()) {
1016 PP.getDiagnostics().Report(FullSourceLoc(),
1017 diag::err_fe_error_reading_stdin);
1018 return true;
1019 }
1020 }
1021
1022 return false;
1023}
1024
Chris Lattneraa391972008-04-19 23:09:31 +00001025
Chris Lattnere116ccf2009-04-21 05:40:52 +00001026//===----------------------------------------------------------------------===//
1027// Preprocessor Initialization
1028//===----------------------------------------------------------------------===//
Sam Bishop1102d6b2008-04-14 14:41:57 +00001029
Chris Lattnere116ccf2009-04-21 05:40:52 +00001030// FIXME: Preprocessor builtins to support.
1031// -A... - Play with #assertions
1032// -undef - Undefine all predefined macros
Chris Lattnerb31ac222009-04-08 20:15:42 +00001033
Chris Lattnere116ccf2009-04-21 05:40:52 +00001034static llvm::cl::list<std::string>
1035D_macros("D", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
1036 llvm::cl::desc("Predefine the specified macro"));
1037static llvm::cl::list<std::string>
1038U_macros("U", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
1039 llvm::cl::desc("Undefine the specified macro"));
Chris Lattnerb8e240e2009-04-08 18:24:34 +00001040
Chris Lattnere116ccf2009-04-21 05:40:52 +00001041static llvm::cl::list<std::string>
1042ImplicitIncludes("include", llvm::cl::value_desc("file"),
1043 llvm::cl::desc("Include file before parsing"));
1044static llvm::cl::list<std::string>
1045ImplicitMacroIncludes("imacros", llvm::cl::value_desc("file"),
1046 llvm::cl::desc("Include macros from file before parsing"));
Chris Lattnerb8e240e2009-04-08 18:24:34 +00001047
Chris Lattnere116ccf2009-04-21 05:40:52 +00001048static llvm::cl::opt<std::string>
1049ImplicitIncludePCH("include-pch", llvm::cl::value_desc("file"),
1050 llvm::cl::desc("Include precompiled header file"));
1051
1052static llvm::cl::opt<std::string>
1053ImplicitIncludePTH("include-pth", llvm::cl::value_desc("file"),
1054 llvm::cl::desc("Include file before parsing"));
1055
Reid Spencer5f016e22007-07-11 17:01:13 +00001056
1057//===----------------------------------------------------------------------===//
1058// Preprocessor include path information.
1059//===----------------------------------------------------------------------===//
1060
1061// This tool exports a large number of command line options to control how the
1062// preprocessor searches for header files. At root, however, the Preprocessor
1063// object takes a very simple interface: a list of directories to search for
1064//
Daniel Dunbarfb4ac7b2009-05-06 03:48:17 +00001065// FIXME: -nostdinc++
Chris Lattner0c946412007-08-26 17:47:35 +00001066// FIXME: -imultilib
Reid Spencer5f016e22007-07-11 17:01:13 +00001067//
Reid Spencer5f016e22007-07-11 17:01:13 +00001068
1069static llvm::cl::opt<bool>
1070nostdinc("nostdinc", llvm::cl::desc("Disable standard #include directories"));
1071
1072// Various command line options. These four add directories to each chain.
1073static llvm::cl::list<std::string>
1074F_dirs("F", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1075 llvm::cl::desc("Add directory to framework include search path"));
1076static llvm::cl::list<std::string>
1077I_dirs("I", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1078 llvm::cl::desc("Add directory to include search path"));
1079static llvm::cl::list<std::string>
1080idirafter_dirs("idirafter", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1081 llvm::cl::desc("Add directory to AFTER include search path"));
1082static llvm::cl::list<std::string>
1083iquote_dirs("iquote", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1084 llvm::cl::desc("Add directory to QUOTE include search path"));
1085static llvm::cl::list<std::string>
1086isystem_dirs("isystem", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1087 llvm::cl::desc("Add directory to SYSTEM include search path"));
1088
1089// These handle -iprefix/-iwithprefix/-iwithprefixbefore.
1090static llvm::cl::list<std::string>
1091iprefix_vals("iprefix", llvm::cl::value_desc("prefix"), llvm::cl::Prefix,
1092 llvm::cl::desc("Set the -iwithprefix/-iwithprefixbefore prefix"));
1093static llvm::cl::list<std::string>
1094iwithprefix_vals("iwithprefix", llvm::cl::value_desc("dir"), llvm::cl::Prefix,
1095 llvm::cl::desc("Set directory to SYSTEM include search path with prefix"));
1096static llvm::cl::list<std::string>
1097iwithprefixbefore_vals("iwithprefixbefore", llvm::cl::value_desc("dir"),
1098 llvm::cl::Prefix,
1099 llvm::cl::desc("Set directory to include search path with prefix"));
1100
Chris Lattner0c946412007-08-26 17:47:35 +00001101static llvm::cl::opt<std::string>
1102isysroot("isysroot", llvm::cl::value_desc("dir"), llvm::cl::init("/"),
1103 llvm::cl::desc("Set the system root directory (usually /)"));
1104
Reid Spencer5f016e22007-07-11 17:01:13 +00001105// Finally, implement the code that groks the options above.
Chris Lattner5f9eae52008-03-01 08:07:28 +00001106
Reid Spencer5f016e22007-07-11 17:01:13 +00001107/// InitializeIncludePaths - Process the -I options and set them in the
1108/// HeaderSearch object.
Nico Weber0fca0222008-08-22 09:25:22 +00001109void InitializeIncludePaths(const char *Argv0, HeaderSearch &Headers,
1110 FileManager &FM, const LangOptions &Lang) {
1111 InitHeaderSearch Init(Headers, Verbose, isysroot);
1112
Ted Kremenekf3721112008-05-31 00:27:00 +00001113 // Handle -I... and -F... options, walking the lists in parallel.
1114 unsigned Iidx = 0, Fidx = 0;
1115 while (Iidx < I_dirs.size() && Fidx < F_dirs.size()) {
1116 if (I_dirs.getPosition(Iidx) < F_dirs.getPosition(Fidx)) {
Nico Weber0fca0222008-08-22 09:25:22 +00001117 Init.AddPath(I_dirs[Iidx], InitHeaderSearch::Angled, false, true, false);
Ted Kremenekf3721112008-05-31 00:27:00 +00001118 ++Iidx;
1119 } else {
Nico Weber0fca0222008-08-22 09:25:22 +00001120 Init.AddPath(F_dirs[Fidx], InitHeaderSearch::Angled, false, true, true);
Ted Kremenekf3721112008-05-31 00:27:00 +00001121 ++Fidx;
1122 }
1123 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001124
Ted Kremenekf3721112008-05-31 00:27:00 +00001125 // Consume what's left from whatever list was longer.
1126 for (; Iidx != I_dirs.size(); ++Iidx)
Nico Weber0fca0222008-08-22 09:25:22 +00001127 Init.AddPath(I_dirs[Iidx], InitHeaderSearch::Angled, false, true, false);
Ted Kremenekf3721112008-05-31 00:27:00 +00001128 for (; Fidx != F_dirs.size(); ++Fidx)
Nico Weber0fca0222008-08-22 09:25:22 +00001129 Init.AddPath(F_dirs[Fidx], InitHeaderSearch::Angled, false, true, true);
Reid Spencer5f016e22007-07-11 17:01:13 +00001130
1131 // Handle -idirafter... options.
1132 for (unsigned i = 0, e = idirafter_dirs.size(); i != e; ++i)
Nico Weber0fca0222008-08-22 09:25:22 +00001133 Init.AddPath(idirafter_dirs[i], InitHeaderSearch::After,
1134 false, true, false);
Reid Spencer5f016e22007-07-11 17:01:13 +00001135
1136 // Handle -iquote... options.
1137 for (unsigned i = 0, e = iquote_dirs.size(); i != e; ++i)
Nico Weber0fca0222008-08-22 09:25:22 +00001138 Init.AddPath(iquote_dirs[i], InitHeaderSearch::Quoted, false, true, false);
Reid Spencer5f016e22007-07-11 17:01:13 +00001139
1140 // Handle -isystem... options.
1141 for (unsigned i = 0, e = isystem_dirs.size(); i != e; ++i)
Nico Weber0fca0222008-08-22 09:25:22 +00001142 Init.AddPath(isystem_dirs[i], InitHeaderSearch::System, false, true, false);
Reid Spencer5f016e22007-07-11 17:01:13 +00001143
1144 // Walk the -iprefix/-iwithprefix/-iwithprefixbefore argument lists in
1145 // parallel, processing the values in order of occurance to get the right
1146 // prefixes.
1147 {
1148 std::string Prefix = ""; // FIXME: this isn't the correct default prefix.
1149 unsigned iprefix_idx = 0;
1150 unsigned iwithprefix_idx = 0;
1151 unsigned iwithprefixbefore_idx = 0;
1152 bool iprefix_done = iprefix_vals.empty();
1153 bool iwithprefix_done = iwithprefix_vals.empty();
1154 bool iwithprefixbefore_done = iwithprefixbefore_vals.empty();
1155 while (!iprefix_done || !iwithprefix_done || !iwithprefixbefore_done) {
1156 if (!iprefix_done &&
1157 (iwithprefix_done ||
1158 iprefix_vals.getPosition(iprefix_idx) <
1159 iwithprefix_vals.getPosition(iwithprefix_idx)) &&
1160 (iwithprefixbefore_done ||
1161 iprefix_vals.getPosition(iprefix_idx) <
1162 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
1163 Prefix = iprefix_vals[iprefix_idx];
1164 ++iprefix_idx;
1165 iprefix_done = iprefix_idx == iprefix_vals.size();
1166 } else if (!iwithprefix_done &&
1167 (iwithprefixbefore_done ||
1168 iwithprefix_vals.getPosition(iwithprefix_idx) <
1169 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
Nico Weber0fca0222008-08-22 09:25:22 +00001170 Init.AddPath(Prefix+iwithprefix_vals[iwithprefix_idx],
1171 InitHeaderSearch::System, false, false, false);
Reid Spencer5f016e22007-07-11 17:01:13 +00001172 ++iwithprefix_idx;
1173 iwithprefix_done = iwithprefix_idx == iwithprefix_vals.size();
1174 } else {
Nico Weber0fca0222008-08-22 09:25:22 +00001175 Init.AddPath(Prefix+iwithprefixbefore_vals[iwithprefixbefore_idx],
1176 InitHeaderSearch::Angled, false, false, false);
Reid Spencer5f016e22007-07-11 17:01:13 +00001177 ++iwithprefixbefore_idx;
1178 iwithprefixbefore_done =
1179 iwithprefixbefore_idx == iwithprefixbefore_vals.size();
1180 }
1181 }
1182 }
Chris Lattner5f9eae52008-03-01 08:07:28 +00001183
Nico Weber0fca0222008-08-22 09:25:22 +00001184 Init.AddDefaultEnvVarPaths(Lang);
Chris Lattner5f9eae52008-03-01 08:07:28 +00001185
Daniel Dunbaradcf5b32009-02-21 20:52:41 +00001186 // Add the clang headers, which are relative to the clang binary.
Chris Lattnerdcaa0962008-03-03 03:16:03 +00001187 llvm::sys::Path MainExecutablePath =
Chris Lattner985e1822008-03-03 05:57:43 +00001188 llvm::sys::Path::GetMainExecutable(Argv0,
1189 (void*)(intptr_t)InitializeIncludePaths);
Chris Lattnerdcaa0962008-03-03 03:16:03 +00001190 if (!MainExecutablePath.isEmpty()) {
1191 MainExecutablePath.eraseComponent(); // Remove /clang from foo/bin/clang
1192 MainExecutablePath.eraseComponent(); // Remove /bin from foo/bin
Daniel Dunbaradcf5b32009-02-21 20:52:41 +00001193
Daniel Dunbarfb4ac7b2009-05-06 03:48:17 +00001194 // Get foo/lib/clang/<version>/include
Daniel Dunbaradcf5b32009-02-21 20:52:41 +00001195 MainExecutablePath.appendComponent("lib");
1196 MainExecutablePath.appendComponent("clang");
Daniel Dunbarfb4ac7b2009-05-06 03:48:17 +00001197 MainExecutablePath.appendComponent(CLANG_VERSION_STRING);
Daniel Dunbaradcf5b32009-02-21 20:52:41 +00001198 MainExecutablePath.appendComponent("include");
Chris Lattner6858dd32009-02-19 06:48:28 +00001199
1200 // We pass true to ignore sysroot so that we *always* look for clang headers
1201 // relative to our executable, never relative to -isysroot.
1202 Init.AddPath(MainExecutablePath.c_str(), InitHeaderSearch::System,
1203 false, false, false, true /*ignore sysroot*/);
Chris Lattnerdcaa0962008-03-03 03:16:03 +00001204 }
1205
Nico Weber0fca0222008-08-22 09:25:22 +00001206 if (!nostdinc)
1207 Init.AddDefaultSystemIncludePaths(Lang);
Reid Spencer5f016e22007-07-11 17:01:13 +00001208
1209 // Now that we have collected all of the include paths, merge them all
1210 // together and tell the preprocessor about them.
1211
Nico Weber0fca0222008-08-22 09:25:22 +00001212 Init.Realize();
Reid Spencer5f016e22007-07-11 17:01:13 +00001213}
1214
Chris Lattnere116ccf2009-04-21 05:40:52 +00001215void InitializePreprocessorInitOptions(PreprocessorInitOptions &InitOpts)
1216{
1217 // Add macros from the command line.
1218 unsigned d = 0, D = D_macros.size();
1219 unsigned u = 0, U = U_macros.size();
1220 while (d < D || u < U) {
1221 if (u == U || (d < D && D_macros.getPosition(d) < U_macros.getPosition(u)))
1222 InitOpts.addMacroDef(D_macros[d++]);
1223 else
1224 InitOpts.addMacroUndef(U_macros[u++]);
1225 }
1226
1227 // If -imacros are specified, include them now. These are processed before
1228 // any -include directives.
1229 for (unsigned i = 0, e = ImplicitMacroIncludes.size(); i != e; ++i)
1230 InitOpts.addMacroInclude(ImplicitMacroIncludes[i]);
1231
Douglas Gregorb64c1932009-05-12 01:31:05 +00001232 if (!ImplicitIncludePTH.empty() || !ImplicitIncludes.empty() ||
1233 (!ImplicitIncludePCH.empty() && ProgAction == PrintPreprocessedInput)) {
Chris Lattnere116ccf2009-04-21 05:40:52 +00001234 // We want to add these paths to the predefines buffer in order, make a
1235 // temporary vector to sort by their occurrence.
1236 llvm::SmallVector<std::pair<unsigned, std::string*>, 8> OrderedPaths;
1237
1238 if (!ImplicitIncludePTH.empty())
1239 OrderedPaths.push_back(std::make_pair(ImplicitIncludePTH.getPosition(),
1240 &ImplicitIncludePTH));
Douglas Gregorb64c1932009-05-12 01:31:05 +00001241 if (!ImplicitIncludePCH.empty() && ProgAction == PrintPreprocessedInput)
1242 OrderedPaths.push_back(std::make_pair(ImplicitIncludePCH.getPosition(),
1243 &ImplicitIncludePCH));
Chris Lattnere116ccf2009-04-21 05:40:52 +00001244 for (unsigned i = 0, e = ImplicitIncludes.size(); i != e; ++i)
1245 OrderedPaths.push_back(std::make_pair(ImplicitIncludes.getPosition(i),
1246 &ImplicitIncludes[i]));
1247 llvm::array_pod_sort(OrderedPaths.begin(), OrderedPaths.end());
1248
1249
1250 // Now that they are ordered by position, add to the predefines buffer.
1251 for (unsigned i = 0, e = OrderedPaths.size(); i != e; ++i) {
1252 std::string *Ptr = OrderedPaths[i].second;
1253 if (!ImplicitIncludes.empty() &&
1254 Ptr >= &ImplicitIncludes[0] &&
1255 Ptr <= &ImplicitIncludes[ImplicitIncludes.size()-1]) {
1256 InitOpts.addInclude(*Ptr, false);
Douglas Gregorb64c1932009-05-12 01:31:05 +00001257 } else if (Ptr == &ImplicitIncludePTH) {
Chris Lattnere116ccf2009-04-21 05:40:52 +00001258 InitOpts.addInclude(*Ptr, true);
Douglas Gregorb64c1932009-05-12 01:31:05 +00001259 } else {
1260 // We end up here when we're producing preprocessed output and
1261 // we loaded a PCH file. In this case, just include the header
1262 // file that was used to build the precompiled header.
1263 assert(Ptr == &ImplicitIncludePCH);
1264 std::string OriginalFile = PCHReader::getOriginalSourceFile(*Ptr);
1265 if (!OriginalFile.empty()) {
1266 InitOpts.addInclude(OriginalFile, false);
1267 ImplicitIncludePCH.clear();
1268 }
Chris Lattnere116ccf2009-04-21 05:40:52 +00001269 }
1270 }
1271 }
1272}
1273
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001274//===----------------------------------------------------------------------===//
1275// Driver PreprocessorFactory - For lazily generating preprocessors ...
1276//===----------------------------------------------------------------------===//
1277
1278namespace {
1279class VISIBILITY_HIDDEN DriverPreprocessorFactory : public PreprocessorFactory {
1280 Diagnostic &Diags;
1281 const LangOptions &LangInfo;
1282 TargetInfo &Target;
1283 SourceManager &SourceMgr;
1284 HeaderSearch &HeaderInfo;
Ted Kremenek339b9c22008-04-17 22:31:54 +00001285
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001286public:
Eli Friedmanf086e3b2009-05-18 07:39:39 +00001287 DriverPreprocessorFactory(Diagnostic &diags, const LangOptions &opts,
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001288 TargetInfo &target, SourceManager &SM,
1289 HeaderSearch &Headers)
Eli Friedmanf086e3b2009-05-18 07:39:39 +00001290 : Diags(diags), LangInfo(opts), Target(target),
Douglas Gregore1d918e2009-04-10 23:10:45 +00001291 SourceMgr(SM), HeaderInfo(Headers) {}
Ted Kremenek339b9c22008-04-17 22:31:54 +00001292
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001293
1294 virtual ~DriverPreprocessorFactory() {}
1295
1296 virtual Preprocessor* CreatePreprocessor() {
Ted Kremenek72b1b152009-01-15 18:47:46 +00001297 llvm::OwningPtr<PTHManager> PTHMgr;
1298
Ted Kremenek748d5d62009-03-20 00:26:38 +00001299 if (!TokenCache.empty() && !ImplicitIncludePTH.empty()) {
1300 fprintf(stderr, "error: cannot use both -token-cache and -include-pth "
1301 "options\n");
Ted Kremenek22f0d092009-03-22 06:42:39 +00001302 exit(1);
Ted Kremenek748d5d62009-03-20 00:26:38 +00001303 }
1304
Ted Kremenek72b1b152009-01-15 18:47:46 +00001305 // Use PTH?
Ted Kremenek748d5d62009-03-20 00:26:38 +00001306 if (!TokenCache.empty() || !ImplicitIncludePTH.empty()) {
1307 const std::string& x = TokenCache.empty() ? ImplicitIncludePTH:TokenCache;
Ted Kremenek22f0d092009-03-22 06:42:39 +00001308 PTHMgr.reset(PTHManager::Create(x, &Diags,
1309 TokenCache.empty() ? Diagnostic::Error
1310 : Diagnostic::Warning));
Ted Kremenek748d5d62009-03-20 00:26:38 +00001311 }
Ted Kremenek72b1b152009-01-15 18:47:46 +00001312
Ted Kremenek22f0d092009-03-22 06:42:39 +00001313 if (Diags.hasErrorOccurred())
1314 exit(1);
1315
Ted Kremenek72b1b152009-01-15 18:47:46 +00001316 // Create the Preprocessor.
1317 llvm::OwningPtr<Preprocessor> PP(new Preprocessor(Diags, LangInfo, Target,
1318 SourceMgr, HeaderInfo,
1319 PTHMgr.get()));
1320
1321 // Note that this is different then passing PTHMgr to Preprocessor's ctor.
1322 // That argument is used as the IdentifierInfoLookup argument to
1323 // IdentifierTable's ctor.
1324 if (PTHMgr) {
1325 PTHMgr->setPreprocessor(PP.get());
1326 PP->setPTHManager(PTHMgr.take());
1327 }
Douglas Gregor14f79002009-04-10 03:52:48 +00001328
Chris Lattnere116ccf2009-04-21 05:40:52 +00001329 PreprocessorInitOptions InitOpts;
1330 InitializePreprocessorInitOptions(InitOpts);
Eli Friedmanf086e3b2009-05-18 07:39:39 +00001331 if (InitializePreprocessor(*PP, InitOpts))
Douglas Gregore1d918e2009-04-10 23:10:45 +00001332 return 0;
Chris Lattnere116ccf2009-04-21 05:40:52 +00001333
Douglas Gregore1d918e2009-04-10 23:10:45 +00001334 return PP.take();
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001335 }
1336};
1337}
Reid Spencer5f016e22007-07-11 17:01:13 +00001338
Reid Spencer5f016e22007-07-11 17:01:13 +00001339//===----------------------------------------------------------------------===//
1340// Basic Parser driver
1341//===----------------------------------------------------------------------===//
1342
Chris Lattner51574ea2008-04-19 23:25:44 +00001343static void ParseFile(Preprocessor &PP, MinimalAction *PA) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001344 Parser P(PP, *PA);
Ted Kremenek95041a22007-12-19 22:51:13 +00001345 PP.EnterMainSourceFile();
Reid Spencer5f016e22007-07-11 17:01:13 +00001346
1347 // Parsing the specified input file.
1348 P.ParseTranslationUnit();
1349 delete PA;
1350}
1351
1352//===----------------------------------------------------------------------===//
Daniel Dunbar70f92432008-10-23 05:50:47 +00001353// Code generation options
1354//===----------------------------------------------------------------------===//
1355
1356static llvm::cl::opt<bool>
Chris Lattner15104882009-03-09 22:05:03 +00001357GenerateDebugInfo("g",
1358 llvm::cl::desc("Generate source level debug information"));
1359
Daniel Dunbara034ba82009-02-17 19:47:34 +00001360static llvm::cl::opt<std::string>
1361TargetCPU("mcpu",
1362 llvm::cl::desc("Target a specific cpu type (-mcpu=help for details)"));
1363
Daniel Dunbar868bd0a2009-05-06 03:16:41 +00001364static llvm::cl::list<std::string>
1365TargetFeatures("target-feature", llvm::cl::desc("Target specific attributes"));
1366
Devang Patel24095da2009-06-04 23:32:02 +00001367
1368static llvm::cl::opt<bool>
1369DisableRedZone("disable-red-zone",
1370 llvm::cl::desc("Do not emit code that uses the red zone."),
1371 llvm::cl::init(false));
1372
Devang Patelacebb392009-06-05 22:05:48 +00001373static llvm::cl::opt<bool>
1374NoImplicitFloat("no-implicit-float",
1375 llvm::cl::desc("Don't generate implicit floating point instructions (x86-only)"),
1376 llvm::cl::init(false));
1377
Daniel Dunbar868bd0a2009-05-06 03:16:41 +00001378/// ComputeTargetFeatures - Recompute the target feature list to only
1379/// be the list of things that are enabled, based on the target cpu
1380/// and feature list.
1381static void ComputeFeatureMap(TargetInfo *Target,
1382 llvm::StringMap<bool> &Features) {
1383 assert(Features.empty() && "invalid map");
1384
1385 // Initialize the feature map based on the target.
1386 Target->getDefaultFeatures(TargetCPU, Features);
1387
1388 // Apply the user specified deltas.
1389 for (llvm::cl::list<std::string>::iterator it = TargetFeatures.begin(),
1390 ie = TargetFeatures.end(); it != ie; ++it) {
1391 const char *Name = it->c_str();
1392
1393 // FIXME: Don't handle errors like this.
1394 if (Name[0] != '-' && Name[0] != '+') {
1395 fprintf(stderr, "error: clang-cc: invalid target feature string: %s\n",
1396 Name);
1397 exit(1);
1398 }
Daniel Dunbar17ca3632009-05-06 21:07:50 +00001399 if (!Target->setFeatureEnabled(Features, Name + 1, (Name[0] == '+'))) {
1400 fprintf(stderr, "error: clang-cc: invalid target feature name: %s\n",
1401 Name + 1);
Daniel Dunbar868bd0a2009-05-06 03:16:41 +00001402 exit(1);
1403 }
Daniel Dunbar868bd0a2009-05-06 03:16:41 +00001404 }
1405}
1406
Chris Lattner7afae712009-03-16 18:41:18 +00001407static void InitializeCompileOptions(CompileOptions &Opts,
Daniel Dunbar868bd0a2009-05-06 03:16:41 +00001408 const LangOptions &LangOpts,
1409 const llvm::StringMap<bool> &Features) {
Daniel Dunbar70f92432008-10-23 05:50:47 +00001410 Opts.OptimizeSize = OptSize;
Chris Lattner20126042009-03-09 22:00:34 +00001411 Opts.DebugInfo = GenerateDebugInfo;
Daniel Dunbar877db382009-06-02 22:07:45 +00001412
1413 if (DisableLLVMOptimizations) {
1414 Opts.OptimizationLevel = 0;
1415 Opts.Inlining = CompileOptions::NoInlining;
Daniel Dunbarac7ffe02008-10-29 07:56:11 +00001416 } else {
Daniel Dunbar877db382009-06-02 22:07:45 +00001417 if (OptSize) {
1418 // -Os implies -O2
1419 Opts.OptimizationLevel = 2;
1420 } else {
1421 Opts.OptimizationLevel = OptLevel;
1422 }
1423
1424 // We must always run at least the always inlining pass.
1425 if (Opts.OptimizationLevel > 1)
1426 Opts.Inlining = CompileOptions::NormalInlining;
1427 else
1428 Opts.Inlining = CompileOptions::OnlyAlwaysInlining;
Daniel Dunbarac7ffe02008-10-29 07:56:11 +00001429 }
Daniel Dunbar8e8f3b72008-10-29 03:42:18 +00001430
1431 // FIXME: There are llvm-gcc options to control these selectively.
Daniel Dunbar8e8f3b72008-10-29 03:42:18 +00001432 Opts.UnrollLoops = (Opts.OptimizationLevel > 1 && !OptSize);
Chris Lattner7afae712009-03-16 18:41:18 +00001433 Opts.SimplifyLibCalls = !LangOpts.NoBuiltin;
Daniel Dunbardd913e52008-10-31 09:34:21 +00001434
1435#ifdef NDEBUG
1436 Opts.VerifyModule = 0;
1437#endif
Daniel Dunbara034ba82009-02-17 19:47:34 +00001438
1439 Opts.CPU = TargetCPU;
Daniel Dunbar868bd0a2009-05-06 03:16:41 +00001440 Opts.Features.clear();
1441 for (llvm::StringMap<bool>::const_iterator it = Features.begin(),
1442 ie = Features.end(); it != ie; ++it) {
1443 // FIXME: If we are completely confident that we have the right
1444 // set, we only need to pass the minuses.
1445 std::string Name(it->second ? "+" : "-");
1446 Name += it->first();
1447 Opts.Features.push_back(Name);
1448 }
Chris Lattner44502662009-02-18 01:23:44 +00001449
Chris Lattnerbd360642009-03-26 05:00:52 +00001450 Opts.NoCommon = NoCommon | LangOpts.CPlusPlus;
1451
Chris Lattner44502662009-02-18 01:23:44 +00001452 // Handle -ftime-report.
1453 Opts.TimePasses = TimeReport;
Devang Patel24095da2009-06-04 23:32:02 +00001454
1455 Opts.DisableRedZone = DisableRedZone;
Devang Patelacebb392009-06-05 22:05:48 +00001456 Opts.NoImplicitFloat = NoImplicitFloat;
Daniel Dunbar70f92432008-10-23 05:50:47 +00001457}
1458
1459//===----------------------------------------------------------------------===//
Douglas Gregor26df2f02009-04-02 19:05:20 +00001460// Fix-It Options
1461//===----------------------------------------------------------------------===//
1462static llvm::cl::list<ParsedSourceLocation>
1463FixItAtLocations("fixit-at", llvm::cl::value_desc("source-location"),
1464 llvm::cl::desc("Perform Fix-It modifications at the given source location"));
1465
1466//===----------------------------------------------------------------------===//
Eli Friedmanc6d656e2009-05-18 22:39:16 +00001467// ObjC Rewriter Options
1468//===----------------------------------------------------------------------===//
1469static llvm::cl::opt<bool>
1470SilenceRewriteMacroWarning("Wno-rewrite-macros", llvm::cl::init(false),
1471 llvm::cl::desc("Silence ObjC rewriting warnings"));
1472
1473//===----------------------------------------------------------------------===//
Eli Friedman0eeb86e2009-05-19 01:17:04 +00001474// Warning Options
1475//===----------------------------------------------------------------------===//
1476
1477// This gets all -W options, including -Werror, -W[no-]system-headers, etc. The
1478// driver has stripped off -Wa,foo etc. The driver has also translated -W to
1479// -Wextra, so we don't need to worry about it.
1480static llvm::cl::list<std::string>
1481OptWarnings("W", llvm::cl::Prefix, llvm::cl::ValueOptional);
1482
1483static llvm::cl::opt<bool> OptPedantic("pedantic");
1484static llvm::cl::opt<bool> OptPedanticErrors("pedantic-errors");
1485static llvm::cl::opt<bool> OptNoWarnings("w");
1486
1487//===----------------------------------------------------------------------===//
Eli Friedman12d3b1d2009-05-19 03:06:47 +00001488// Preprocessing (-E mode) Options
1489//===----------------------------------------------------------------------===//
1490static llvm::cl::opt<bool>
1491DisableLineMarkers("P", llvm::cl::desc("Disable linemarker output in -E mode"));
1492static llvm::cl::opt<bool>
1493EnableCommentOutput("C", llvm::cl::desc("Enable comment output in -E mode"));
1494static llvm::cl::opt<bool>
1495EnableMacroCommentOutput("CC",
1496 llvm::cl::desc("Enable comment output in -E mode, "
1497 "even from macro expansions"));
1498static llvm::cl::opt<bool>
1499DumpMacros("dM", llvm::cl::desc("Print macro definitions in -E mode instead of"
1500 " normal output"));
1501static llvm::cl::opt<bool>
1502DumpDefines("dD", llvm::cl::desc("Print macro definitions in -E mode in "
1503 "addition to normal output"));
Eli Friedmanb5c8f8b2009-05-19 03:35:57 +00001504
1505//===----------------------------------------------------------------------===//
1506// Dependency file options
1507//===----------------------------------------------------------------------===//
1508static llvm::cl::opt<std::string>
1509DependencyFile("dependency-file",
1510 llvm::cl::desc("Filename (or -) to write dependency output to"));
1511
1512static llvm::cl::opt<bool>
1513DependenciesIncludeSystemHeaders("sys-header-deps",
1514 llvm::cl::desc("Include system headers in dependency output"));
1515
1516static llvm::cl::list<std::string>
1517DependencyTargets("MT",
1518 llvm::cl::desc("Specify target for dependency"));
1519
1520// FIXME: Implement feature
1521static llvm::cl::opt<bool>
1522PhonyDependencyTarget("MP",
1523 llvm::cl::desc("Create phony target for each dependency "
1524 "(other than main file)"));
1525
Eli Friedman12d3b1d2009-05-19 03:06:47 +00001526//===----------------------------------------------------------------------===//
Eli Friedmane71b85f2009-05-19 10:18:02 +00001527// Analysis options
1528//===----------------------------------------------------------------------===//
1529
1530static llvm::cl::list<Analyses>
1531AnalysisList(llvm::cl::desc("Source Code Analysis - Checks and Analyses"),
1532llvm::cl::values(
1533#define ANALYSIS(NAME, CMDFLAG, DESC, SCOPE)\
1534clEnumValN(NAME, CMDFLAG, DESC),
Eli Friedman0ec78fa2009-05-19 21:10:40 +00001535#include "clang/Frontend/Analyses.def"
Eli Friedmane71b85f2009-05-19 10:18:02 +00001536clEnumValEnd));
1537
1538static llvm::cl::opt<AnalysisStores>
1539AnalysisStoreOpt("analyzer-store",
1540 llvm::cl::desc("Source Code Analysis - Abstract Memory Store Models"),
1541 llvm::cl::init(BasicStoreModel),
1542 llvm::cl::values(
1543#define ANALYSIS_STORE(NAME, CMDFLAG, DESC, CREATFN)\
1544clEnumValN(NAME##Model, CMDFLAG, DESC),
Eli Friedman0ec78fa2009-05-19 21:10:40 +00001545#include "clang/Frontend/Analyses.def"
Eli Friedmane71b85f2009-05-19 10:18:02 +00001546clEnumValEnd));
1547
1548static llvm::cl::opt<AnalysisConstraints>
1549AnalysisConstraintsOpt("analyzer-constraints",
1550 llvm::cl::desc("Source Code Analysis - Symbolic Constraint Engines"),
1551 llvm::cl::init(RangeConstraintsModel),
1552 llvm::cl::values(
1553#define ANALYSIS_CONSTRAINTS(NAME, CMDFLAG, DESC, CREATFN)\
1554clEnumValN(NAME##Model, CMDFLAG, DESC),
Eli Friedman0ec78fa2009-05-19 21:10:40 +00001555#include "clang/Frontend/Analyses.def"
Eli Friedmane71b85f2009-05-19 10:18:02 +00001556clEnumValEnd));
1557
1558static llvm::cl::opt<AnalysisDiagClients>
1559AnalysisDiagOpt("analyzer-output",
1560 llvm::cl::desc("Source Code Analysis - Output Options"),
1561 llvm::cl::init(PD_HTML),
1562 llvm::cl::values(
1563#define ANALYSIS_DIAGNOSTICS(NAME, CMDFLAG, DESC, CREATFN, AUTOCREATE)\
1564clEnumValN(PD_##NAME, CMDFLAG, DESC),
Eli Friedman0ec78fa2009-05-19 21:10:40 +00001565#include "clang/Frontend/Analyses.def"
Eli Friedmane71b85f2009-05-19 10:18:02 +00001566clEnumValEnd));
1567
1568static llvm::cl::opt<bool>
1569VisualizeEGDot("analyzer-viz-egraph-graphviz",
1570 llvm::cl::desc("Display exploded graph using GraphViz"));
1571
1572static llvm::cl::opt<bool>
1573VisualizeEGUbi("analyzer-viz-egraph-ubigraph",
1574 llvm::cl::desc("Display exploded graph using Ubigraph"));
1575
1576static llvm::cl::opt<bool>
1577AnalyzeAll("analyzer-opt-analyze-headers",
1578 llvm::cl::desc("Force the static analyzer to analyze "
1579 "functions defined in header files"));
1580
1581static llvm::cl::opt<bool>
1582AnalyzerDisplayProgress("analyzer-display-progress",
1583 llvm::cl::desc("Emit verbose output about the analyzer's progress."));
1584
1585static llvm::cl::opt<bool>
1586PurgeDead("analyzer-purge-dead",
1587 llvm::cl::init(true),
1588 llvm::cl::desc("Remove dead symbols, bindings, and constraints before"
1589 " processing a statement."));
1590
1591static llvm::cl::opt<bool>
1592EagerlyAssume("analyzer-eagerly-assume",
1593 llvm::cl::init(false),
1594 llvm::cl::desc("Eagerly assume the truth/falseness of some "
1595 "symbolic constraints."));
1596
1597static llvm::cl::opt<std::string>
1598AnalyzeSpecificFunction("analyze-function",
1599 llvm::cl::desc("Run analysis on specific function"));
1600
1601static llvm::cl::opt<bool>
1602TrimGraph("trim-egraph",
1603 llvm::cl::desc("Only show error-related paths in the analysis graph"));
1604
1605static AnalyzerOptions ReadAnalyzerOptions() {
1606 AnalyzerOptions Opts;
1607 Opts.AnalysisList = AnalysisList;
1608 Opts.AnalysisStoreOpt = AnalysisStoreOpt;
1609 Opts.AnalysisConstraintsOpt = AnalysisConstraintsOpt;
1610 Opts.AnalysisDiagOpt = AnalysisDiagOpt;
1611 Opts.VisualizeEGDot = VisualizeEGDot;
1612 Opts.VisualizeEGUbi = VisualizeEGUbi;
1613 Opts.AnalyzeAll = AnalyzeAll;
1614 Opts.AnalyzerDisplayProgress = AnalyzerDisplayProgress;
1615 Opts.PurgeDead = PurgeDead;
1616 Opts.EagerlyAssume = EagerlyAssume;
1617 Opts.AnalyzeSpecificFunction = AnalyzeSpecificFunction;
1618 Opts.TrimGraph = TrimGraph;
1619 return Opts;
1620}
1621
1622//===----------------------------------------------------------------------===//
Chris Lattner75a97cb2009-04-17 21:05:01 +00001623// -dump-build-information Stuff
1624//===----------------------------------------------------------------------===//
1625
1626static llvm::cl::opt<std::string>
1627DumpBuildInformation("dump-build-information",
1628 llvm::cl::value_desc("filename"),
1629 llvm::cl::desc("output a dump of some build information to a file"));
1630
1631static llvm::raw_ostream *BuildLogFile = 0;
1632
1633/// LoggingDiagnosticClient - This is a simple diagnostic client that forwards
1634/// all diagnostics to both BuildLogFile and a chained DiagnosticClient.
1635namespace {
1636class LoggingDiagnosticClient : public DiagnosticClient {
1637 llvm::OwningPtr<DiagnosticClient> Chain1;
1638 llvm::OwningPtr<DiagnosticClient> Chain2;
1639public:
1640
1641 LoggingDiagnosticClient(DiagnosticClient *Normal) {
1642 // Output diags both where requested...
1643 Chain1.reset(Normal);
1644 // .. and to our log file.
1645 Chain2.reset(new TextDiagnosticPrinter(*BuildLogFile,
1646 !NoShowColumn,
1647 !NoCaretDiagnostics,
1648 !NoShowLocation,
1649 PrintSourceRangeInfo,
Chris Lattneraa5bf2e2009-04-19 07:44:08 +00001650 PrintDiagnosticOption,
Douglas Gregorfffd93f2009-05-01 21:53:04 +00001651 !NoDiagnosticsFixIt,
Nate Begeman4e3629e2009-06-25 22:43:10 +00001652 MessageLength));
Chris Lattner75a97cb2009-04-17 21:05:01 +00001653 }
1654
1655 virtual void setLangOptions(const LangOptions *LO) {
1656 Chain1->setLangOptions(LO);
1657 Chain2->setLangOptions(LO);
1658 }
1659
1660 virtual bool IncludeInDiagnosticCounts() const {
1661 return Chain1->IncludeInDiagnosticCounts();
1662 }
1663
1664 virtual void HandleDiagnostic(Diagnostic::Level DiagLevel,
1665 const DiagnosticInfo &Info) {
1666 Chain1->HandleDiagnostic(DiagLevel, Info);
1667 Chain2->HandleDiagnostic(DiagLevel, Info);
1668 }
1669};
1670} // end anonymous namespace.
1671
1672static void SetUpBuildDumpLog(unsigned argc, char **argv,
1673 llvm::OwningPtr<DiagnosticClient> &DiagClient) {
1674
1675 std::string ErrorInfo;
1676 BuildLogFile = new llvm::raw_fd_ostream(DumpBuildInformation.c_str(), false,
1677 ErrorInfo);
1678
1679 if (!ErrorInfo.empty()) {
1680 llvm::errs() << "error opening -dump-build-information file '"
1681 << DumpBuildInformation << "', option ignored!\n";
1682 delete BuildLogFile;
1683 BuildLogFile = 0;
1684 DumpBuildInformation = "";
1685 return;
1686 }
1687
1688 (*BuildLogFile) << "clang-cc command line arguments: ";
1689 for (unsigned i = 0; i != argc; ++i)
1690 (*BuildLogFile) << argv[i] << ' ';
1691 (*BuildLogFile) << '\n';
1692
1693 // LoggingDiagnosticClient - Insert a new logging diagnostic client in between
1694 // the diagnostic producers and the normal receiver.
1695 DiagClient.reset(new LoggingDiagnosticClient(DiagClient.take()));
1696}
1697
1698
1699
1700//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +00001701// Main driver
1702//===----------------------------------------------------------------------===//
1703
Eli Friedman66d6f042009-05-18 22:20:00 +00001704static llvm::raw_ostream* ComputeOutFile(const std::string& InFile,
1705 const char* Extension,
1706 bool Binary,
1707 llvm::sys::Path& OutPath) {
1708 llvm::raw_ostream* Ret;
1709 bool UseStdout = false;
1710 std::string OutFile;
1711 if (OutputFile == "-" || (OutputFile.empty() && InFile == "-")) {
1712 UseStdout = true;
1713 } else if (!OutputFile.empty()) {
1714 OutFile = OutputFile;
1715 } else if (Extension) {
1716 llvm::sys::Path Path(InFile);
1717 Path.eraseSuffix();
1718 Path.appendSuffix(Extension);
1719 OutFile = Path.toString();
1720 } else {
1721 UseStdout = true;
Chris Lattner8a5c8092009-02-18 01:20:05 +00001722 }
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +00001723
Eli Friedman66d6f042009-05-18 22:20:00 +00001724 if (UseStdout) {
1725 Ret = new llvm::raw_stdout_ostream();
1726 if (Binary)
1727 llvm::sys::Program::ChangeStdoutToBinary();
1728 } else {
1729 std::string Error;
1730 Ret = new llvm::raw_fd_ostream(OutFile.c_str(), Binary, Error);
1731 if (!Error.empty()) {
1732 // FIXME: Don't fail this way.
1733 llvm::cerr << "ERROR: " << Error << "\n";
1734 ::exit(1);
1735 }
1736 OutPath = OutFile;
Ted Kremenekdb094a22007-12-05 18:27:04 +00001737 }
Eli Friedman66d6f042009-05-18 22:20:00 +00001738
1739 return Ret;
Ted Kremenekdb094a22007-12-05 18:27:04 +00001740}
1741
Reid Spencer5f016e22007-07-11 17:01:13 +00001742/// ProcessInputFile - Process a single input file with the specified state.
1743///
Ted Kremenek339b9c22008-04-17 22:31:54 +00001744static void ProcessInputFile(Preprocessor &PP, PreprocessorFactory &PPF,
Daniel Dunbar868bd0a2009-05-06 03:16:41 +00001745 const std::string &InFile, ProgActions PA,
1746 const llvm::StringMap<bool> &Features) {
Eli Friedman66d6f042009-05-18 22:20:00 +00001747 llvm::OwningPtr<llvm::raw_ostream> OS;
Ted Kremenek7e7e6252008-08-08 02:46:37 +00001748 llvm::OwningPtr<ASTConsumer> Consumer;
Chris Lattnerbd247762007-07-22 06:05:44 +00001749 bool ClearSourceMgr = false;
Douglas Gregor558cb562009-04-02 01:08:08 +00001750 FixItRewriter *FixItRewrite = 0;
Douglas Gregorf807fe02009-04-14 16:27:31 +00001751 bool CompleteTranslationUnit = true;
Eli Friedman66d6f042009-05-18 22:20:00 +00001752 llvm::sys::Path OutPath;
Douglas Gregor558cb562009-04-02 01:08:08 +00001753
Ted Kremenek85888962008-10-21 00:54:44 +00001754 switch (PA) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001755 default:
Eli Friedman66d6f042009-05-18 22:20:00 +00001756 fprintf(stderr, "Unexpected program action!\n");
1757 HadErrors = true;
1758 return;
1759
1760 case ASTPrint:
1761 OS.reset(ComputeOutFile(InFile, 0, false, OutPath));
1762 Consumer.reset(CreateASTPrinter(OS.get()));
1763 break;
Ted Kremenekdb094a22007-12-05 18:27:04 +00001764
Douglas Gregoree75c052009-05-21 20:55:50 +00001765 case ASTPrintXML:
1766 OS.reset(ComputeOutFile(InFile, "xml", false, OutPath));
1767 Consumer.reset(CreateASTPrinterXML(OS.get()));
1768 break;
1769
Eli Friedman66d6f042009-05-18 22:20:00 +00001770 case ASTDump:
Douglas Gregor4fe0c8e2009-05-30 00:08:05 +00001771 Consumer.reset(CreateASTDumper());
Eli Friedman66d6f042009-05-18 22:20:00 +00001772 break;
1773
Eli Friedman66d6f042009-05-18 22:20:00 +00001774 case ASTView:
Douglas Gregor4fe0c8e2009-05-30 00:08:05 +00001775 Consumer.reset(CreateASTViewer());
Eli Friedman66d6f042009-05-18 22:20:00 +00001776 break;
1777
1778 case PrintDeclContext:
1779 Consumer.reset(CreateDeclContextPrinter());
1780 break;
1781
1782 case EmitHTML:
1783 OS.reset(ComputeOutFile(InFile, 0, true, OutPath));
1784 Consumer.reset(CreateHTMLPrinter(OS.get(), PP.getDiagnostics(), &PP, &PPF));
1785 break;
1786
1787 case InheritanceView:
1788 Consumer.reset(CreateInheritanceViewer(InheritanceViewCls));
1789 break;
1790
1791 case EmitAssembly:
1792 case EmitLLVM:
1793 case EmitBC:
1794 case EmitLLVMOnly: {
1795 BackendAction Act;
1796 if (ProgAction == EmitAssembly) {
1797 Act = Backend_EmitAssembly;
1798 OS.reset(ComputeOutFile(InFile, "s", true, OutPath));
1799 } else if (ProgAction == EmitLLVM) {
1800 Act = Backend_EmitLL;
1801 OS.reset(ComputeOutFile(InFile, "ll", true, OutPath));
1802 } else if (ProgAction == EmitLLVMOnly) {
1803 Act = Backend_EmitNothing;
1804 } else {
1805 Act = Backend_EmitBC;
1806 OS.reset(ComputeOutFile(InFile, "bc", true, OutPath));
Ted Kremenekdb094a22007-12-05 18:27:04 +00001807 }
Ted Kremenekfdfc1982007-12-19 22:24:34 +00001808
Eli Friedman66d6f042009-05-18 22:20:00 +00001809 CompileOptions Opts;
1810 InitializeCompileOptions(Opts, PP.getLangOptions(), Features);
1811 Consumer.reset(CreateBackendConsumer(Act, PP.getDiagnostics(),
1812 PP.getLangOptions(), Opts, InFile,
1813 OS.get()));
Ted Kremenekdb094a22007-12-05 18:27:04 +00001814 break;
Eli Friedman66d6f042009-05-18 22:20:00 +00001815 }
1816
1817 case GeneratePCH:
1818 OS.reset(ComputeOutFile(InFile, 0, true, OutPath));
1819 Consumer.reset(CreatePCHGenerator(PP, OS.get()));
1820 CompleteTranslationUnit = false;
1821 break;
1822
1823 case RewriteObjC:
1824 OS.reset(ComputeOutFile(InFile, "cpp", true, OutPath));
Eli Friedmanbce831b2009-05-18 22:29:17 +00001825 Consumer.reset(CreateObjCRewriter(InFile, OS.get(), PP.getDiagnostics(),
Eli Friedmanc6d656e2009-05-18 22:39:16 +00001826 PP.getLangOptions(),
1827 SilenceRewriteMacroWarning));
Eli Friedman66d6f042009-05-18 22:20:00 +00001828 break;
1829
1830 case RewriteBlocks:
1831 Consumer.reset(CreateBlockRewriter(InFile, PP.getDiagnostics(),
1832 PP.getLangOptions()));
1833 break;
1834
Eli Friedmane71b85f2009-05-19 10:18:02 +00001835 case RunAnalysis: {
Eli Friedman66d6f042009-05-18 22:20:00 +00001836 Consumer.reset(CreateAnalysisConsumer(PP.getDiagnostics(), &PP, &PPF,
Eli Friedmane71b85f2009-05-19 10:18:02 +00001837 PP.getLangOptions(), OutputFile,
1838 ReadAnalyzerOptions()));
Eli Friedman66d6f042009-05-18 22:20:00 +00001839 break;
Eli Friedmane71b85f2009-05-19 10:18:02 +00001840 }
Eli Friedman66d6f042009-05-18 22:20:00 +00001841
Chris Lattnerc106c102008-10-12 05:03:36 +00001842 case DumpRawTokens: {
Chris Lattner47099742009-02-18 01:51:21 +00001843 llvm::TimeRegion Timer(ClangFrontendTimer);
Chris Lattnerc106c102008-10-12 05:03:36 +00001844 SourceManager &SM = PP.getSourceManager();
Chris Lattnerc106c102008-10-12 05:03:36 +00001845 // Start lexing the specified input file.
Chris Lattner025c3a62009-01-17 07:35:14 +00001846 Lexer RawLex(SM.getMainFileID(), SM, PP.getLangOptions());
Chris Lattnerc106c102008-10-12 05:03:36 +00001847 RawLex.SetKeepWhitespaceMode(true);
1848
1849 Token RawTok;
Chris Lattnerc106c102008-10-12 05:03:36 +00001850 RawLex.LexFromRawLexer(RawTok);
1851 while (RawTok.isNot(tok::eof)) {
1852 PP.DumpToken(RawTok, true);
1853 fprintf(stderr, "\n");
1854 RawLex.LexFromRawLexer(RawTok);
1855 }
1856 ClearSourceMgr = true;
1857 break;
1858 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001859 case DumpTokens: { // Token dump mode.
Chris Lattner47099742009-02-18 01:51:21 +00001860 llvm::TimeRegion Timer(ClangFrontendTimer);
Chris Lattnerd2177732007-07-20 16:59:19 +00001861 Token Tok;
Chris Lattnerc106c102008-10-12 05:03:36 +00001862 // Start preprocessing the specified input file.
Ted Kremenek95041a22007-12-19 22:51:13 +00001863 PP.EnterMainSourceFile();
Reid Spencer5f016e22007-07-11 17:01:13 +00001864 do {
1865 PP.Lex(Tok);
1866 PP.DumpToken(Tok, true);
1867 fprintf(stderr, "\n");
Chris Lattner057aaf62007-10-09 18:03:42 +00001868 } while (Tok.isNot(tok::eof));
Chris Lattnerbd247762007-07-22 06:05:44 +00001869 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001870 break;
1871 }
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001872 case RunPreprocessorOnly:
Reid Spencer5f016e22007-07-11 17:01:13 +00001873 break;
Ted Kremenek85888962008-10-21 00:54:44 +00001874
Douglas Gregorbf1bd6e2009-04-02 23:43:50 +00001875 case GeneratePTH: {
Chris Lattner47099742009-02-18 01:51:21 +00001876 llvm::TimeRegion Timer(ClangFrontendTimer);
Eli Friedmanf54fce82009-05-19 01:02:07 +00001877 if (OutputFile.empty() || OutputFile == "-") {
1878 // FIXME: Don't fail this way.
1879 // FIXME: Verify that we can actually seek in the given file.
1880 llvm::cerr << "ERROR: PTH requires an seekable file for output!\n";
1881 ::exit(1);
1882 }
1883 OS.reset(ComputeOutFile(InFile, 0, true, OutPath));
1884 CacheTokens(PP, static_cast<llvm::raw_fd_ostream*>(OS.get()));
Ted Kremenek85888962008-10-21 00:54:44 +00001885 ClearSourceMgr = true;
1886 break;
1887 }
Douglas Gregor6ab35242009-04-09 21:40:53 +00001888
Chris Lattnercc7dea82009-04-27 22:02:30 +00001889 case PrintPreprocessedInput:
Eli Friedmanf54fce82009-05-19 01:02:07 +00001890 OS.reset(ComputeOutFile(InFile, 0, true, OutPath));
Reid Spencer5f016e22007-07-11 17:01:13 +00001891 break;
Chris Lattnerb57e3d42008-05-08 06:52:13 +00001892
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001893 case ParseNoop:
Reid Spencer5f016e22007-07-11 17:01:13 +00001894 break;
1895
Chris Lattner47099742009-02-18 01:51:21 +00001896 case ParsePrintCallbacks: {
1897 llvm::TimeRegion Timer(ClangFrontendTimer);
Eli Friedmanf54fce82009-05-19 01:02:07 +00001898 OS.reset(ComputeOutFile(InFile, 0, true, OutPath));
1899 ParseFile(PP, CreatePrintParserActionsAction(PP, OS.get()));
Chris Lattnerbd247762007-07-22 06:05:44 +00001900 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001901 break;
Chris Lattner47099742009-02-18 01:51:21 +00001902 }
1903
1904 case ParseSyntaxOnly: { // -fsyntax-only
1905 llvm::TimeRegion Timer(ClangFrontendTimer);
Ted Kremenek7e7e6252008-08-08 02:46:37 +00001906 Consumer.reset(new ASTConsumer());
Ted Kremenek2bf55142007-09-17 20:49:30 +00001907 break;
Chris Lattner47099742009-02-18 01:51:21 +00001908 }
Chris Lattnerb57e3d42008-05-08 06:52:13 +00001909
1910 case RewriteMacros:
Eli Friedmanf54fce82009-05-19 01:02:07 +00001911 OS.reset(ComputeOutFile(InFile, 0, true, OutPath));
1912 RewriteMacrosInInput(PP, OS.get());
Chris Lattnerb57e3d42008-05-08 06:52:13 +00001913 ClearSourceMgr = true;
1914 break;
Chris Lattnerb13c5ee2008-10-12 05:29:20 +00001915
Eli Friedmanf54fce82009-05-19 01:02:07 +00001916 case RewriteTest:
1917 OS.reset(ComputeOutFile(InFile, 0, true, OutPath));
1918 DoRewriteTest(PP, OS.get());
Chris Lattnerb13c5ee2008-10-12 05:29:20 +00001919 ClearSourceMgr = true;
1920 break;
Douglas Gregor558cb562009-04-02 01:08:08 +00001921
1922 case FixIt:
1923 llvm::TimeRegion Timer(ClangFrontendTimer);
1924 Consumer.reset(new ASTConsumer());
Douglas Gregorde4bf6a2009-04-02 17:13:00 +00001925 FixItRewrite = new FixItRewriter(PP.getDiagnostics(),
Chris Lattner2c78b872009-04-14 23:22:57 +00001926 PP.getSourceManager(),
1927 PP.getLangOptions());
Douglas Gregor558cb562009-04-02 01:08:08 +00001928 break;
Chris Lattner47099742009-02-18 01:51:21 +00001929 }
Ted Kremenek46157b52009-01-28 04:29:29 +00001930
Chris Lattner1aee61a2009-04-27 21:25:27 +00001931 if (FixItAtLocations.size() > 0) {
1932 // Even without the "-fixit" flag, with may have some specific
1933 // locations where the user has requested fixes. Process those
1934 // locations now.
1935 if (!FixItRewrite)
1936 FixItRewrite = new FixItRewriter(PP.getDiagnostics(),
1937 PP.getSourceManager(),
1938 PP.getLangOptions());
Chris Lattner9ecd26a2009-03-28 01:37:17 +00001939
Chris Lattner1aee61a2009-04-27 21:25:27 +00001940 bool AddedFixitLocation = false;
1941 for (unsigned Idx = 0, Last = FixItAtLocations.size();
1942 Idx != Last; ++Idx) {
1943 RequestedSourceLocation Requested;
Argyrios Kyrtzidis34d25d82009-06-23 22:01:39 +00001944 if (ResolveParsedLocation(FixItAtLocations[Idx],
1945 PP.getFileManager(), Requested)) {
Chris Lattner1aee61a2009-04-27 21:25:27 +00001946 fprintf(stderr, "FIX-IT could not find file \"%s\"\n",
1947 FixItAtLocations[Idx].FileName.c_str());
1948 } else {
1949 FixItRewrite->addFixItLocation(Requested);
1950 AddedFixitLocation = true;
Douglas Gregor26df2f02009-04-02 19:05:20 +00001951 }
1952 }
1953
Chris Lattner1aee61a2009-04-27 21:25:27 +00001954 if (!AddedFixitLocation) {
1955 // All of the fix-it locations were bad. Don't fix anything.
1956 delete FixItRewrite;
1957 FixItRewrite = 0;
1958 }
1959 }
1960
1961 llvm::OwningPtr<ASTContext> ContextOwner;
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001962 if (Consumer)
Chris Lattner9ecd26a2009-03-28 01:37:17 +00001963 ContextOwner.reset(new ASTContext(PP.getLangOptions(),
1964 PP.getSourceManager(),
1965 PP.getTargetInfo(),
1966 PP.getIdentifierTable(),
1967 PP.getSelectorTable(),
Chris Lattner1b63e4f2009-06-14 01:54:56 +00001968 PP.getBuiltinInfo(),
Douglas Gregor2deaea32009-04-22 18:49:13 +00001969 /* FreeMemory = */ !DisableFree,
Chris Lattner1b63e4f2009-06-14 01:54:56 +00001970 /* size_reserve = */0));
1971
Chris Lattnercc7dea82009-04-27 22:02:30 +00001972 llvm::OwningPtr<PCHReader> Reader;
1973 llvm::OwningPtr<ExternalASTSource> Source;
1974
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001975 if (!ImplicitIncludePCH.empty()) {
Chris Lattnercc7dea82009-04-27 22:02:30 +00001976 Reader.reset(new PCHReader(PP, ContextOwner.get()));
1977
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001978 // The user has asked us to include a precompiled header. Load
1979 // the precompiled header into the AST context.
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001980 switch (Reader->ReadPCH(ImplicitIncludePCH)) {
1981 case PCHReader::Success: {
Douglas Gregore721f952009-04-28 18:58:38 +00001982 // Set the predefines buffer as suggested by the PCH
1983 // reader. Typically, the predefines buffer will be empty.
1984 PP.setPredefines(Reader->getSuggestedPredefines());
1985
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001986 // Attach the PCH reader to the AST context as an external AST
1987 // source, so that declarations will be deserialized from the
1988 // PCH file as needed.
Chris Lattnercc7dea82009-04-27 22:02:30 +00001989 if (ContextOwner) {
1990 Source.reset(Reader.take());
Douglas Gregore1d918e2009-04-10 23:10:45 +00001991 ContextOwner->setExternalSource(Source);
Chris Lattnercc7dea82009-04-27 22:02:30 +00001992 }
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001993 break;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001994 }
1995
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001996 case PCHReader::Failure:
1997 // Unrecoverable failure: don't even try to process the input
1998 // file.
1999 return;
2000
2001 case PCHReader::IgnorePCH:
Douglas Gregor1ab86ac2009-04-28 22:01:16 +00002002 // No suitable PCH file could be found. Return an error.
2003 return;
2004
2005#if 0
2006 // FIXME: We can recover from failed attempts to load PCH
2007 // files. This code will do so, if we ever want to enable it.
2008
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002009 // We delayed the initialization of builtins in the hope of
2010 // loading the PCH file. Since the PCH file could not be
2011 // loaded, initialize builtins now.
2012 if (ContextOwner)
2013 ContextOwner->InitializeBuiltins(PP.getIdentifierTable());
Douglas Gregor1ab86ac2009-04-28 22:01:16 +00002014#endif
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002015 }
2016
2017 // Finish preprocessor initialization. We do this now (rather
2018 // than earlier) because this initialization creates new source
2019 // location entries in the source manager, which must come after
2020 // the source location entries for the PCH file.
2021 if (InitializeSourceManager(PP, InFile))
2022 return;
Ted Kremenek46157b52009-01-28 04:29:29 +00002023 }
Daniel Dunbar879c3ea2008-10-27 22:03:52 +00002024
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002025
2026 // If we have an ASTConsumer, run the parser with it.
2027 if (Consumer)
2028 ParseAST(PP, Consumer.get(), *ContextOwner.get(), Stats,
2029 CompleteTranslationUnit);
2030
2031 if (PA == RunPreprocessorOnly) { // Just lex as fast as we can, no output.
2032 llvm::TimeRegion Timer(ClangFrontendTimer);
2033 Token Tok;
2034 // Start parsing the specified input file.
2035 PP.EnterMainSourceFile();
2036 do {
2037 PP.Lex(Tok);
2038 } while (Tok.isNot(tok::eof));
2039 ClearSourceMgr = true;
2040 } else if (PA == ParseNoop) { // -parse-noop
2041 llvm::TimeRegion Timer(ClangFrontendTimer);
2042 ParseFile(PP, new MinimalAction(PP));
2043 ClearSourceMgr = true;
Chris Lattnercc7dea82009-04-27 22:02:30 +00002044 } else if (PA == PrintPreprocessedInput){ // -E mode.
2045 llvm::TimeRegion Timer(ClangFrontendTimer);
Eli Friedman12d3b1d2009-05-19 03:06:47 +00002046 if (DumpMacros)
2047 DoPrintMacros(PP, OS.get());
2048 else
2049 DoPrintPreprocessedInput(PP, OS.get(), EnableCommentOutput,
2050 EnableMacroCommentOutput,
2051 DisableLineMarkers, DumpDefines);
Chris Lattnercc7dea82009-04-27 22:02:30 +00002052 ClearSourceMgr = true;
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002053 }
2054
Chris Lattner1aee61a2009-04-27 21:25:27 +00002055 if (FixItRewrite)
2056 FixItRewrite->WriteFixedFile(InFile, OutputFile);
2057
2058 // If in -disable-free mode, don't deallocate ASTContext.
2059 if (DisableFree)
2060 ContextOwner.take();
2061 else
2062 ContextOwner.reset(); // Delete ASTContext
Eli Friedman66d6f042009-05-18 22:20:00 +00002063
Daniel Dunbar879c3ea2008-10-27 22:03:52 +00002064 if (VerifyDiagnostics)
Daniel Dunbar276373d2008-10-27 22:10:13 +00002065 if (CheckDiagnostics(PP))
2066 exit(1);
Chris Lattnere66b65c2008-02-06 01:42:25 +00002067
Reid Spencer5f016e22007-07-11 17:01:13 +00002068 if (Stats) {
Ted Kremenekfdfc1982007-12-19 22:24:34 +00002069 fprintf(stderr, "\nSTATISTICS FOR '%s':\n", InFile.c_str());
Reid Spencer5f016e22007-07-11 17:01:13 +00002070 PP.PrintStats();
2071 PP.getIdentifierTable().PrintStats();
Chris Lattnerdee73592007-12-15 20:48:40 +00002072 PP.getHeaderSearchInfo().PrintStats();
Ted Kremenek1b95a652009-01-09 18:20:21 +00002073 PP.getSourceManager().PrintStats();
Reid Spencer5f016e22007-07-11 17:01:13 +00002074 fprintf(stderr, "\n");
2075 }
Chris Lattnerbd247762007-07-22 06:05:44 +00002076
2077 // For a multi-file compilation, some things are ok with nuking the source
2078 // manager tables, other require stable fileid/macroid's across multiple
2079 // files.
Chris Lattnerdee73592007-12-15 20:48:40 +00002080 if (ClearSourceMgr)
2081 PP.getSourceManager().clearIDTables();
Daniel Dunbard68ba0e2008-11-11 06:35:39 +00002082
2083 if (DisableFree)
2084 Consumer.take();
Eli Friedman66d6f042009-05-18 22:20:00 +00002085 else
2086 Consumer.reset();
2087
2088 // Always delete the output stream because we don't want to leak file
2089 // handles. Also, we don't want to try to erase an open file.
2090 OS.reset();
2091
2092 if ((HadErrors || (PP.getDiagnostics().getNumErrors() != 0)) &&
2093 !OutPath.isEmpty()) {
2094 // If we had errors, try to erase the output file.
2095 OutPath.eraseFromDisk();
2096 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002097}
2098
2099static llvm::cl::list<std::string>
2100InputFilenames(llvm::cl::Positional, llvm::cl::desc("<input files>"));
2101
Reid Spencer5f016e22007-07-11 17:01:13 +00002102int main(int argc, char **argv) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002103 llvm::sys::PrintStackTraceOnErrorSignal();
Chris Lattner09e94a32009-03-04 21:41:39 +00002104 llvm::PrettyStackTraceProgram X(argc, argv);
Chris Lattnerdc763102009-03-06 05:38:04 +00002105 llvm::cl::ParseCommandLineOptions(argc, argv,
Chris Lattner110e4782009-03-06 05:38:25 +00002106 "LLVM 'Clang' Compiler: http://clang.llvm.org\n");
Daniel Dunbar08e6dc62009-05-28 16:37:33 +00002107
Chris Lattner2fe11942009-06-17 17:25:50 +00002108 llvm::InitializeAllTargets();
2109 llvm::InitializeAllAsmPrinters();
2110
Chris Lattner47099742009-02-18 01:51:21 +00002111 if (TimeReport)
2112 ClangFrontendTimer = new llvm::Timer("Clang front-end time");
2113
Daniel Dunbar08e6dc62009-05-28 16:37:33 +00002114 if (Verbose)
2115 fprintf(stderr, "clang-cc version 1.0 based upon " PACKAGE_STRING
2116 " hosted on " LLVM_HOSTTRIPLE "\n");
2117
Reid Spencer5f016e22007-07-11 17:01:13 +00002118 // If no input was specified, read from stdin.
2119 if (InputFilenames.empty())
2120 InputFilenames.push_back("-");
Douglas Gregor68a0d782009-05-02 00:03:46 +00002121
Ted Kremenek31e703b2007-12-11 23:28:38 +00002122 // Create the diagnostic client for reporting errors or for
2123 // implementing -verify.
Chris Lattner409d4e72009-04-17 20:40:01 +00002124 llvm::OwningPtr<DiagnosticClient> DiagClient;
2125 if (VerifyDiagnostics) {
2126 // When checking diagnostics, just buffer them up.
2127 DiagClient.reset(new TextDiagnosticBuffer());
2128 if (InputFilenames.size() != 1) {
2129 fprintf(stderr, "-verify only works on single input files for now.\n");
2130 return 1;
2131 }
2132 if (!HTMLDiag.empty()) {
2133 fprintf(stderr, "-verify and -html-diags don't work together\n");
2134 return 1;
2135 }
2136 } else if (HTMLDiag.empty()) {
Ted Kremenekb4398aa2008-08-07 17:49:57 +00002137 // Print diagnostics to stderr by default.
Douglas Gregor68a0d782009-05-02 00:03:46 +00002138
2139 // If -fmessage-length=N was not specified, determine whether this
2140 // is a terminal and, if so, implicitly define -fmessage-length
2141 // appropriately.
2142 if (MessageLength.getNumOccurrences() == 0)
Douglas Gregor67187ce2009-05-11 18:06:49 +00002143 MessageLength.setValue(llvm::sys::Process::StandardErrColumns());
Douglas Gregor68a0d782009-05-02 00:03:46 +00002144
Torok Edwin603fca72009-06-04 07:18:23 +00002145 if (!NoColorDiagnostic) {
2146 NoColorDiagnostic.setValue(!llvm::sys::Process::StandardErrHasColors());
2147 }
2148
Chris Lattner409d4e72009-04-17 20:40:01 +00002149 DiagClient.reset(new TextDiagnosticPrinter(llvm::errs(),
Chris Lattnera03a5b52008-11-19 06:56:25 +00002150 !NoShowColumn,
Chris Lattner65f5e642009-01-30 19:01:41 +00002151 !NoCaretDiagnostics,
Chris Lattner1fbee5d2009-03-13 01:08:23 +00002152 !NoShowLocation,
Chris Lattnerd51d74a2009-04-16 05:44:38 +00002153 PrintSourceRangeInfo,
Chris Lattneraa5bf2e2009-04-19 07:44:08 +00002154 PrintDiagnosticOption,
Douglas Gregorfffd93f2009-05-01 21:53:04 +00002155 !NoDiagnosticsFixIt,
Torok Edwin603fca72009-06-04 07:18:23 +00002156 MessageLength,
2157 !NoColorDiagnostic));
Ted Kremenekb4398aa2008-08-07 17:49:57 +00002158 } else {
Chris Lattner409d4e72009-04-17 20:40:01 +00002159 DiagClient.reset(CreateHTMLDiagnosticClient(HTMLDiag));
Reid Spencer5f016e22007-07-11 17:01:13 +00002160 }
Chris Lattner75a97cb2009-04-17 21:05:01 +00002161
2162 if (!DumpBuildInformation.empty()) {
2163 if (!HTMLDiag.empty()) {
2164 fprintf(stderr,
2165 "-dump-build-information and -html-diags don't work together\n");
2166 return 1;
2167 }
2168
2169 SetUpBuildDumpLog(argc, argv, DiagClient);
2170 }
2171
Ted Kremenekb4398aa2008-08-07 17:49:57 +00002172
Reid Spencer5f016e22007-07-11 17:01:13 +00002173 // Configure our handling of diagnostics.
Ted Kremenekb4398aa2008-08-07 17:49:57 +00002174 Diagnostic Diags(DiagClient.get());
Eli Friedman0eeb86e2009-05-19 01:17:04 +00002175 if (ProcessWarningOptions(Diags, OptWarnings, OptPedantic, OptPedanticErrors,
2176 OptNoWarnings))
Sebastian Redl63a9e0f2009-03-06 17:41:35 +00002177 return 1;
Ted Kremenek31e703b2007-12-11 23:28:38 +00002178
Chris Lattner4f037832007-12-05 23:24:17 +00002179 // -I- is a deprecated GCC feature, scan for it and reject it.
2180 for (unsigned i = 0, e = I_dirs.size(); i != e; ++i) {
2181 if (I_dirs[i] == "-") {
Chris Lattner5917fe12008-11-18 05:05:28 +00002182 Diags.Report(FullSourceLoc(), diag::err_pp_I_dash_not_supported);
Chris Lattner4f037832007-12-05 23:24:17 +00002183 I_dirs.erase(I_dirs.begin()+i);
2184 --i;
2185 }
2186 }
Chris Lattner11215192008-03-14 06:12:05 +00002187
2188 // Get information about the target being compiled for.
2189 std::string Triple = CreateTargetTriple();
Ted Kremenek7a08e282008-08-07 18:13:12 +00002190 llvm::OwningPtr<TargetInfo> Target(TargetInfo::CreateTargetInfo(Triple));
2191
Chris Lattner11215192008-03-14 06:12:05 +00002192 if (Target == 0) {
Daniel Dunbar50f4f462009-03-12 10:14:16 +00002193 Diags.Report(FullSourceLoc(), diag::err_fe_unknown_triple)
2194 << Triple.c_str();
Sebastian Redlc5613db2009-03-07 12:09:25 +00002195 return 1;
Chris Lattner11215192008-03-14 06:12:05 +00002196 }
Chris Lattner4f037832007-12-05 23:24:17 +00002197
Daniel Dunbard4270232009-01-20 23:17:32 +00002198 if (!InheritanceViewCls.empty()) // C++ visualization?
Ted Kremenek7cae2f62008-10-23 23:36:29 +00002199 ProgAction = InheritanceView;
Ted Kremenekb4398aa2008-08-07 17:49:57 +00002200
Ted Kremenekc0c03bc2008-06-06 22:42:39 +00002201 llvm::OwningPtr<SourceManager> SourceMgr;
2202
Chris Lattner2c78b872009-04-14 23:22:57 +00002203 // Create a file manager object to provide access to and cache the filesystem.
2204 FileManager FileMgr;
Douglas Gregor4fed3f42009-04-27 18:38:38 +00002205
Daniel Dunbar868bd0a2009-05-06 03:16:41 +00002206 // Compute the feature set, unfortunately this effects the language!
2207 llvm::StringMap<bool> Features;
2208 ComputeFeatureMap(Target.get(), Features);
2209
Reid Spencer5f016e22007-07-11 17:01:13 +00002210 for (unsigned i = 0, e = InputFilenames.size(); i != e; ++i) {
Ted Kremenek31e703b2007-12-11 23:28:38 +00002211 const std::string &InFile = InputFilenames[i];
Ted Kremenek31e703b2007-12-11 23:28:38 +00002212
Chris Lattnerf63aea32009-03-04 21:40:56 +00002213 /// Create a SourceManager object. This tracks and owns all the file
2214 /// buffers allocated to a translation unit.
2215 if (!SourceMgr)
2216 SourceMgr.reset(new SourceManager());
2217 else
2218 SourceMgr->clearIDTables();
2219
2220 // Initialize language options, inferring file types from input filenames.
2221 LangOptions LangInfo;
Chris Lattner409d4e72009-04-17 20:40:01 +00002222 DiagClient->setLangOptions(&LangInfo);
Chris Lattner2c78b872009-04-14 23:22:57 +00002223
Chris Lattnerf63aea32009-03-04 21:40:56 +00002224 InitializeBaseLanguage();
2225 LangKind LK = GetLanguage(InFile);
Daniel Dunbar0b5b0da2009-04-01 05:09:09 +00002226 InitializeLangOptions(LangInfo, LK);
Daniel Dunbar868bd0a2009-05-06 03:16:41 +00002227 InitializeLanguageStandard(LangInfo, LK, Target.get(), Features);
Chris Lattnerf63aea32009-03-04 21:40:56 +00002228
2229 // Process the -I options and set them in the HeaderInfo.
2230 HeaderSearch HeaderInfo(FileMgr);
2231
Chris Lattner2c78b872009-04-14 23:22:57 +00002232
Chris Lattnerf63aea32009-03-04 21:40:56 +00002233 InitializeIncludePaths(argv[0], HeaderInfo, FileMgr, LangInfo);
2234
2235 // Set up the preprocessor with these options.
Eli Friedmanf086e3b2009-05-18 07:39:39 +00002236 DriverPreprocessorFactory PPFactory(Diags, LangInfo, *Target,
Chris Lattnerf63aea32009-03-04 21:40:56 +00002237 *SourceMgr.get(), HeaderInfo);
2238
2239 llvm::OwningPtr<Preprocessor> PP(PPFactory.CreatePreprocessor());
2240
2241 if (!PP)
2242 continue;
Ted Kremenekb4398aa2008-08-07 17:49:57 +00002243
Eli Friedmanb5c8f8b2009-05-19 03:35:57 +00002244 // Handle generating dependencies, if requested
2245 if (!DependencyFile.empty()) {
2246 llvm::raw_ostream *DependencyOS;
2247 if (DependencyTargets.empty()) {
2248 // FIXME: Use a proper diagnostic
2249 llvm::cerr << "-dependency-file requires at least one -MT option\n";
2250 HadErrors = true;
2251 continue;
2252 }
2253 std::string ErrStr;
2254 DependencyOS =
2255 new llvm::raw_fd_ostream(DependencyFile.c_str(), false, ErrStr);
2256 if (!ErrStr.empty()) {
2257 // FIXME: Use a proper diagnostic
2258 llvm::cerr << "unable to open dependency file: " + ErrStr;
2259 HadErrors = true;
2260 continue;
2261 }
2262
2263 AttachDependencyFileGen(PP.get(), DependencyOS, DependencyTargets,
2264 DependenciesIncludeSystemHeaders,
2265 PhonyDependencyTarget);
2266 }
2267
Chris Lattner1b63e4f2009-06-14 01:54:56 +00002268 if (ImplicitIncludePCH.empty()) {
2269 if (InitializeSourceManager(*PP.get(), InFile))
2270 continue;
2271
2272 // Initialize builtin info.
2273 PP->getBuiltinInfo().InitializeBuiltins(PP->getIdentifierTable(),
Chris Lattner1b63e4f2009-06-14 01:54:56 +00002274 PP->getLangOptions().NoBuiltin);
2275 }
Douglas Gregor14f79002009-04-10 03:52:48 +00002276
Chris Lattner409d4e72009-04-17 20:40:01 +00002277 if (!HTMLDiag.empty())
2278 ((PathDiagnosticClient*)DiagClient.get())->SetPreprocessor(PP.get());
Chris Lattnerf63aea32009-03-04 21:40:56 +00002279
2280 // Process the source file.
Daniel Dunbar868bd0a2009-05-06 03:16:41 +00002281 ProcessInputFile(*PP, PPFactory, InFile, ProgAction, Features);
Chris Lattnerf63aea32009-03-04 21:40:56 +00002282
Chris Lattner40469652009-04-17 20:16:08 +00002283 HeaderInfo.ClearFileInfo();
Chris Lattner409d4e72009-04-17 20:40:01 +00002284 DiagClient->setLangOptions(0);
Reid Spencer5f016e22007-07-11 17:01:13 +00002285 }
Chris Lattner11215192008-03-14 06:12:05 +00002286
Mike Stumpfc0fed32009-04-28 01:19:10 +00002287 if (!NoCaretDiagnostics)
2288 if (unsigned NumDiagnostics = Diags.getNumDiagnostics())
2289 fprintf(stderr, "%d diagnostic%s generated.\n", NumDiagnostics,
2290 (NumDiagnostics == 1 ? "" : "s"));
Reid Spencer5f016e22007-07-11 17:01:13 +00002291
2292 if (Stats) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002293 FileMgr.PrintStats();
2294 fprintf(stderr, "\n");
2295 }
Chris Lattner75a97cb2009-04-17 21:05:01 +00002296
2297 delete ClangFrontendTimer;
2298 delete BuildLogFile;
Reid Spencer5f016e22007-07-11 17:01:13 +00002299
Daniel Dunbar276373d2008-10-27 22:10:13 +00002300 // If verifying diagnostics and we reached here, all is well.
2301 if (VerifyDiagnostics)
2302 return 0;
Chris Lattner47099742009-02-18 01:51:21 +00002303
Daniel Dunbar524b86f2008-10-28 00:38:08 +00002304 // Managed static deconstruction. Useful for making things like
2305 // -time-passes usable.
2306 llvm::llvm_shutdown();
2307
Daniel Dunbarb0adbba2008-10-04 23:42:49 +00002308 return HadErrors || (Diags.getNumErrors() != 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00002309}