blob: a1efe0101d7053ec42fcb5c4c7ee89e4404e441b [file] [log] [blame]
Chris Lattner4b009652007-07-25 00:24:17 +00001//===--- clang.cpp - C-Language Front-end ---------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner959e5be2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner4b009652007-07-25 00:24:17 +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 Lattner39fb14e2009-02-18 01:17:01 +000020// -Wfatal-errors
Chris Lattner4b009652007-07-25 00:24:17 +000021// -ftabstop=width
22//
23//===----------------------------------------------------------------------===//
24
Eli Friedman7efefa52009-05-19 21:10:40 +000025#include "clang/Frontend/AnalysisConsumer.h"
Eli Friedmanbc821a42009-05-18 23:02:01 +000026#include "clang/Frontend/ASTConsumers.h"
Daniel Dunbar68952de2009-03-02 06:16:29 +000027#include "clang/Frontend/CompileOptions.h"
Douglas Gregor133d2552009-04-02 01:08:08 +000028#include "clang/Frontend/FixItRewriter.h"
Daniel Dunbarf45afe62009-03-12 10:14:16 +000029#include "clang/Frontend/FrontendDiagnostic.h"
Daniel Dunbar68952de2009-03-02 06:16:29 +000030#include "clang/Frontend/InitHeaderSearch.h"
Chris Lattner94269d72009-04-21 05:40:52 +000031#include "clang/Frontend/InitPreprocessor.h"
Daniel Dunbarf45afe62009-03-12 10:14:16 +000032#include "clang/Frontend/PathDiagnosticClients.h"
Douglas Gregorc34897d2009-04-09 22:27:44 +000033#include "clang/Frontend/PCHReader.h"
Daniel Dunbar68952de2009-03-02 06:16:29 +000034#include "clang/Frontend/TextDiagnosticBuffer.h"
35#include "clang/Frontend/TextDiagnosticPrinter.h"
Argiris Kirtzidiseab61812009-06-23 22:01:39 +000036#include "clang/Frontend/CommandLineSourceLoc.h"
Eli Friedman7e1d6372009-05-19 04:14:29 +000037#include "clang/Frontend/Utils.h"
Ted Kremenekfd75e312008-03-27 06:17:42 +000038#include "clang/Analysis/PathDiagnostic.h"
Chris Lattnerf5e9db02008-02-06 02:01:47 +000039#include "clang/CodeGen/ModuleBuilder.h"
Chris Lattner0bed6ec2008-02-06 00:23:21 +000040#include "clang/Sema/ParseAST.h"
Chris Lattner86a24842009-01-29 06:55:46 +000041#include "clang/Sema/SemaDiagnostic.h"
Chris Lattner1cc01712007-09-15 22:56:56 +000042#include "clang/AST/ASTConsumer.h"
Chris Lattnerfc318192009-03-28 04:31:31 +000043#include "clang/AST/ASTContext.h"
44#include "clang/AST/Decl.h"
Chris Lattnera17991f2009-03-29 16:50:03 +000045#include "clang/AST/DeclGroup.h"
Chris Lattner4b009652007-07-25 00:24:17 +000046#include "clang/Parse/Parser.h"
47#include "clang/Lex/HeaderSearch.h"
Chris Lattner71af6d62009-02-06 04:16:41 +000048#include "clang/Lex/LexDiagnostic.h"
Chris Lattner4b009652007-07-25 00:24:17 +000049#include "clang/Basic/FileManager.h"
50#include "clang/Basic/SourceManager.h"
51#include "clang/Basic/TargetInfo.h"
Daniel Dunbarae81a792009-05-06 04:07:06 +000052#include "clang/Basic/Version.h"
Chris Lattner01de9c82008-09-30 20:16:56 +000053#include "llvm/ADT/OwningPtr.h"
Chris Lattnerac139d22007-12-15 23:20:07 +000054#include "llvm/ADT/SmallPtrSet.h"
Chris Lattner01de9c82008-09-30 20:16:56 +000055#include "llvm/ADT/StringExtras.h"
Daniel Dunbar07181d72009-05-06 03:16:41 +000056#include "llvm/ADT/StringMap.h"
Chris Lattner0e004a12009-04-08 18:24:34 +000057#include "llvm/ADT/STLExtras.h"
Chris Lattner01de9c82008-09-30 20:16:56 +000058#include "llvm/Config/config.h"
Chris Lattner4b009652007-07-25 00:24:17 +000059#include "llvm/Support/CommandLine.h"
Daniel Dunbarbb298c02008-10-28 00:38:08 +000060#include "llvm/Support/ManagedStatic.h"
Chris Lattner4b009652007-07-25 00:24:17 +000061#include "llvm/Support/MemoryBuffer.h"
Zhongxing Xuf4ec4d92008-11-26 05:23:17 +000062#include "llvm/Support/PluginLoader.h"
Chris Lattner2b2d0c42009-03-04 21:41:39 +000063#include "llvm/Support/PrettyStackTrace.h"
Eli Friedmana9c310842009-05-18 22:20:00 +000064#include "llvm/Support/Streams.h"
Chris Lattnerefe33382009-02-18 01:51:21 +000065#include "llvm/Support/Timer.h"
Daniel Dunbarabe2e542008-10-02 01:21:33 +000066#include "llvm/System/Host.h"
Chris Lattner3ee4a2f2008-03-03 03:16:03 +000067#include "llvm/System/Path.h"
Douglas Gregor3dd11e82009-05-03 03:52:38 +000068#include "llvm/System/Process.h"
Eli Friedmana9c310842009-05-18 22:20:00 +000069#include "llvm/System/Program.h"
Chris Lattner01de9c82008-09-30 20:16:56 +000070#include "llvm/System/Signals.h"
Chris Lattner4d495682009-06-17 17:25:50 +000071#include "llvm/Target/TargetSelect.h"
Douglas Gregor24b48b02009-04-02 19:05:20 +000072#include <cstdlib>
Douglas Gregor3dd11e82009-05-03 03:52:38 +000073#if HAVE_SYS_TYPES_H
Douglas Gregor965a13c2009-05-02 00:03:46 +000074# include <sys/types.h>
75#endif
Douglas Gregor24b48b02009-04-02 19:05:20 +000076
Chris Lattner4b009652007-07-25 00:24:17 +000077using namespace clang;
78
79//===----------------------------------------------------------------------===//
Douglas Gregor24b48b02009-04-02 19:05:20 +000080// Source Location Parser
81//===----------------------------------------------------------------------===//
82
Argiris Kirtzidiseab61812009-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 Gregor24b48b02009-04-02 19:05:20 +000087 if (!File)
88 return true;
89
90 Result.File = File;
Argiris Kirtzidiseab61812009-06-23 22:01:39 +000091 Result.Line = ParsedLoc.Line;
92 Result.Column = ParsedLoc.Column;
Douglas Gregor24b48b02009-04-02 19:05:20 +000093 return false;
94}
95
Douglas Gregor24b48b02009-04-02 19:05:20 +000096//===----------------------------------------------------------------------===//
Chris Lattner4b009652007-07-25 00:24:17 +000097// Global options.
98//===----------------------------------------------------------------------===//
99
Chris Lattnerefe33382009-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 Dunbar4efedde2008-10-16 16:54:18 +0000105static bool HadErrors = false;
Daniel Dunbar70a66b12008-10-04 23:42:49 +0000106
Chris Lattner4b009652007-07-25 00:24:17 +0000107static llvm::cl::opt<bool>
108Verbose("v", llvm::cl::desc("Enable verbose output"));
109static llvm::cl::opt<bool>
Nate Begeman6acbedd2007-12-30 01:38:50 +0000110Stats("print-stats",
111 llvm::cl::desc("Print performance metrics and statistics"));
Daniel Dunbar4efedde2008-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 Dunbarbb56def2009-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"));
Chris Lattner4b009652007-07-25 00:24:17 +0000119
120enum ProgActions {
Steve Naroff44e81222008-04-14 22:03:09 +0000121 RewriteObjC, // ObjC->C Rewriter.
Steve Naroff93c18352008-09-18 14:10:13 +0000122 RewriteBlocks, // ObjC->C Rewriter for Blocks.
Chris Lattner1665a9f2008-05-08 06:52:13 +0000123 RewriteMacros, // Expand macros but not #includes.
Chris Lattnerc3fbf392008-10-12 05:29:20 +0000124 RewriteTest, // Rewriter playground
Douglas Gregor133d2552009-04-02 01:08:08 +0000125 FixIt, // Fix-It Rewriter
Ted Kremeneke1a79d82008-03-19 07:53:42 +0000126 HTMLTest, // HTML displayer testing stuff.
Daniel Dunbar85e44e22008-10-21 23:49:24 +0000127 EmitAssembly, // Emit a .s file.
Chris Lattner4b009652007-07-25 00:24:17 +0000128 EmitLLVM, // Emit a .ll file.
Seo Sanghyeon550a1eb2007-12-24 01:52:34 +0000129 EmitBC, // Emit a .bc file.
Daniel Dunbard999a8e2009-02-26 22:39:37 +0000130 EmitLLVMOnly, // Generate LLVM IR, but do not
Ted Kremenek24612ae2008-03-18 21:19:49 +0000131 EmitHTML, // Translate input source into HTML.
Chris Lattner4045a8a2007-10-11 00:18:28 +0000132 ASTPrint, // Parse ASTs and print them.
Douglas Gregor8987c032009-05-21 20:55:50 +0000133 ASTPrintXML, // Parse ASTs and print them in XML.
Chris Lattner4045a8a2007-10-11 00:18:28 +0000134 ASTDump, // Parse ASTs and dump them.
135 ASTView, // Parse ASTs and view them in Graphviz.
Zhongxing Xu6036bbe2009-01-13 01:29:24 +0000136 PrintDeclContext, // Print DeclContext and their Decls.
Chris Lattner4b009652007-07-25 00:24:17 +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 Lattneraf669fb2008-10-12 05:03:36 +0000142 DumpTokens, // Dump out preprocessed tokens.
143 DumpRawTokens, // Dump out raw tokens.
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000144 RunAnalysis, // Run one or more source code analyses.
Douglas Gregor2a0e8742009-04-02 23:43:50 +0000145 GeneratePTH, // Generate pre-tokenized header.
Douglas Gregorc34897d2009-04-09 22:27:44 +0000146 GeneratePCH, // Generate pre-compiled header.
Ted Kremenekd9ceb3d2008-10-23 23:36:29 +0000147 InheritanceView // View C++ inheritance for a specified class.
Chris Lattner4b009652007-07-25 00:24:17 +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 Lattneraf669fb2008-10-12 05:03:36 +0000158 clEnumValN(DumpRawTokens, "dump-raw-tokens",
159 "Lex file in raw mode and dump raw tokens"),
Daniel Dunbar9c321102009-01-20 23:17:32 +0000160 clEnumValN(RunAnalysis, "analyze",
161 "Run static analysis engine"),
Chris Lattneraf669fb2008-10-12 05:03:36 +0000162 clEnumValN(DumpTokens, "dump-tokens",
Chris Lattner4b009652007-07-25 00:24:17 +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 Kremenek24612ae2008-03-18 21:19:49 +0000170 clEnumValN(EmitHTML, "emit-html",
171 "Output input source as HTML"),
Chris Lattner4045a8a2007-10-11 00:18:28 +0000172 clEnumValN(ASTPrint, "ast-print",
173 "Build ASTs and then pretty-print them"),
Douglas Gregor8987c032009-05-21 20:55:50 +0000174 clEnumValN(ASTPrintXML, "ast-print-xml",
175 "Build ASTs and then print them in XML format"),
Chris Lattner4045a8a2007-10-11 00:18:28 +0000176 clEnumValN(ASTDump, "ast-dump",
177 "Build ASTs and then debug dump them"),
Chris Lattner664dd082007-10-11 00:37:43 +0000178 clEnumValN(ASTView, "ast-view",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000179 "Build ASTs and view them with GraphViz"),
Zhongxing Xu6036bbe2009-01-13 01:29:24 +0000180 clEnumValN(PrintDeclContext, "print-decl-contexts",
Ted Kremenek4787dcf2009-04-01 00:23:28 +0000181 "Print DeclContexts and their Decls"),
Douglas Gregor2a0e8742009-04-02 23:43:50 +0000182 clEnumValN(GeneratePTH, "emit-pth",
Ted Kremenek4787dcf2009-04-01 00:23:28 +0000183 "Generate pre-tokenized header file"),
Douglas Gregorc34897d2009-04-09 22:27:44 +0000184 clEnumValN(GeneratePCH, "emit-pch",
185 "Generate pre-compiled header file"),
Daniel Dunbar85e44e22008-10-21 23:49:24 +0000186 clEnumValN(EmitAssembly, "S",
187 "Emit native assembly code"),
Chris Lattner4b009652007-07-25 00:24:17 +0000188 clEnumValN(EmitLLVM, "emit-llvm",
Ted Kremenek05334682007-09-06 21:26:58 +0000189 "Build ASTs then convert to LLVM, emit .ll file"),
Seo Sanghyeon550a1eb2007-12-24 01:52:34 +0000190 clEnumValN(EmitBC, "emit-llvm-bc",
191 "Build ASTs then convert to LLVM, emit .bc file"),
Daniel Dunbard999a8e2009-02-26 22:39:37 +0000192 clEnumValN(EmitLLVMOnly, "emit-llvm-only",
193 "Build ASTs and convert to LLVM, discarding output"),
Chris Lattnerc3fbf392008-10-12 05:29:20 +0000194 clEnumValN(RewriteTest, "rewrite-test",
195 "Rewriter playground"),
Steve Naroff44e81222008-04-14 22:03:09 +0000196 clEnumValN(RewriteObjC, "rewrite-objc",
Chris Lattner1665a9f2008-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 Naroff93c18352008-09-18 14:10:13 +0000200 clEnumValN(RewriteBlocks, "rewrite-blocks",
201 "Rewrite Blocks to C"),
Douglas Gregor133d2552009-04-02 01:08:08 +0000202 clEnumValN(FixIt, "fixit",
203 "Apply fix-it advice to the input source"),
Chris Lattner4b009652007-07-25 00:24:17 +0000204 clEnumValEnd));
205
Ted Kremenekd01eae62007-12-19 19:47:59 +0000206
207static llvm::cl::opt<std::string>
208OutputFile("o",
Ted Kremenek09b3f0d2007-12-19 19:50:41 +0000209 llvm::cl::value_desc("path"),
Douglas Gregor608ff622009-04-22 21:45:53 +0000210 llvm::cl::desc("Specify output file"));
Ted Kremenek517cb512008-04-14 18:40:58 +0000211
Ted Kremenek57f25b22008-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 Gupta40e56a12008-05-08 08:54:20 +0000221//===----------------------------------------------------------------------===//
Ted Kremenek517cb512008-04-14 18:40:58 +0000222// Diagnostic Options
223//===----------------------------------------------------------------------===//
224
Ted Kremenek10389cf2007-09-26 19:42:19 +0000225static llvm::cl::opt<bool>
226VerifyDiagnostics("verify",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000227 llvm::cl::desc("Verify emitted diagnostics and warnings"));
Ted Kremenek10389cf2007-09-26 19:42:19 +0000228
Ted Kremenekfd75e312008-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 Weber0e13eaa2008-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 Lattnerb96a04f2009-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 Weber0e13eaa2008-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 Lattner695a4f52009-03-13 01:08:23 +0000248static llvm::cl::opt<bool>
Chris Lattner041bd732009-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 Lattner13bac9e2009-04-21 05:34:31 +0000254PrintSourceRangeInfo("fdiagnostics-print-source-range-info",
255 llvm::cl::desc("Print source range spans in numeric form"));
256
Chris Lattnera96ec3b2009-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 Weber0e13eaa2008-08-05 23:33:20 +0000260
Douglas Gregora4eb3e72009-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
Edwin Törökeff37122009-06-04 07:18:23 +0000267static llvm::cl::opt<bool>
Edwin Törökcca1e502009-06-04 07:27:53 +0000268NoColorDiagnostic("fno-color-diagnostics",
Edwin Törökeff37122009-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)."));
Chris Lattner4b009652007-07-25 00:24:17 +0000272//===----------------------------------------------------------------------===//
Ted Kremenekd9ceb3d2008-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 Dunbar47f0b0f2009-01-14 18:56:36 +0000279 llvm::cl::desc("View C++ inheritance for a specified class"));
Ted Kremenekd9ceb3d2008-10-23 23:36:29 +0000280
281//===----------------------------------------------------------------------===//
Douglas Gregor23d23262009-02-14 20:49:29 +0000282// Builtin Options
283//===----------------------------------------------------------------------===//
Chris Lattner93d4d982009-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 Gregor23d23262009-02-14 20:49:29 +0000290static llvm::cl::opt<bool>
291Freestanding("ffreestanding",
Daniel Dunbarfd46ea22009-02-16 22:43:43 +0000292 llvm::cl::desc("Assert that the compilation takes place in a "
Douglas Gregor23d23262009-02-14 20:49:29 +0000293 "freestanding environment"));
294
Daniel Dunbarfd46ea22009-02-16 22:43:43 +0000295static llvm::cl::opt<bool>
Daniel Dunbar9d805ce2009-04-07 21:16:11 +0000296AllowBuiltins("fbuiltin", llvm::cl::init(true),
297 llvm::cl::desc("Disable implicit builtin knowledge of functions"));
Chris Lattner911b8672009-03-13 22:38:49 +0000298
299
300static llvm::cl::opt<bool>
Daniel Dunbar9d805ce2009-04-07 21:16:11 +0000301MathErrno("fmath-errno", llvm::cl::init(true),
302 llvm::cl::desc("Require math functions to respect errno"));
Daniel Dunbarfd46ea22009-02-16 22:43:43 +0000303
Douglas Gregor23d23262009-02-14 20:49:29 +0000304//===----------------------------------------------------------------------===//
Chris Lattner4b009652007-07-25 00:24:17 +0000305// Language Options
306//===----------------------------------------------------------------------===//
307
308enum LangKind {
309 langkind_unspecified,
310 langkind_c,
311 langkind_c_cpp,
Chris Lattnera19689a2008-10-22 17:29:21 +0000312 langkind_asm_cpp,
Chris Lattner4b009652007-07-25 00:24:17 +0000313 langkind_cxx,
314 langkind_cxx_cpp,
315 langkind_objc,
316 langkind_objc_cpp,
317 langkind_objcxx,
Nate Begeman006f78a2009-06-25 22:43:10 +0000318 langkind_objcxx_cpp,
319 langkind_ocl
Chris Lattner4b009652007-07-25 00:24:17 +0000320};
321
Chris Lattner4b009652007-07-25 00:24:17 +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 Begeman006f78a2009-06-25 22:43:10 +0000326 clEnumValN(langkind_ocl, "cl", "OpenCL C"),
Chris Lattner4b009652007-07-25 00:24:17 +0000327 clEnumValN(langkind_cxx, "c++", "C++"),
328 clEnumValN(langkind_objc, "objective-c", "Objective C"),
329 clEnumValN(langkind_objcxx,"objective-c++","Objective C++"),
Daniel Dunbarb1488592009-01-29 23:50:47 +0000330 clEnumValN(langkind_c_cpp, "cpp-output",
Chris Lattner4b009652007-07-25 00:24:17 +0000331 "Preprocessed C"),
Chris Lattnera19689a2008-10-22 17:29:21 +0000332 clEnumValN(langkind_asm_cpp, "assembler-with-cpp",
333 "Preprocessed asm"),
Chris Lattner4b009652007-07-25 00:24:17 +0000334 clEnumValN(langkind_cxx_cpp, "c++-cpp-output",
Chris Lattnerb5555ea2009-02-06 06:19:20 +0000335 "Preprocessed C++"),
Chris Lattner4b009652007-07-25 00:24:17 +0000336 clEnumValN(langkind_objc_cpp, "objective-c-cpp-output",
337 "Preprocessed Objective C"),
Chris Lattnerb5555ea2009-02-06 06:19:20 +0000338 clEnumValN(langkind_objcxx_cpp, "objective-c++-cpp-output",
Chris Lattner4b009652007-07-25 00:24:17 +0000339 "Preprocessed Objective C++"),
Daniel Dunbardb6126e2009-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"),
Chris Lattner4b009652007-07-25 00:24:17 +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 Lattnere1be6022009-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 Jahanian2ccf6172009-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 Lattnere1be6022009-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 Jahanianfefd5e82009-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 Lattnere1be6022009-04-14 23:22:57 +0000391
Ted Kremenek11ad8952007-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 Lattner4eac0502008-01-04 19:12:28 +0000408 return langkind_c;
Chris Lattner4b009652007-07-25 00:24:17 +0000409 }
410
Ted Kremenek11ad8952007-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 Lattner5dc0c1b2009-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 Lattnera19689a2008-10-22 17:29:21 +0000421 return langkind_asm_cpp;
Ted Kremenek11ad8952007-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 Begeman006f78a2009-06-25 22:43:10 +0000437 else if (Ext == "cl")
438 return langkind_ocl;
Ted Kremenek11ad8952007-12-05 23:49:08 +0000439 else
440 return langkind_c;
441}
442
443
Ted Kremenek71c6cc62008-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 Dunbardb6126e2009-04-01 05:09:09 +0000453static void InitializeLangOptions(LangOptions &Options, LangKind LK){
Chris Lattner4b009652007-07-25 00:24:17 +0000454 // FIXME: implement -fpreprocessed mode.
455 bool NoPreprocess = false;
456
Ted Kremenek11ad8952007-12-05 23:49:08 +0000457 switch (LK) {
Chris Lattner4b009652007-07-25 00:24:17 +0000458 default: assert(0 && "Unknown language kind!");
Chris Lattnera19689a2008-10-22 17:29:21 +0000459 case langkind_asm_cpp:
Daniel Dunbar20b88022008-12-01 18:55:22 +0000460 Options.AsmPreprocessor = 1;
Chris Lattnera19689a2008-10-22 17:29:21 +0000461 // FALLTHROUGH
Chris Lattner4b009652007-07-25 00:24:17 +0000462 case langkind_c_cpp:
463 NoPreprocess = true;
464 // FALLTHROUGH
465 case langkind_c:
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000466 InitializeCOptions(Options);
Chris Lattner4b009652007-07-25 00:24:17 +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 Kremenek71c6cc62008-10-21 00:54:44 +0000478 InitializeObjCOptions(Options);
Chris Lattner4b009652007-07-25 00:24:17 +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 Begeman006f78a2009-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;
Chris Lattner4b009652007-07-25 00:24:17 +0000493 }
Chris Lattnere1be6022009-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 Jahanian2ccf6172009-04-17 03:04:15 +0000500 if (ObjCEnableGCBitmapPrint)
501 Options.ObjCGCBitmapPrint = 1;
502
Chris Lattnere1be6022009-04-14 23:22:57 +0000503 Options.setVisibilityMode(SymbolVisibility);
504 Options.OverflowChecking = OverflowChecking;
Chris Lattner4b009652007-07-25 00:24:17 +0000505}
506
507/// LangStds - Language standards we support.
508enum LangStds {
509 lang_unspecified,
510 lang_c89, lang_c94, lang_c99,
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000511 lang_gnu_START,
512 lang_gnu89 = lang_gnu_START, lang_gnu99,
Chris Lattner4b009652007-07-25 00:24:17 +0000513 lang_cxx98, lang_gnucxx98,
514 lang_cxx0x, lang_gnucxx0x
515};
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 Lattnerddeb7402009-04-06 17:17:55 +0000526 clEnumValN(lang_c99, "c9x", "ISO C 1999"),
Chris Lattner4b009652007-07-25 00:24:17 +0000527 clEnumValN(lang_c99, "iso9899:1999", "ISO C 1999"),
Chris Lattnerddeb7402009-04-06 17:17:55 +0000528 clEnumValN(lang_c99, "iso9899:199x", "ISO C 1999"),
Chris Lattner4b009652007-07-25 00:24:17 +0000529 clEnumValN(lang_gnu89, "gnu89",
Gabor Greifbe1618a2009-02-28 09:22:15 +0000530 "ISO C 1990 with GNU extensions"),
Chris Lattner4b009652007-07-25 00:24:17 +0000531 clEnumValN(lang_gnu99, "gnu99",
Gabor Greifbe1618a2009-02-28 09:22:15 +0000532 "ISO C 1999 with GNU extensions (default for C)"),
Chris Lattner4b009652007-07-25 00:24:17 +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++)"),
540 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 Greif46612282009-03-11 23:07:18 +0000544 "extensions"),
Chris Lattner4b009652007-07-25 00:24:17 +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 Carlsson55bfe0d2007-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 Naroff73a07032008-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 Gupta69683532008-05-08 08:28:14 +0000560 "Microsoft header files "));
Chris Lattnerdb6be562007-11-28 05:34:05 +0000561
562static llvm::cl::opt<bool>
563WritableStrings("fwritable-strings",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000564 llvm::cl::desc("Store string literals as writable data"));
Anders Carlssone87cd982007-11-30 04:21:22 +0000565
566static llvm::cl::opt<bool>
Anders Carlsson6cf61c92009-01-30 23:26:40 +0000567NoLaxVectorConversions("fno-lax-vector-conversions",
Anders Carlsson355ed052009-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 Lattnerd7bc88b2008-12-04 23:20:07 +0000571
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000572static llvm::cl::opt<bool>
Daniel Dunbar9d805ce2009-04-07 21:16:11 +0000573EnableBlocks("fblocks", llvm::cl::desc("enable the 'blocks' language feature"));
Mike Stump9093c742009-02-02 22:57:57 +0000574
575static llvm::cl::opt<bool>
Chris Lattner1e3eedb2009-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 Stump9093c742009-02-02 22:57:57 +0000581ObjCNonFragileABI("fobjc-nonfragile-abi",
582 llvm::cl::desc("enable objective-c's nonfragile abi"));
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000583
Daniel Dunbar5523e862009-05-04 05:16:21 +0000584
585static llvm::cl::opt<bool>
Daniel Dunbar9bae8652009-02-04 21:19:06 +0000586EmitAllDecls("femit-all-decls",
587 llvm::cl::desc("Emit all declarations, even if unused"));
Ted Kremenek2658c4a2008-04-29 04:37:03 +0000588
Daniel Dunbar91692d92008-08-11 17:36:14 +0000589static llvm::cl::opt<bool>
590Exceptions("fexceptions",
Chris Lattner77c04832009-04-19 07:00:02 +0000591 llvm::cl::desc("Enable support for exception handling"));
Daniel Dunbar91692d92008-08-11 17:36:14 +0000592
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000593static llvm::cl::opt<bool>
594GNURuntime("fgnu-runtime",
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000595 llvm::cl::desc("Generate output compatible with the standard GNU "
Chris Lattner77c04832009-04-19 07:00:02 +0000596 "Objective-C runtime"));
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000597
598static llvm::cl::opt<bool>
599NeXTRuntime("fnext-runtime",
Ted Kremenek71c6cc62008-10-21 00:54:44 +0000600 llvm::cl::desc("Generate output compatible with the NeXT "
Chris Lattner77c04832009-04-19 07:00:02 +0000601 "runtime"));
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000602
Eli Friedman449eb692009-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 Kremenek88bec0f2008-09-03 21:22:16 +0000606
607
608static llvm::cl::opt<bool>
Chris Lattner77c04832009-04-19 07:00:02 +0000609Trigraphs("trigraphs", llvm::cl::desc("Process trigraph sequences"));
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000610
Douglas Gregor375733c2009-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 Lattner77c04832009-04-19 07:00:02 +0000615static llvm::cl::opt<bool>
616DollarsInIdents("fdollars-in-identifiers",
617 llvm::cl::desc("Allow '$' in identifiers"));
Chris Lattner738d3f62009-03-02 22:11:07 +0000618
Anders Carlssondfd77642009-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 Dunbard27b66b2009-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 Carlssondfd77642009-04-06 17:37:10 +0000628NoCommon("fno-common",
629 llvm::cl::desc("Compile common globals like normal definitions"),
630 llvm::cl::ValueDisallowed);
631
Daniel Dunbardedc94c2009-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 Carlssondfd77642009-04-06 17:37:10 +0000635
Anders Carlssonf2310142009-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 Carlssondfd77642009-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 Carlssondfd77642009-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 Dunbare079c712009-04-08 03:03:23 +0000657static llvm::cl::opt<unsigned>
Daniel Dunbarcdd3c762009-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 Dunbare079c712009-04-08 03:03:23 +0000662
Bill Wendlinge1d4f5d2009-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 Dunbar34542952008-08-23 08:43:39 +0000668static void InitializeLanguageStandard(LangOptions &Options, LangKind LK,
Daniel Dunbar07181d72009-05-06 03:16:41 +0000669 TargetInfo *Target,
670 const llvm::StringMap<bool> &Features) {
Chris Lattnerddae7102008-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 Dunbar07181d72009-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 Lattner738d3f62009-03-02 22:11:07 +0000677
Chris Lattner4b009652007-07-25 00:24:17 +0000678 if (LangStd == lang_unspecified) {
679 // Based on the base language, pick one.
Ted Kremenek11ad8952007-12-05 23:49:08 +0000680 switch (LK) {
Ted Kremenek9bd34312009-03-19 19:02:20 +0000681 case lang_unspecified: assert(0 && "Unknown base language");
Nate Begeman006f78a2009-06-25 22:43:10 +0000682 case langkind_ocl:
683 LangStd = lang_c99;
684 break;
Chris Lattner4b009652007-07-25 00:24:17 +0000685 case langkind_c:
Chris Lattnera19689a2008-10-22 17:29:21 +0000686 case langkind_asm_cpp:
Chris Lattner4b009652007-07-25 00:24:17 +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.
706 case lang_gnucxx0x:
707 case lang_cxx0x:
708 Options.CPlusPlus0x = 1;
709 // FALL THROUGH
710 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:
Chris Lattner4b009652007-07-25 00:24:17 +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 Lattner0297c762008-02-25 04:01:39 +0000724 Options.Digraphs = 1; // C94, C99, C++.
725 // FALL THROUGH.
Chris Lattner4b009652007-07-25 00:24:17 +0000726 case lang_c89:
727 break;
728 }
Argiris Kirtzidisb1519552008-09-11 04:21:06 +0000729
Chris Lattner31e7f6f2009-03-20 15:44:26 +0000730 // GNUMode - Set if we're in gnu99, gnu89, gnucxx98, etc.
731 Options.GNUMode = LangStd >= lang_gnu_START;
732
Argiris Kirtzidisb1519552008-09-11 04:21:06 +0000733 if (Options.CPlusPlus) {
734 Options.C99 = 0;
Chris Lattner31e7f6f2009-03-20 15:44:26 +0000735 Options.HexFloats = Options.GNUMode;
Argiris Kirtzidisb1519552008-09-11 04:21:06 +0000736 }
Chris Lattner4b009652007-07-25 00:24:17 +0000737
Chris Lattner6ab935b2008-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 Kremenek88bec0f2008-09-03 21:22:16 +0000742
Daniel Dunbarfacf3512009-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 Lattner31e7f6f2009-03-20 15:44:26 +0000745 Options.Trigraphs = !Options.GNUMode;
Chris Lattner58d5ba52008-12-05 00:10:44 +0000746 if (Trigraphs.getPosition())
Chris Lattner31e7f6f2009-03-20 15:44:26 +0000747 Options.Trigraphs = Trigraphs; // Command line option wins if specified.
Ted Kremenek88bec0f2008-09-03 21:22:16 +0000748
Chris Lattner58d5ba52008-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 Carlsson8ffcf732009-01-21 18:47:36 +0000752 // However, blocks are not turned off when compiling Obj-C or Obj-C++ code.
Chris Lattner31e7f6f2009-03-20 15:44:26 +0000753 if (!Options.ObjC1 && !Options.GNUMode)
Chris Lattner58d5ba52008-12-05 00:10:44 +0000754 Options.Blocks = 0;
755
Chris Lattner284784c2009-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 Lattner77c04832009-04-19 07:00:02 +0000761 Options.DollarIdents = DollarsInIdents;
762
Chris Lattnerd7bc88b2008-12-04 23:20:07 +0000763 if (PascalStrings.getPosition())
764 Options.PascalStrings = PascalStrings;
Eli Friedman6b6ca942009-06-08 06:11:14 +0000765 if (MSExtensions.getPosition())
766 Options.Microsoft = MSExtensions;
Chris Lattnerdb6be562007-11-28 05:34:05 +0000767 Options.WritableStrings = WritableStrings;
Anders Carlsson355ed052009-01-30 23:17:46 +0000768 if (NoLaxVectorConversions.getPosition())
769 Options.LaxVectorConversions = 0;
Daniel Dunbar91692d92008-08-11 17:36:14 +0000770 Options.Exceptions = Exceptions;
Mike Stump9093c742009-02-02 22:57:57 +0000771 if (EnableBlocks.getPosition())
Chris Lattnerd7bc88b2008-12-04 23:20:07 +0000772 Options.Blocks = EnableBlocks;
Eli Friedman449eb692009-06-05 07:12:17 +0000773 if (CharIsSigned.getPosition())
774 Options.CharIsSigned = CharIsSigned;
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000775
Daniel Dunbar73e8e032009-03-20 23:49:28 +0000776 if (!AllowBuiltins)
Chris Lattner911b8672009-03-13 22:38:49 +0000777 Options.NoBuiltin = 1;
Douglas Gregor23d23262009-02-14 20:49:29 +0000778 if (Freestanding)
Chris Lattner911b8672009-03-13 22:38:49 +0000779 Options.Freestanding = Options.NoBuiltin = 1;
780
Chris Lattner1e3eedb2009-03-13 17:38:01 +0000781 if (EnableHeinousExtensions)
782 Options.HeinousExtensions = 1;
Douglas Gregor23d23262009-02-14 20:49:29 +0000783
Anders Carlssonf2310142009-05-13 19:49:53 +0000784 if (AccessControl)
785 Options.AccessControl = 1;
786
Daniel Dunbarfd46ea22009-02-16 22:43:43 +0000787 Options.MathErrno = MathErrno;
788
Douglas Gregor375733c2009-03-10 00:06:19 +0000789 Options.InstantiationDepth = TemplateDepth;
790
Chris Lattnerddae7102008-12-04 22:54:33 +0000791 // Override the default runtime if the user requested it.
792 if (NeXTRuntime)
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000793 Options.NeXTRuntime = 1;
Chris Lattnerddae7102008-12-04 22:54:33 +0000794 else if (GNURuntime)
Daniel Dunbar1be1df32008-08-11 21:35:06 +0000795 Options.NeXTRuntime = 0;
Fariborz Jahanian48543f52009-01-21 22:04:16 +0000796
Fariborz Jahaniand0374812009-01-22 23:02:58 +0000797 if (ObjCNonFragileABI)
798 Options.ObjCNonFragileABI = 1;
Fariborz Jahanianfefd5e82009-05-22 20:17:16 +0000799
800 Options.ObjCSenderDispatch = ObjCSenderDispatch;
Daniel Dunbar5523e862009-05-04 05:16:21 +0000801
Daniel Dunbar9bae8652009-02-04 21:19:06 +0000802 if (EmitAllDecls)
803 Options.EmitAllDecls = 1;
Anders Carlssondfd77642009-04-06 17:37:10 +0000804
Daniel Dunbarcdd3c762009-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 Carlssondfd77642009-04-06 17:37:10 +0000808
809 // -Os implies -O2
Daniel Dunbarcdd3c762009-04-08 18:03:55 +0000810 if (OptSize || OptLevel)
Anders Carlssondfd77642009-04-06 17:37:10 +0000811 Options.Optimize = 1;
Daniel Dunbare079c712009-04-08 03:03:23 +0000812
813 assert(PICLevel <= 2 && "Invalid value for -pic-level");
814 Options.PICLevel = PICLevel;
Daniel Dunbardedc94c2009-04-08 05:11:16 +0000815
Daniel Dunbarcdd3c762009-04-08 18:03:55 +0000816 Options.GNUInline = !Options.C99;
Chris Lattnerd7f00522009-05-06 04:38:30 +0000817 // FIXME: This is affected by other options (-fno-inline).
Daniel Dunbarcdd3c762009-04-08 18:03:55 +0000818 Options.NoInline = !OptSize && !OptLevel;
819
820 Options.Static = StaticDefine;
821
Bill Wendlinge1d4f5d2009-06-28 07:36:13 +0000822 assert(StackProtector <= 2 && "Invalid value for -stack-protector");
823 if (StackProtector != -1)
824 Options.StackProtector = StackProtector;
825
Daniel Dunbardedc94c2009-04-08 05:11:16 +0000826 if (MainFileName.getPosition())
827 Options.setMainFileName(MainFileName.c_str());
Chris Lattner4b009652007-07-25 00:24:17 +0000828}
829
830//===----------------------------------------------------------------------===//
Ted Kremenek40499482007-12-03 22:06:55 +0000831// Target Triple Processing.
832//===----------------------------------------------------------------------===//
833
834static llvm::cl::opt<std::string>
835TargetTriple("triple",
Sanjiv Gupta69683532008-05-08 08:28:14 +0000836 llvm::cl::desc("Specify target triple (e.g. i686-apple-darwin9)"));
Ted Kremenek40499482007-12-03 22:06:55 +0000837
Chris Lattnerfc457002008-03-05 01:18:20 +0000838static llvm::cl::opt<std::string>
Chris Lattner2b168e02008-09-30 01:13:12 +0000839MacOSVersionMin("mmacosx-version-min",
Daniel Dunbar93f64532009-04-10 19:52:24 +0000840 llvm::cl::desc("Specify target Mac OS X version (e.g. 10.5)"));
Chris Lattner2b168e02008-09-30 01:13:12 +0000841
Chris Lattner01de9c82008-09-30 20:16:56 +0000842// If -mmacosx-version-min=10.3.9 is specified, change the triple from being
843// something like powerpc-apple-darwin9 to powerpc-apple-darwin7
Daniel Dunbar4d36d982009-03-31 20:10:05 +0000844
845// FIXME: We should have the driver do this instead.
Chris Lattner01de9c82008-09-30 20:16:56 +0000846static void HandleMacOSVersionMin(std::string &Triple) {
847 std::string::size_type DarwinDashIdx = Triple.find("-darwin");
848 if (DarwinDashIdx == std::string::npos) {
849 fprintf(stderr,
Daniel Dunbar93f64532009-04-10 19:52:24 +0000850 "-mmacosx-version-min only valid for darwin (Mac OS X) targets\n");
Chris Lattner01de9c82008-09-30 20:16:56 +0000851 exit(1);
852 }
853 unsigned DarwinNumIdx = DarwinDashIdx + strlen("-darwin");
854
Chris Lattner01de9c82008-09-30 20:16:56 +0000855 // Remove the number.
856 Triple.resize(DarwinNumIdx);
857
858 // Validate that MacOSVersionMin is a 'version number', starting with 10.[3-9]
859 bool MacOSVersionMinIsInvalid = false;
860 int VersionNum = 0;
861 if (MacOSVersionMin.size() < 4 ||
862 MacOSVersionMin.substr(0, 3) != "10." ||
863 !isdigit(MacOSVersionMin[3])) {
864 MacOSVersionMinIsInvalid = true;
865 } else {
866 const char *Start = MacOSVersionMin.c_str()+3;
867 char *End = 0;
868 VersionNum = (int)strtol(Start, &End, 10);
869
Chris Lattnerd376f6d2008-09-30 20:30:12 +0000870 // The version number must be in the range 0-9.
871 MacOSVersionMinIsInvalid = (unsigned)VersionNum > 9;
872
Chris Lattner01de9c82008-09-30 20:16:56 +0000873 // Turn MacOSVersionMin into a darwin number: e.g. 10.3.9 is 3 -> 7.
874 Triple += llvm::itostr(VersionNum+4);
875
Chris Lattnerd376f6d2008-09-30 20:30:12 +0000876 if (End[0] == '.' && isdigit(End[1]) && End[2] == '\0') { // 10.4.7 is ok.
877 // Add the period piece (.7) to the end of the triple. This gives us
878 // something like ...-darwin8.7
Chris Lattner01de9c82008-09-30 20:16:56 +0000879 Triple += End;
Chris Lattner01de9c82008-09-30 20:16:56 +0000880 } else if (End[0] != '\0') { // "10.4" is ok. 10.4x is not.
881 MacOSVersionMinIsInvalid = true;
882 }
883 }
884
885 if (MacOSVersionMinIsInvalid) {
886 fprintf(stderr,
Daniel Dunbar7fe2af62009-03-31 17:35:15 +0000887 "-mmacosx-version-min=%s is invalid, expected something like '10.4'.\n",
Chris Lattner01de9c82008-09-30 20:16:56 +0000888 MacOSVersionMin.c_str());
889 exit(1);
890 }
Fariborz Jahanian27c08a52009-04-10 20:33:45 +0000891 else if (VersionNum <= 4 &&
892 !strncmp(Triple.c_str(), "x86_64", strlen("x86_64"))) {
893 fprintf(stderr,
894 "-mmacosx-version-min=%s is invalid with -arch x86_64.\n",
895 MacOSVersionMin.c_str());
896 exit(1);
897 }
898
Chris Lattner01de9c82008-09-30 20:16:56 +0000899}
900
Daniel Dunbar93f64532009-04-10 19:52:24 +0000901static llvm::cl::opt<std::string>
902IPhoneOSVersionMin("miphoneos-version-min",
903 llvm::cl::desc("Specify target iPhone OS version (e.g. 2.0)"));
904
905// If -miphoneos-version-min=2.2 is specified, change the triple from being
906// something like armv6-apple-darwin10 to armv6-apple-darwin9.2.2. We use
907// 9 as the default major Darwin number, and encode the iPhone OS version
908// number in the minor version and revision.
909
910// FIXME: We should have the driver do this instead.
911static void HandleIPhoneOSVersionMin(std::string &Triple) {
912 std::string::size_type DarwinDashIdx = Triple.find("-darwin");
913 if (DarwinDashIdx == std::string::npos) {
914 fprintf(stderr,
915 "-miphoneos-version-min only valid for darwin (Mac OS X) targets\n");
916 exit(1);
917 }
918 unsigned DarwinNumIdx = DarwinDashIdx + strlen("-darwin");
919
920 // Remove the number.
921 Triple.resize(DarwinNumIdx);
922
923 // Validate that IPhoneOSVersionMin is a 'version number', starting with [2-9].[0-9]
924 bool IPhoneOSVersionMinIsInvalid = false;
925 int VersionNum = 0;
926 if (IPhoneOSVersionMin.size() < 3 ||
927 !isdigit(IPhoneOSVersionMin[0])) {
928 IPhoneOSVersionMinIsInvalid = true;
929 } else {
930 const char *Start = IPhoneOSVersionMin.c_str();
931 char *End = 0;
932 VersionNum = (int)strtol(Start, &End, 10);
933
934 // The version number must be in the range 0-9.
935 IPhoneOSVersionMinIsInvalid = (unsigned)VersionNum > 9;
936
937 // Turn IPhoneOSVersionMin into a darwin number: e.g. 2.0 is 2 -> 9.2.
938 Triple += "9." + llvm::itostr(VersionNum);
939
940 if (End[0] == '.' && isdigit(End[1]) && End[2] == '\0') { // 2.2 is ok.
941 // Add the period piece (.2) to the end of the triple. This gives us
942 // something like ...-darwin9.2.2
943 Triple += End;
944 } else if (End[0] != '\0') { // "2.2" is ok. 2x is not.
945 IPhoneOSVersionMinIsInvalid = true;
946 }
947 }
948
949 if (IPhoneOSVersionMinIsInvalid) {
950 fprintf(stderr,
951 "-miphoneos-version-min=%s is invalid, expected something like '2.0'.\n",
952 IPhoneOSVersionMin.c_str());
953 exit(1);
954 }
955}
956
Chris Lattner01de9c82008-09-30 20:16:56 +0000957/// CreateTargetTriple - Process the various options that affect the target
958/// triple and build a final aggregate triple that we are compiling for.
Chris Lattnerf3d79c32008-03-09 01:35:13 +0000959static std::string CreateTargetTriple() {
Ted Kremenek40499482007-12-03 22:06:55 +0000960 // Initialize base triple. If a -triple option has been specified, use
961 // that triple. Otherwise, default to the host triple.
Chris Lattner210c0cc2007-12-12 05:01:48 +0000962 std::string Triple = TargetTriple;
Daniel Dunbar7fe2af62009-03-31 17:35:15 +0000963 if (Triple.empty())
964 Triple = llvm::sys::getHostTriple();
Chris Lattner2b168e02008-09-30 01:13:12 +0000965
966 // If -mmacosx-version-min=10.3.9 is specified, change the triple from being
967 // something like powerpc-apple-darwin9 to powerpc-apple-darwin7
Chris Lattner01de9c82008-09-30 20:16:56 +0000968 if (!MacOSVersionMin.empty())
969 HandleMacOSVersionMin(Triple);
Daniel Dunbar93f64532009-04-10 19:52:24 +0000970 else if (!IPhoneOSVersionMin.empty())
971 HandleIPhoneOSVersionMin(Triple);;
Ted Kremenek40499482007-12-03 22:06:55 +0000972
Chris Lattner2b168e02008-09-30 01:13:12 +0000973 return Triple;
Ted Kremenek40499482007-12-03 22:06:55 +0000974}
975
976//===----------------------------------------------------------------------===//
Chris Lattner94269d72009-04-21 05:40:52 +0000977// SourceManager initialization.
Chris Lattner4b009652007-07-25 00:24:17 +0000978//===----------------------------------------------------------------------===//
979
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000980static bool InitializeSourceManager(Preprocessor &PP,
981 const std::string &InFile) {
982 // Figure out where to get and map in the main file.
983 SourceManager &SourceMgr = PP.getSourceManager();
984 FileManager &FileMgr = PP.getFileManager();
Daniel Dunbarbb56def2009-04-27 21:19:07 +0000985
986 if (EmptyInputOnly) {
987 const char *EmptyStr = "";
988 llvm::MemoryBuffer *SB =
989 llvm::MemoryBuffer::getMemBuffer(EmptyStr, EmptyStr, "<empty input>");
990 SourceMgr.createMainFileIDForMemBuffer(SB);
991 } else if (InFile != "-") {
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000992 const FileEntry *File = FileMgr.getFile(InFile);
993 if (File) SourceMgr.createMainFileID(File, SourceLocation());
994 if (SourceMgr.getMainFileID().isInvalid()) {
995 PP.getDiagnostics().Report(FullSourceLoc(), diag::err_fe_error_reading)
996 << InFile.c_str();
997 return true;
998 }
999 } else {
1000 llvm::MemoryBuffer *SB = llvm::MemoryBuffer::getSTDIN();
1001
1002 // If stdin was empty, SB is null. Cons up an empty memory
1003 // buffer now.
1004 if (!SB) {
1005 const char *EmptyStr = "";
1006 SB = llvm::MemoryBuffer::getMemBuffer(EmptyStr, EmptyStr, "<stdin>");
1007 }
1008
1009 SourceMgr.createMainFileIDForMemBuffer(SB);
1010 if (SourceMgr.getMainFileID().isInvalid()) {
1011 PP.getDiagnostics().Report(FullSourceLoc(),
1012 diag::err_fe_error_reading_stdin);
1013 return true;
1014 }
1015 }
1016
1017 return false;
1018}
1019
Chris Lattner47b6a162008-04-19 23:09:31 +00001020
Chris Lattner94269d72009-04-21 05:40:52 +00001021//===----------------------------------------------------------------------===//
1022// Preprocessor Initialization
1023//===----------------------------------------------------------------------===//
Sam Bishop61a20782008-04-14 14:41:57 +00001024
Chris Lattner94269d72009-04-21 05:40:52 +00001025// FIXME: Preprocessor builtins to support.
1026// -A... - Play with #assertions
1027// -undef - Undefine all predefined macros
Chris Lattnerb62396d2009-04-08 20:15:42 +00001028
Chris Lattner94269d72009-04-21 05:40:52 +00001029static llvm::cl::list<std::string>
1030D_macros("D", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
1031 llvm::cl::desc("Predefine the specified macro"));
1032static llvm::cl::list<std::string>
1033U_macros("U", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
1034 llvm::cl::desc("Undefine the specified macro"));
Chris Lattner0e004a12009-04-08 18:24:34 +00001035
Chris Lattner94269d72009-04-21 05:40:52 +00001036static llvm::cl::list<std::string>
1037ImplicitIncludes("include", llvm::cl::value_desc("file"),
1038 llvm::cl::desc("Include file before parsing"));
1039static llvm::cl::list<std::string>
1040ImplicitMacroIncludes("imacros", llvm::cl::value_desc("file"),
1041 llvm::cl::desc("Include macros from file before parsing"));
Chris Lattner0e004a12009-04-08 18:24:34 +00001042
Chris Lattner94269d72009-04-21 05:40:52 +00001043static llvm::cl::opt<std::string>
1044ImplicitIncludePCH("include-pch", llvm::cl::value_desc("file"),
1045 llvm::cl::desc("Include precompiled header file"));
1046
1047static llvm::cl::opt<std::string>
1048ImplicitIncludePTH("include-pth", llvm::cl::value_desc("file"),
1049 llvm::cl::desc("Include file before parsing"));
1050
Chris Lattner4b009652007-07-25 00:24:17 +00001051
1052//===----------------------------------------------------------------------===//
1053// Preprocessor include path information.
1054//===----------------------------------------------------------------------===//
1055
1056// This tool exports a large number of command line options to control how the
1057// preprocessor searches for header files. At root, however, the Preprocessor
1058// object takes a very simple interface: a list of directories to search for
1059//
Daniel Dunbarf1c39f02009-05-06 03:48:17 +00001060// FIXME: -nostdinc++
Chris Lattnerae3dcc02007-08-26 17:47:35 +00001061// FIXME: -imultilib
Chris Lattner4b009652007-07-25 00:24:17 +00001062//
Chris Lattner4b009652007-07-25 00:24:17 +00001063
1064static llvm::cl::opt<bool>
1065nostdinc("nostdinc", llvm::cl::desc("Disable standard #include directories"));
1066
1067// Various command line options. These four add directories to each chain.
1068static llvm::cl::list<std::string>
1069F_dirs("F", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1070 llvm::cl::desc("Add directory to framework include search path"));
1071static llvm::cl::list<std::string>
1072I_dirs("I", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1073 llvm::cl::desc("Add directory to include search path"));
1074static llvm::cl::list<std::string>
1075idirafter_dirs("idirafter", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1076 llvm::cl::desc("Add directory to AFTER include search path"));
1077static llvm::cl::list<std::string>
1078iquote_dirs("iquote", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1079 llvm::cl::desc("Add directory to QUOTE include search path"));
1080static llvm::cl::list<std::string>
1081isystem_dirs("isystem", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1082 llvm::cl::desc("Add directory to SYSTEM include search path"));
1083
1084// These handle -iprefix/-iwithprefix/-iwithprefixbefore.
1085static llvm::cl::list<std::string>
1086iprefix_vals("iprefix", llvm::cl::value_desc("prefix"), llvm::cl::Prefix,
1087 llvm::cl::desc("Set the -iwithprefix/-iwithprefixbefore prefix"));
1088static llvm::cl::list<std::string>
1089iwithprefix_vals("iwithprefix", llvm::cl::value_desc("dir"), llvm::cl::Prefix,
1090 llvm::cl::desc("Set directory to SYSTEM include search path with prefix"));
1091static llvm::cl::list<std::string>
1092iwithprefixbefore_vals("iwithprefixbefore", llvm::cl::value_desc("dir"),
1093 llvm::cl::Prefix,
1094 llvm::cl::desc("Set directory to include search path with prefix"));
1095
Chris Lattnerae3dcc02007-08-26 17:47:35 +00001096static llvm::cl::opt<std::string>
1097isysroot("isysroot", llvm::cl::value_desc("dir"), llvm::cl::init("/"),
1098 llvm::cl::desc("Set the system root directory (usually /)"));
1099
Chris Lattner4b009652007-07-25 00:24:17 +00001100// Finally, implement the code that groks the options above.
Chris Lattner4f022a72008-03-01 08:07:28 +00001101
Chris Lattner4b009652007-07-25 00:24:17 +00001102/// InitializeIncludePaths - Process the -I options and set them in the
1103/// HeaderSearch object.
Nico Weber770e3882008-08-22 09:25:22 +00001104void InitializeIncludePaths(const char *Argv0, HeaderSearch &Headers,
1105 FileManager &FM, const LangOptions &Lang) {
1106 InitHeaderSearch Init(Headers, Verbose, isysroot);
1107
Ted Kremenekb4d41e12008-05-31 00:27:00 +00001108 // Handle -I... and -F... options, walking the lists in parallel.
1109 unsigned Iidx = 0, Fidx = 0;
1110 while (Iidx < I_dirs.size() && Fidx < F_dirs.size()) {
1111 if (I_dirs.getPosition(Iidx) < F_dirs.getPosition(Fidx)) {
Nico Weber770e3882008-08-22 09:25:22 +00001112 Init.AddPath(I_dirs[Iidx], InitHeaderSearch::Angled, false, true, false);
Ted Kremenekb4d41e12008-05-31 00:27:00 +00001113 ++Iidx;
1114 } else {
Nico Weber770e3882008-08-22 09:25:22 +00001115 Init.AddPath(F_dirs[Fidx], InitHeaderSearch::Angled, false, true, true);
Ted Kremenekb4d41e12008-05-31 00:27:00 +00001116 ++Fidx;
1117 }
1118 }
Chris Lattner4b009652007-07-25 00:24:17 +00001119
Ted Kremenekb4d41e12008-05-31 00:27:00 +00001120 // Consume what's left from whatever list was longer.
1121 for (; Iidx != I_dirs.size(); ++Iidx)
Nico Weber770e3882008-08-22 09:25:22 +00001122 Init.AddPath(I_dirs[Iidx], InitHeaderSearch::Angled, false, true, false);
Ted Kremenekb4d41e12008-05-31 00:27:00 +00001123 for (; Fidx != F_dirs.size(); ++Fidx)
Nico Weber770e3882008-08-22 09:25:22 +00001124 Init.AddPath(F_dirs[Fidx], InitHeaderSearch::Angled, false, true, true);
Chris Lattner4b009652007-07-25 00:24:17 +00001125
1126 // Handle -idirafter... options.
1127 for (unsigned i = 0, e = idirafter_dirs.size(); i != e; ++i)
Nico Weber770e3882008-08-22 09:25:22 +00001128 Init.AddPath(idirafter_dirs[i], InitHeaderSearch::After,
1129 false, true, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001130
1131 // Handle -iquote... options.
1132 for (unsigned i = 0, e = iquote_dirs.size(); i != e; ++i)
Nico Weber770e3882008-08-22 09:25:22 +00001133 Init.AddPath(iquote_dirs[i], InitHeaderSearch::Quoted, false, true, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001134
1135 // Handle -isystem... options.
1136 for (unsigned i = 0, e = isystem_dirs.size(); i != e; ++i)
Nico Weber770e3882008-08-22 09:25:22 +00001137 Init.AddPath(isystem_dirs[i], InitHeaderSearch::System, false, true, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001138
1139 // Walk the -iprefix/-iwithprefix/-iwithprefixbefore argument lists in
1140 // parallel, processing the values in order of occurance to get the right
1141 // prefixes.
1142 {
1143 std::string Prefix = ""; // FIXME: this isn't the correct default prefix.
1144 unsigned iprefix_idx = 0;
1145 unsigned iwithprefix_idx = 0;
1146 unsigned iwithprefixbefore_idx = 0;
1147 bool iprefix_done = iprefix_vals.empty();
1148 bool iwithprefix_done = iwithprefix_vals.empty();
1149 bool iwithprefixbefore_done = iwithprefixbefore_vals.empty();
1150 while (!iprefix_done || !iwithprefix_done || !iwithprefixbefore_done) {
1151 if (!iprefix_done &&
1152 (iwithprefix_done ||
1153 iprefix_vals.getPosition(iprefix_idx) <
1154 iwithprefix_vals.getPosition(iwithprefix_idx)) &&
1155 (iwithprefixbefore_done ||
1156 iprefix_vals.getPosition(iprefix_idx) <
1157 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
1158 Prefix = iprefix_vals[iprefix_idx];
1159 ++iprefix_idx;
1160 iprefix_done = iprefix_idx == iprefix_vals.size();
1161 } else if (!iwithprefix_done &&
1162 (iwithprefixbefore_done ||
1163 iwithprefix_vals.getPosition(iwithprefix_idx) <
1164 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
Nico Weber770e3882008-08-22 09:25:22 +00001165 Init.AddPath(Prefix+iwithprefix_vals[iwithprefix_idx],
1166 InitHeaderSearch::System, false, false, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001167 ++iwithprefix_idx;
1168 iwithprefix_done = iwithprefix_idx == iwithprefix_vals.size();
1169 } else {
Nico Weber770e3882008-08-22 09:25:22 +00001170 Init.AddPath(Prefix+iwithprefixbefore_vals[iwithprefixbefore_idx],
1171 InitHeaderSearch::Angled, false, false, false);
Chris Lattner4b009652007-07-25 00:24:17 +00001172 ++iwithprefixbefore_idx;
1173 iwithprefixbefore_done =
1174 iwithprefixbefore_idx == iwithprefixbefore_vals.size();
1175 }
1176 }
1177 }
Chris Lattner4f022a72008-03-01 08:07:28 +00001178
Nico Weber770e3882008-08-22 09:25:22 +00001179 Init.AddDefaultEnvVarPaths(Lang);
Chris Lattner4f022a72008-03-01 08:07:28 +00001180
Daniel Dunbar4e604292009-02-21 20:52:41 +00001181 // Add the clang headers, which are relative to the clang binary.
Chris Lattner3ee4a2f2008-03-03 03:16:03 +00001182 llvm::sys::Path MainExecutablePath =
Chris Lattner716a0542008-03-03 05:57:43 +00001183 llvm::sys::Path::GetMainExecutable(Argv0,
1184 (void*)(intptr_t)InitializeIncludePaths);
Chris Lattner3ee4a2f2008-03-03 03:16:03 +00001185 if (!MainExecutablePath.isEmpty()) {
1186 MainExecutablePath.eraseComponent(); // Remove /clang from foo/bin/clang
1187 MainExecutablePath.eraseComponent(); // Remove /bin from foo/bin
Daniel Dunbar4e604292009-02-21 20:52:41 +00001188
Daniel Dunbarf1c39f02009-05-06 03:48:17 +00001189 // Get foo/lib/clang/<version>/include
Daniel Dunbar4e604292009-02-21 20:52:41 +00001190 MainExecutablePath.appendComponent("lib");
1191 MainExecutablePath.appendComponent("clang");
Daniel Dunbarf1c39f02009-05-06 03:48:17 +00001192 MainExecutablePath.appendComponent(CLANG_VERSION_STRING);
Daniel Dunbar4e604292009-02-21 20:52:41 +00001193 MainExecutablePath.appendComponent("include");
Chris Lattner99a72652009-02-19 06:48:28 +00001194
1195 // We pass true to ignore sysroot so that we *always* look for clang headers
1196 // relative to our executable, never relative to -isysroot.
1197 Init.AddPath(MainExecutablePath.c_str(), InitHeaderSearch::System,
1198 false, false, false, true /*ignore sysroot*/);
Chris Lattner3ee4a2f2008-03-03 03:16:03 +00001199 }
1200
Nico Weber770e3882008-08-22 09:25:22 +00001201 if (!nostdinc)
1202 Init.AddDefaultSystemIncludePaths(Lang);
Chris Lattner4b009652007-07-25 00:24:17 +00001203
1204 // Now that we have collected all of the include paths, merge them all
1205 // together and tell the preprocessor about them.
1206
Nico Weber770e3882008-08-22 09:25:22 +00001207 Init.Realize();
Chris Lattner4b009652007-07-25 00:24:17 +00001208}
1209
Chris Lattner94269d72009-04-21 05:40:52 +00001210void InitializePreprocessorInitOptions(PreprocessorInitOptions &InitOpts)
1211{
1212 // Add macros from the command line.
1213 unsigned d = 0, D = D_macros.size();
1214 unsigned u = 0, U = U_macros.size();
1215 while (d < D || u < U) {
1216 if (u == U || (d < D && D_macros.getPosition(d) < U_macros.getPosition(u)))
1217 InitOpts.addMacroDef(D_macros[d++]);
1218 else
1219 InitOpts.addMacroUndef(U_macros[u++]);
1220 }
1221
1222 // If -imacros are specified, include them now. These are processed before
1223 // any -include directives.
1224 for (unsigned i = 0, e = ImplicitMacroIncludes.size(); i != e; ++i)
1225 InitOpts.addMacroInclude(ImplicitMacroIncludes[i]);
1226
Douglas Gregoreccf0d12009-05-12 01:31:05 +00001227 if (!ImplicitIncludePTH.empty() || !ImplicitIncludes.empty() ||
1228 (!ImplicitIncludePCH.empty() && ProgAction == PrintPreprocessedInput)) {
Chris Lattner94269d72009-04-21 05:40:52 +00001229 // We want to add these paths to the predefines buffer in order, make a
1230 // temporary vector to sort by their occurrence.
1231 llvm::SmallVector<std::pair<unsigned, std::string*>, 8> OrderedPaths;
1232
1233 if (!ImplicitIncludePTH.empty())
1234 OrderedPaths.push_back(std::make_pair(ImplicitIncludePTH.getPosition(),
1235 &ImplicitIncludePTH));
Douglas Gregoreccf0d12009-05-12 01:31:05 +00001236 if (!ImplicitIncludePCH.empty() && ProgAction == PrintPreprocessedInput)
1237 OrderedPaths.push_back(std::make_pair(ImplicitIncludePCH.getPosition(),
1238 &ImplicitIncludePCH));
Chris Lattner94269d72009-04-21 05:40:52 +00001239 for (unsigned i = 0, e = ImplicitIncludes.size(); i != e; ++i)
1240 OrderedPaths.push_back(std::make_pair(ImplicitIncludes.getPosition(i),
1241 &ImplicitIncludes[i]));
1242 llvm::array_pod_sort(OrderedPaths.begin(), OrderedPaths.end());
1243
1244
1245 // Now that they are ordered by position, add to the predefines buffer.
1246 for (unsigned i = 0, e = OrderedPaths.size(); i != e; ++i) {
1247 std::string *Ptr = OrderedPaths[i].second;
1248 if (!ImplicitIncludes.empty() &&
1249 Ptr >= &ImplicitIncludes[0] &&
1250 Ptr <= &ImplicitIncludes[ImplicitIncludes.size()-1]) {
1251 InitOpts.addInclude(*Ptr, false);
Douglas Gregoreccf0d12009-05-12 01:31:05 +00001252 } else if (Ptr == &ImplicitIncludePTH) {
Chris Lattner94269d72009-04-21 05:40:52 +00001253 InitOpts.addInclude(*Ptr, true);
Douglas Gregoreccf0d12009-05-12 01:31:05 +00001254 } else {
1255 // We end up here when we're producing preprocessed output and
1256 // we loaded a PCH file. In this case, just include the header
1257 // file that was used to build the precompiled header.
1258 assert(Ptr == &ImplicitIncludePCH);
1259 std::string OriginalFile = PCHReader::getOriginalSourceFile(*Ptr);
1260 if (!OriginalFile.empty()) {
1261 InitOpts.addInclude(OriginalFile, false);
1262 ImplicitIncludePCH.clear();
1263 }
Chris Lattner94269d72009-04-21 05:40:52 +00001264 }
1265 }
1266 }
1267}
1268
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001269//===----------------------------------------------------------------------===//
1270// Driver PreprocessorFactory - For lazily generating preprocessors ...
1271//===----------------------------------------------------------------------===//
1272
1273namespace {
1274class VISIBILITY_HIDDEN DriverPreprocessorFactory : public PreprocessorFactory {
1275 Diagnostic &Diags;
1276 const LangOptions &LangInfo;
1277 TargetInfo &Target;
1278 SourceManager &SourceMgr;
1279 HeaderSearch &HeaderInfo;
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001280
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001281public:
Eli Friedmane934dca2009-05-18 07:39:39 +00001282 DriverPreprocessorFactory(Diagnostic &diags, const LangOptions &opts,
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001283 TargetInfo &target, SourceManager &SM,
1284 HeaderSearch &Headers)
Eli Friedmane934dca2009-05-18 07:39:39 +00001285 : Diags(diags), LangInfo(opts), Target(target),
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001286 SourceMgr(SM), HeaderInfo(Headers) {}
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001287
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001288
1289 virtual ~DriverPreprocessorFactory() {}
1290
1291 virtual Preprocessor* CreatePreprocessor() {
Ted Kremenekd976c3d2009-01-15 18:47:46 +00001292 llvm::OwningPtr<PTHManager> PTHMgr;
1293
Ted Kremenek2ee90d52009-03-20 00:26:38 +00001294 if (!TokenCache.empty() && !ImplicitIncludePTH.empty()) {
1295 fprintf(stderr, "error: cannot use both -token-cache and -include-pth "
1296 "options\n");
Ted Kremenek6348cc62009-03-22 06:42:39 +00001297 exit(1);
Ted Kremenek2ee90d52009-03-20 00:26:38 +00001298 }
1299
Ted Kremenekd976c3d2009-01-15 18:47:46 +00001300 // Use PTH?
Ted Kremenek2ee90d52009-03-20 00:26:38 +00001301 if (!TokenCache.empty() || !ImplicitIncludePTH.empty()) {
1302 const std::string& x = TokenCache.empty() ? ImplicitIncludePTH:TokenCache;
Ted Kremenek6348cc62009-03-22 06:42:39 +00001303 PTHMgr.reset(PTHManager::Create(x, &Diags,
1304 TokenCache.empty() ? Diagnostic::Error
1305 : Diagnostic::Warning));
Ted Kremenek2ee90d52009-03-20 00:26:38 +00001306 }
Ted Kremenekd976c3d2009-01-15 18:47:46 +00001307
Ted Kremenek6348cc62009-03-22 06:42:39 +00001308 if (Diags.hasErrorOccurred())
1309 exit(1);
1310
Ted Kremenekd976c3d2009-01-15 18:47:46 +00001311 // Create the Preprocessor.
1312 llvm::OwningPtr<Preprocessor> PP(new Preprocessor(Diags, LangInfo, Target,
1313 SourceMgr, HeaderInfo,
1314 PTHMgr.get()));
1315
1316 // Note that this is different then passing PTHMgr to Preprocessor's ctor.
1317 // That argument is used as the IdentifierInfoLookup argument to
1318 // IdentifierTable's ctor.
1319 if (PTHMgr) {
1320 PTHMgr->setPreprocessor(PP.get());
1321 PP->setPTHManager(PTHMgr.take());
1322 }
Douglas Gregorab1cef72009-04-10 03:52:48 +00001323
Chris Lattner94269d72009-04-21 05:40:52 +00001324 PreprocessorInitOptions InitOpts;
1325 InitializePreprocessorInitOptions(InitOpts);
Eli Friedmane934dca2009-05-18 07:39:39 +00001326 if (InitializePreprocessor(*PP, InitOpts))
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001327 return 0;
Chris Lattner94269d72009-04-21 05:40:52 +00001328
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001329 return PP.take();
Ted Kremenek01d3bf72008-04-17 21:38:34 +00001330 }
1331};
1332}
Chris Lattner4b009652007-07-25 00:24:17 +00001333
Chris Lattner4b009652007-07-25 00:24:17 +00001334//===----------------------------------------------------------------------===//
1335// Basic Parser driver
1336//===----------------------------------------------------------------------===//
1337
Chris Lattner9d818a22008-04-19 23:25:44 +00001338static void ParseFile(Preprocessor &PP, MinimalAction *PA) {
Chris Lattner4b009652007-07-25 00:24:17 +00001339 Parser P(PP, *PA);
Ted Kremenek17861c52007-12-19 22:51:13 +00001340 PP.EnterMainSourceFile();
Chris Lattner4b009652007-07-25 00:24:17 +00001341
1342 // Parsing the specified input file.
1343 P.ParseTranslationUnit();
1344 delete PA;
1345}
1346
1347//===----------------------------------------------------------------------===//
Daniel Dunbaraa7a0662008-10-23 05:50:47 +00001348// Code generation options
1349//===----------------------------------------------------------------------===//
1350
1351static llvm::cl::opt<bool>
Chris Lattner9a09eda2009-03-09 22:05:03 +00001352GenerateDebugInfo("g",
1353 llvm::cl::desc("Generate source level debug information"));
1354
Daniel Dunbar9101a632009-02-17 19:47:34 +00001355static llvm::cl::opt<std::string>
1356TargetCPU("mcpu",
1357 llvm::cl::desc("Target a specific cpu type (-mcpu=help for details)"));
1358
Daniel Dunbar07181d72009-05-06 03:16:41 +00001359static llvm::cl::list<std::string>
1360TargetFeatures("target-feature", llvm::cl::desc("Target specific attributes"));
1361
Devang Patela3707f12009-06-04 23:32:02 +00001362
1363static llvm::cl::opt<bool>
1364DisableRedZone("disable-red-zone",
1365 llvm::cl::desc("Do not emit code that uses the red zone."),
1366 llvm::cl::init(false));
1367
Devang Patel62c2cca2009-06-05 22:05:48 +00001368static llvm::cl::opt<bool>
1369NoImplicitFloat("no-implicit-float",
1370 llvm::cl::desc("Don't generate implicit floating point instructions (x86-only)"),
1371 llvm::cl::init(false));
1372
Daniel Dunbar07181d72009-05-06 03:16:41 +00001373/// ComputeTargetFeatures - Recompute the target feature list to only
1374/// be the list of things that are enabled, based on the target cpu
1375/// and feature list.
1376static void ComputeFeatureMap(TargetInfo *Target,
1377 llvm::StringMap<bool> &Features) {
1378 assert(Features.empty() && "invalid map");
1379
1380 // Initialize the feature map based on the target.
1381 Target->getDefaultFeatures(TargetCPU, Features);
1382
1383 // Apply the user specified deltas.
1384 for (llvm::cl::list<std::string>::iterator it = TargetFeatures.begin(),
1385 ie = TargetFeatures.end(); it != ie; ++it) {
1386 const char *Name = it->c_str();
1387
1388 // FIXME: Don't handle errors like this.
1389 if (Name[0] != '-' && Name[0] != '+') {
1390 fprintf(stderr, "error: clang-cc: invalid target feature string: %s\n",
1391 Name);
1392 exit(1);
1393 }
Daniel Dunbar0838f962009-05-06 21:07:50 +00001394 if (!Target->setFeatureEnabled(Features, Name + 1, (Name[0] == '+'))) {
1395 fprintf(stderr, "error: clang-cc: invalid target feature name: %s\n",
1396 Name + 1);
Daniel Dunbar07181d72009-05-06 03:16:41 +00001397 exit(1);
1398 }
Daniel Dunbar07181d72009-05-06 03:16:41 +00001399 }
1400}
1401
Chris Lattner8a9615c2009-03-16 18:41:18 +00001402static void InitializeCompileOptions(CompileOptions &Opts,
Daniel Dunbar07181d72009-05-06 03:16:41 +00001403 const LangOptions &LangOpts,
1404 const llvm::StringMap<bool> &Features) {
Daniel Dunbaraa7a0662008-10-23 05:50:47 +00001405 Opts.OptimizeSize = OptSize;
Chris Lattner88cbb9b2009-03-09 22:00:34 +00001406 Opts.DebugInfo = GenerateDebugInfo;
Daniel Dunbard27b66b2009-06-02 22:07:45 +00001407
1408 if (DisableLLVMOptimizations) {
1409 Opts.OptimizationLevel = 0;
1410 Opts.Inlining = CompileOptions::NoInlining;
Daniel Dunbard725b162008-10-29 07:56:11 +00001411 } else {
Daniel Dunbard27b66b2009-06-02 22:07:45 +00001412 if (OptSize) {
1413 // -Os implies -O2
1414 Opts.OptimizationLevel = 2;
1415 } else {
1416 Opts.OptimizationLevel = OptLevel;
1417 }
1418
1419 // We must always run at least the always inlining pass.
1420 if (Opts.OptimizationLevel > 1)
1421 Opts.Inlining = CompileOptions::NormalInlining;
1422 else
1423 Opts.Inlining = CompileOptions::OnlyAlwaysInlining;
Daniel Dunbard725b162008-10-29 07:56:11 +00001424 }
Daniel Dunbar721cbf12008-10-29 03:42:18 +00001425
1426 // FIXME: There are llvm-gcc options to control these selectively.
Daniel Dunbar721cbf12008-10-29 03:42:18 +00001427 Opts.UnrollLoops = (Opts.OptimizationLevel > 1 && !OptSize);
Chris Lattner8a9615c2009-03-16 18:41:18 +00001428 Opts.SimplifyLibCalls = !LangOpts.NoBuiltin;
Daniel Dunbare8d0ba72008-10-31 09:34:21 +00001429
1430#ifdef NDEBUG
1431 Opts.VerifyModule = 0;
1432#endif
Daniel Dunbar9101a632009-02-17 19:47:34 +00001433
1434 Opts.CPU = TargetCPU;
Daniel Dunbar07181d72009-05-06 03:16:41 +00001435 Opts.Features.clear();
1436 for (llvm::StringMap<bool>::const_iterator it = Features.begin(),
1437 ie = Features.end(); it != ie; ++it) {
1438 // FIXME: If we are completely confident that we have the right
1439 // set, we only need to pass the minuses.
1440 std::string Name(it->second ? "+" : "-");
1441 Name += it->first();
1442 Opts.Features.push_back(Name);
1443 }
Chris Lattnere8f70712009-02-18 01:23:44 +00001444
Chris Lattnerf04a7562009-03-26 05:00:52 +00001445 Opts.NoCommon = NoCommon | LangOpts.CPlusPlus;
1446
Chris Lattnere8f70712009-02-18 01:23:44 +00001447 // Handle -ftime-report.
1448 Opts.TimePasses = TimeReport;
Devang Patela3707f12009-06-04 23:32:02 +00001449
1450 Opts.DisableRedZone = DisableRedZone;
Devang Patel62c2cca2009-06-05 22:05:48 +00001451 Opts.NoImplicitFloat = NoImplicitFloat;
Daniel Dunbaraa7a0662008-10-23 05:50:47 +00001452}
1453
1454//===----------------------------------------------------------------------===//
Douglas Gregor24b48b02009-04-02 19:05:20 +00001455// Fix-It Options
1456//===----------------------------------------------------------------------===//
1457static llvm::cl::list<ParsedSourceLocation>
1458FixItAtLocations("fixit-at", llvm::cl::value_desc("source-location"),
1459 llvm::cl::desc("Perform Fix-It modifications at the given source location"));
1460
1461//===----------------------------------------------------------------------===//
Eli Friedman35ba7a62009-05-18 22:39:16 +00001462// ObjC Rewriter Options
1463//===----------------------------------------------------------------------===//
1464static llvm::cl::opt<bool>
1465SilenceRewriteMacroWarning("Wno-rewrite-macros", llvm::cl::init(false),
1466 llvm::cl::desc("Silence ObjC rewriting warnings"));
1467
1468//===----------------------------------------------------------------------===//
Eli Friedman4d03d382009-05-19 01:17:04 +00001469// Warning Options
1470//===----------------------------------------------------------------------===//
1471
1472// This gets all -W options, including -Werror, -W[no-]system-headers, etc. The
1473// driver has stripped off -Wa,foo etc. The driver has also translated -W to
1474// -Wextra, so we don't need to worry about it.
1475static llvm::cl::list<std::string>
1476OptWarnings("W", llvm::cl::Prefix, llvm::cl::ValueOptional);
1477
1478static llvm::cl::opt<bool> OptPedantic("pedantic");
1479static llvm::cl::opt<bool> OptPedanticErrors("pedantic-errors");
1480static llvm::cl::opt<bool> OptNoWarnings("w");
1481
1482//===----------------------------------------------------------------------===//
Eli Friedmane2554252009-05-19 03:06:47 +00001483// Preprocessing (-E mode) Options
1484//===----------------------------------------------------------------------===//
1485static llvm::cl::opt<bool>
1486DisableLineMarkers("P", llvm::cl::desc("Disable linemarker output in -E mode"));
1487static llvm::cl::opt<bool>
1488EnableCommentOutput("C", llvm::cl::desc("Enable comment output in -E mode"));
1489static llvm::cl::opt<bool>
1490EnableMacroCommentOutput("CC",
1491 llvm::cl::desc("Enable comment output in -E mode, "
1492 "even from macro expansions"));
1493static llvm::cl::opt<bool>
1494DumpMacros("dM", llvm::cl::desc("Print macro definitions in -E mode instead of"
1495 " normal output"));
1496static llvm::cl::opt<bool>
1497DumpDefines("dD", llvm::cl::desc("Print macro definitions in -E mode in "
1498 "addition to normal output"));
Eli Friedmane595fe92009-05-19 03:35:57 +00001499
1500//===----------------------------------------------------------------------===//
1501// Dependency file options
1502//===----------------------------------------------------------------------===//
1503static llvm::cl::opt<std::string>
1504DependencyFile("dependency-file",
1505 llvm::cl::desc("Filename (or -) to write dependency output to"));
1506
1507static llvm::cl::opt<bool>
1508DependenciesIncludeSystemHeaders("sys-header-deps",
1509 llvm::cl::desc("Include system headers in dependency output"));
1510
1511static llvm::cl::list<std::string>
1512DependencyTargets("MT",
1513 llvm::cl::desc("Specify target for dependency"));
1514
1515// FIXME: Implement feature
1516static llvm::cl::opt<bool>
1517PhonyDependencyTarget("MP",
1518 llvm::cl::desc("Create phony target for each dependency "
1519 "(other than main file)"));
1520
Eli Friedmane2554252009-05-19 03:06:47 +00001521//===----------------------------------------------------------------------===//
Eli Friedman78a57622009-05-19 10:18:02 +00001522// Analysis options
1523//===----------------------------------------------------------------------===//
1524
1525static llvm::cl::list<Analyses>
1526AnalysisList(llvm::cl::desc("Source Code Analysis - Checks and Analyses"),
1527llvm::cl::values(
1528#define ANALYSIS(NAME, CMDFLAG, DESC, SCOPE)\
1529clEnumValN(NAME, CMDFLAG, DESC),
Eli Friedman7efefa52009-05-19 21:10:40 +00001530#include "clang/Frontend/Analyses.def"
Eli Friedman78a57622009-05-19 10:18:02 +00001531clEnumValEnd));
1532
1533static llvm::cl::opt<AnalysisStores>
1534AnalysisStoreOpt("analyzer-store",
1535 llvm::cl::desc("Source Code Analysis - Abstract Memory Store Models"),
1536 llvm::cl::init(BasicStoreModel),
1537 llvm::cl::values(
1538#define ANALYSIS_STORE(NAME, CMDFLAG, DESC, CREATFN)\
1539clEnumValN(NAME##Model, CMDFLAG, DESC),
Eli Friedman7efefa52009-05-19 21:10:40 +00001540#include "clang/Frontend/Analyses.def"
Eli Friedman78a57622009-05-19 10:18:02 +00001541clEnumValEnd));
1542
1543static llvm::cl::opt<AnalysisConstraints>
1544AnalysisConstraintsOpt("analyzer-constraints",
1545 llvm::cl::desc("Source Code Analysis - Symbolic Constraint Engines"),
1546 llvm::cl::init(RangeConstraintsModel),
1547 llvm::cl::values(
1548#define ANALYSIS_CONSTRAINTS(NAME, CMDFLAG, DESC, CREATFN)\
1549clEnumValN(NAME##Model, CMDFLAG, DESC),
Eli Friedman7efefa52009-05-19 21:10:40 +00001550#include "clang/Frontend/Analyses.def"
Eli Friedman78a57622009-05-19 10:18:02 +00001551clEnumValEnd));
1552
1553static llvm::cl::opt<AnalysisDiagClients>
1554AnalysisDiagOpt("analyzer-output",
1555 llvm::cl::desc("Source Code Analysis - Output Options"),
1556 llvm::cl::init(PD_HTML),
1557 llvm::cl::values(
1558#define ANALYSIS_DIAGNOSTICS(NAME, CMDFLAG, DESC, CREATFN, AUTOCREATE)\
1559clEnumValN(PD_##NAME, CMDFLAG, DESC),
Eli Friedman7efefa52009-05-19 21:10:40 +00001560#include "clang/Frontend/Analyses.def"
Eli Friedman78a57622009-05-19 10:18:02 +00001561clEnumValEnd));
1562
1563static llvm::cl::opt<bool>
1564VisualizeEGDot("analyzer-viz-egraph-graphviz",
1565 llvm::cl::desc("Display exploded graph using GraphViz"));
1566
1567static llvm::cl::opt<bool>
1568VisualizeEGUbi("analyzer-viz-egraph-ubigraph",
1569 llvm::cl::desc("Display exploded graph using Ubigraph"));
1570
1571static llvm::cl::opt<bool>
1572AnalyzeAll("analyzer-opt-analyze-headers",
1573 llvm::cl::desc("Force the static analyzer to analyze "
1574 "functions defined in header files"));
1575
1576static llvm::cl::opt<bool>
1577AnalyzerDisplayProgress("analyzer-display-progress",
1578 llvm::cl::desc("Emit verbose output about the analyzer's progress."));
1579
1580static llvm::cl::opt<bool>
1581PurgeDead("analyzer-purge-dead",
1582 llvm::cl::init(true),
1583 llvm::cl::desc("Remove dead symbols, bindings, and constraints before"
1584 " processing a statement."));
1585
1586static llvm::cl::opt<bool>
1587EagerlyAssume("analyzer-eagerly-assume",
1588 llvm::cl::init(false),
1589 llvm::cl::desc("Eagerly assume the truth/falseness of some "
1590 "symbolic constraints."));
1591
1592static llvm::cl::opt<std::string>
1593AnalyzeSpecificFunction("analyze-function",
1594 llvm::cl::desc("Run analysis on specific function"));
1595
1596static llvm::cl::opt<bool>
1597TrimGraph("trim-egraph",
1598 llvm::cl::desc("Only show error-related paths in the analysis graph"));
1599
1600static AnalyzerOptions ReadAnalyzerOptions() {
1601 AnalyzerOptions Opts;
1602 Opts.AnalysisList = AnalysisList;
1603 Opts.AnalysisStoreOpt = AnalysisStoreOpt;
1604 Opts.AnalysisConstraintsOpt = AnalysisConstraintsOpt;
1605 Opts.AnalysisDiagOpt = AnalysisDiagOpt;
1606 Opts.VisualizeEGDot = VisualizeEGDot;
1607 Opts.VisualizeEGUbi = VisualizeEGUbi;
1608 Opts.AnalyzeAll = AnalyzeAll;
1609 Opts.AnalyzerDisplayProgress = AnalyzerDisplayProgress;
1610 Opts.PurgeDead = PurgeDead;
1611 Opts.EagerlyAssume = EagerlyAssume;
1612 Opts.AnalyzeSpecificFunction = AnalyzeSpecificFunction;
1613 Opts.TrimGraph = TrimGraph;
1614 return Opts;
1615}
1616
1617//===----------------------------------------------------------------------===//
Chris Lattner94859302009-04-17 21:05:01 +00001618// -dump-build-information Stuff
1619//===----------------------------------------------------------------------===//
1620
1621static llvm::cl::opt<std::string>
1622DumpBuildInformation("dump-build-information",
1623 llvm::cl::value_desc("filename"),
1624 llvm::cl::desc("output a dump of some build information to a file"));
1625
1626static llvm::raw_ostream *BuildLogFile = 0;
1627
1628/// LoggingDiagnosticClient - This is a simple diagnostic client that forwards
1629/// all diagnostics to both BuildLogFile and a chained DiagnosticClient.
1630namespace {
1631class LoggingDiagnosticClient : public DiagnosticClient {
1632 llvm::OwningPtr<DiagnosticClient> Chain1;
1633 llvm::OwningPtr<DiagnosticClient> Chain2;
1634public:
1635
1636 LoggingDiagnosticClient(DiagnosticClient *Normal) {
1637 // Output diags both where requested...
1638 Chain1.reset(Normal);
1639 // .. and to our log file.
1640 Chain2.reset(new TextDiagnosticPrinter(*BuildLogFile,
1641 !NoShowColumn,
1642 !NoCaretDiagnostics,
1643 !NoShowLocation,
1644 PrintSourceRangeInfo,
Chris Lattner041bd732009-04-19 07:44:08 +00001645 PrintDiagnosticOption,
Douglas Gregora4eb3e72009-05-01 21:53:04 +00001646 !NoDiagnosticsFixIt,
Nate Begeman006f78a2009-06-25 22:43:10 +00001647 MessageLength));
Chris Lattner94859302009-04-17 21:05:01 +00001648 }
1649
1650 virtual void setLangOptions(const LangOptions *LO) {
1651 Chain1->setLangOptions(LO);
1652 Chain2->setLangOptions(LO);
1653 }
1654
1655 virtual bool IncludeInDiagnosticCounts() const {
1656 return Chain1->IncludeInDiagnosticCounts();
1657 }
1658
1659 virtual void HandleDiagnostic(Diagnostic::Level DiagLevel,
1660 const DiagnosticInfo &Info) {
1661 Chain1->HandleDiagnostic(DiagLevel, Info);
1662 Chain2->HandleDiagnostic(DiagLevel, Info);
1663 }
1664};
1665} // end anonymous namespace.
1666
1667static void SetUpBuildDumpLog(unsigned argc, char **argv,
1668 llvm::OwningPtr<DiagnosticClient> &DiagClient) {
1669
1670 std::string ErrorInfo;
1671 BuildLogFile = new llvm::raw_fd_ostream(DumpBuildInformation.c_str(), false,
1672 ErrorInfo);
1673
1674 if (!ErrorInfo.empty()) {
1675 llvm::errs() << "error opening -dump-build-information file '"
1676 << DumpBuildInformation << "', option ignored!\n";
1677 delete BuildLogFile;
1678 BuildLogFile = 0;
1679 DumpBuildInformation = "";
1680 return;
1681 }
1682
1683 (*BuildLogFile) << "clang-cc command line arguments: ";
1684 for (unsigned i = 0; i != argc; ++i)
1685 (*BuildLogFile) << argv[i] << ' ';
1686 (*BuildLogFile) << '\n';
1687
1688 // LoggingDiagnosticClient - Insert a new logging diagnostic client in between
1689 // the diagnostic producers and the normal receiver.
1690 DiagClient.reset(new LoggingDiagnosticClient(DiagClient.take()));
1691}
1692
1693
1694
1695//===----------------------------------------------------------------------===//
Chris Lattner4b009652007-07-25 00:24:17 +00001696// Main driver
1697//===----------------------------------------------------------------------===//
1698
Eli Friedmana9c310842009-05-18 22:20:00 +00001699static llvm::raw_ostream* ComputeOutFile(const std::string& InFile,
1700 const char* Extension,
1701 bool Binary,
1702 llvm::sys::Path& OutPath) {
1703 llvm::raw_ostream* Ret;
1704 bool UseStdout = false;
1705 std::string OutFile;
1706 if (OutputFile == "-" || (OutputFile.empty() && InFile == "-")) {
1707 UseStdout = true;
1708 } else if (!OutputFile.empty()) {
1709 OutFile = OutputFile;
1710 } else if (Extension) {
1711 llvm::sys::Path Path(InFile);
1712 Path.eraseSuffix();
1713 Path.appendSuffix(Extension);
1714 OutFile = Path.toString();
1715 } else {
1716 UseStdout = true;
Chris Lattner7f902922009-02-18 01:20:05 +00001717 }
Seo Sanghyeon550a1eb2007-12-24 01:52:34 +00001718
Eli Friedmana9c310842009-05-18 22:20:00 +00001719 if (UseStdout) {
1720 Ret = new llvm::raw_stdout_ostream();
1721 if (Binary)
1722 llvm::sys::Program::ChangeStdoutToBinary();
1723 } else {
1724 std::string Error;
1725 Ret = new llvm::raw_fd_ostream(OutFile.c_str(), Binary, Error);
1726 if (!Error.empty()) {
1727 // FIXME: Don't fail this way.
1728 llvm::cerr << "ERROR: " << Error << "\n";
1729 ::exit(1);
1730 }
1731 OutPath = OutFile;
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001732 }
Eli Friedmana9c310842009-05-18 22:20:00 +00001733
1734 return Ret;
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001735}
1736
Chris Lattner4b009652007-07-25 00:24:17 +00001737/// ProcessInputFile - Process a single input file with the specified state.
1738///
Ted Kremenek4e9899f2008-04-17 22:31:54 +00001739static void ProcessInputFile(Preprocessor &PP, PreprocessorFactory &PPF,
Daniel Dunbar07181d72009-05-06 03:16:41 +00001740 const std::string &InFile, ProgActions PA,
1741 const llvm::StringMap<bool> &Features) {
Eli Friedmana9c310842009-05-18 22:20:00 +00001742 llvm::OwningPtr<llvm::raw_ostream> OS;
Ted Kremenek50aab982008-08-08 02:46:37 +00001743 llvm::OwningPtr<ASTConsumer> Consumer;
Chris Lattner4b009652007-07-25 00:24:17 +00001744 bool ClearSourceMgr = false;
Douglas Gregor133d2552009-04-02 01:08:08 +00001745 FixItRewriter *FixItRewrite = 0;
Douglas Gregore0d5c562009-04-14 16:27:31 +00001746 bool CompleteTranslationUnit = true;
Eli Friedmana9c310842009-05-18 22:20:00 +00001747 llvm::sys::Path OutPath;
Douglas Gregor133d2552009-04-02 01:08:08 +00001748
Ted Kremenek71c6cc62008-10-21 00:54:44 +00001749 switch (PA) {
Chris Lattner4b009652007-07-25 00:24:17 +00001750 default:
Eli Friedmana9c310842009-05-18 22:20:00 +00001751 fprintf(stderr, "Unexpected program action!\n");
1752 HadErrors = true;
1753 return;
1754
1755 case ASTPrint:
1756 OS.reset(ComputeOutFile(InFile, 0, false, OutPath));
1757 Consumer.reset(CreateASTPrinter(OS.get()));
1758 break;
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001759
Douglas Gregor8987c032009-05-21 20:55:50 +00001760 case ASTPrintXML:
1761 OS.reset(ComputeOutFile(InFile, "xml", false, OutPath));
1762 Consumer.reset(CreateASTPrinterXML(OS.get()));
1763 break;
1764
Eli Friedmana9c310842009-05-18 22:20:00 +00001765 case ASTDump:
Douglas Gregor996677c2009-05-30 00:08:05 +00001766 Consumer.reset(CreateASTDumper());
Eli Friedmana9c310842009-05-18 22:20:00 +00001767 break;
1768
Eli Friedmana9c310842009-05-18 22:20:00 +00001769 case ASTView:
Douglas Gregor996677c2009-05-30 00:08:05 +00001770 Consumer.reset(CreateASTViewer());
Eli Friedmana9c310842009-05-18 22:20:00 +00001771 break;
1772
1773 case PrintDeclContext:
1774 Consumer.reset(CreateDeclContextPrinter());
1775 break;
1776
1777 case EmitHTML:
1778 OS.reset(ComputeOutFile(InFile, 0, true, OutPath));
1779 Consumer.reset(CreateHTMLPrinter(OS.get(), PP.getDiagnostics(), &PP, &PPF));
1780 break;
1781
1782 case InheritanceView:
1783 Consumer.reset(CreateInheritanceViewer(InheritanceViewCls));
1784 break;
1785
1786 case EmitAssembly:
1787 case EmitLLVM:
1788 case EmitBC:
1789 case EmitLLVMOnly: {
1790 BackendAction Act;
1791 if (ProgAction == EmitAssembly) {
1792 Act = Backend_EmitAssembly;
1793 OS.reset(ComputeOutFile(InFile, "s", true, OutPath));
1794 } else if (ProgAction == EmitLLVM) {
1795 Act = Backend_EmitLL;
1796 OS.reset(ComputeOutFile(InFile, "ll", true, OutPath));
1797 } else if (ProgAction == EmitLLVMOnly) {
1798 Act = Backend_EmitNothing;
1799 } else {
1800 Act = Backend_EmitBC;
1801 OS.reset(ComputeOutFile(InFile, "bc", true, OutPath));
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001802 }
Ted Kremenekd890f6a2007-12-19 22:24:34 +00001803
Eli Friedmana9c310842009-05-18 22:20:00 +00001804 CompileOptions Opts;
1805 InitializeCompileOptions(Opts, PP.getLangOptions(), Features);
1806 Consumer.reset(CreateBackendConsumer(Act, PP.getDiagnostics(),
1807 PP.getLangOptions(), Opts, InFile,
1808 OS.get()));
Ted Kremeneka36aaef2007-12-05 18:27:04 +00001809 break;
Eli Friedmana9c310842009-05-18 22:20:00 +00001810 }
1811
1812 case GeneratePCH:
1813 OS.reset(ComputeOutFile(InFile, 0, true, OutPath));
1814 Consumer.reset(CreatePCHGenerator(PP, OS.get()));
1815 CompleteTranslationUnit = false;
1816 break;
1817
1818 case RewriteObjC:
1819 OS.reset(ComputeOutFile(InFile, "cpp", true, OutPath));
Eli Friedman848763f2009-05-18 22:29:17 +00001820 Consumer.reset(CreateObjCRewriter(InFile, OS.get(), PP.getDiagnostics(),
Eli Friedman35ba7a62009-05-18 22:39:16 +00001821 PP.getLangOptions(),
1822 SilenceRewriteMacroWarning));
Eli Friedmana9c310842009-05-18 22:20:00 +00001823 break;
1824
1825 case RewriteBlocks:
1826 Consumer.reset(CreateBlockRewriter(InFile, PP.getDiagnostics(),
1827 PP.getLangOptions()));
1828 break;
1829
Eli Friedman78a57622009-05-19 10:18:02 +00001830 case RunAnalysis: {
Eli Friedmana9c310842009-05-18 22:20:00 +00001831 Consumer.reset(CreateAnalysisConsumer(PP.getDiagnostics(), &PP, &PPF,
Eli Friedman78a57622009-05-19 10:18:02 +00001832 PP.getLangOptions(), OutputFile,
1833 ReadAnalyzerOptions()));
Eli Friedmana9c310842009-05-18 22:20:00 +00001834 break;
Eli Friedman78a57622009-05-19 10:18:02 +00001835 }
Eli Friedmana9c310842009-05-18 22:20:00 +00001836
Chris Lattneraf669fb2008-10-12 05:03:36 +00001837 case DumpRawTokens: {
Chris Lattnerefe33382009-02-18 01:51:21 +00001838 llvm::TimeRegion Timer(ClangFrontendTimer);
Chris Lattneraf669fb2008-10-12 05:03:36 +00001839 SourceManager &SM = PP.getSourceManager();
Chris Lattneraf669fb2008-10-12 05:03:36 +00001840 // Start lexing the specified input file.
Chris Lattnerc7b23592009-01-17 07:35:14 +00001841 Lexer RawLex(SM.getMainFileID(), SM, PP.getLangOptions());
Chris Lattneraf669fb2008-10-12 05:03:36 +00001842 RawLex.SetKeepWhitespaceMode(true);
1843
1844 Token RawTok;
Chris Lattneraf669fb2008-10-12 05:03:36 +00001845 RawLex.LexFromRawLexer(RawTok);
1846 while (RawTok.isNot(tok::eof)) {
1847 PP.DumpToken(RawTok, true);
1848 fprintf(stderr, "\n");
1849 RawLex.LexFromRawLexer(RawTok);
1850 }
1851 ClearSourceMgr = true;
1852 break;
1853 }
Chris Lattner4b009652007-07-25 00:24:17 +00001854 case DumpTokens: { // Token dump mode.
Chris Lattnerefe33382009-02-18 01:51:21 +00001855 llvm::TimeRegion Timer(ClangFrontendTimer);
Chris Lattner4b009652007-07-25 00:24:17 +00001856 Token Tok;
Chris Lattneraf669fb2008-10-12 05:03:36 +00001857 // Start preprocessing the specified input file.
Ted Kremenek17861c52007-12-19 22:51:13 +00001858 PP.EnterMainSourceFile();
Chris Lattner4b009652007-07-25 00:24:17 +00001859 do {
1860 PP.Lex(Tok);
1861 PP.DumpToken(Tok, true);
1862 fprintf(stderr, "\n");
Chris Lattner3b494152007-10-09 18:03:42 +00001863 } while (Tok.isNot(tok::eof));
Chris Lattner4b009652007-07-25 00:24:17 +00001864 ClearSourceMgr = true;
1865 break;
1866 }
Chris Lattner270d29a2009-04-27 21:45:14 +00001867 case RunPreprocessorOnly:
Chris Lattner4b009652007-07-25 00:24:17 +00001868 break;
Ted Kremenek71c6cc62008-10-21 00:54:44 +00001869
Douglas Gregor2a0e8742009-04-02 23:43:50 +00001870 case GeneratePTH: {
Chris Lattnerefe33382009-02-18 01:51:21 +00001871 llvm::TimeRegion Timer(ClangFrontendTimer);
Eli Friedman4ae15b92009-05-19 01:02:07 +00001872 if (OutputFile.empty() || OutputFile == "-") {
1873 // FIXME: Don't fail this way.
1874 // FIXME: Verify that we can actually seek in the given file.
1875 llvm::cerr << "ERROR: PTH requires an seekable file for output!\n";
1876 ::exit(1);
1877 }
1878 OS.reset(ComputeOutFile(InFile, 0, true, OutPath));
1879 CacheTokens(PP, static_cast<llvm::raw_fd_ostream*>(OS.get()));
Ted Kremenek71c6cc62008-10-21 00:54:44 +00001880 ClearSourceMgr = true;
1881 break;
1882 }
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001883
Chris Lattner772a7c12009-04-27 22:02:30 +00001884 case PrintPreprocessedInput:
Eli Friedman4ae15b92009-05-19 01:02:07 +00001885 OS.reset(ComputeOutFile(InFile, 0, true, OutPath));
Chris Lattner4b009652007-07-25 00:24:17 +00001886 break;
Chris Lattner1665a9f2008-05-08 06:52:13 +00001887
Chris Lattner270d29a2009-04-27 21:45:14 +00001888 case ParseNoop:
Chris Lattner4b009652007-07-25 00:24:17 +00001889 break;
1890
Chris Lattnerefe33382009-02-18 01:51:21 +00001891 case ParsePrintCallbacks: {
1892 llvm::TimeRegion Timer(ClangFrontendTimer);
Eli Friedman4ae15b92009-05-19 01:02:07 +00001893 OS.reset(ComputeOutFile(InFile, 0, true, OutPath));
1894 ParseFile(PP, CreatePrintParserActionsAction(PP, OS.get()));
Chris Lattner4b009652007-07-25 00:24:17 +00001895 ClearSourceMgr = true;
1896 break;
Chris Lattnerefe33382009-02-18 01:51:21 +00001897 }
1898
1899 case ParseSyntaxOnly: { // -fsyntax-only
1900 llvm::TimeRegion Timer(ClangFrontendTimer);
Ted Kremenek50aab982008-08-08 02:46:37 +00001901 Consumer.reset(new ASTConsumer());
Ted Kremenek0a03ce62007-09-17 20:49:30 +00001902 break;
Chris Lattnerefe33382009-02-18 01:51:21 +00001903 }
Chris Lattner1665a9f2008-05-08 06:52:13 +00001904
1905 case RewriteMacros:
Eli Friedman4ae15b92009-05-19 01:02:07 +00001906 OS.reset(ComputeOutFile(InFile, 0, true, OutPath));
1907 RewriteMacrosInInput(PP, OS.get());
Chris Lattner1665a9f2008-05-08 06:52:13 +00001908 ClearSourceMgr = true;
1909 break;
Chris Lattnerc3fbf392008-10-12 05:29:20 +00001910
Eli Friedman4ae15b92009-05-19 01:02:07 +00001911 case RewriteTest:
1912 OS.reset(ComputeOutFile(InFile, 0, true, OutPath));
1913 DoRewriteTest(PP, OS.get());
Chris Lattnerc3fbf392008-10-12 05:29:20 +00001914 ClearSourceMgr = true;
1915 break;
Douglas Gregor133d2552009-04-02 01:08:08 +00001916
1917 case FixIt:
1918 llvm::TimeRegion Timer(ClangFrontendTimer);
1919 Consumer.reset(new ASTConsumer());
Douglas Gregor563a2512009-04-02 17:13:00 +00001920 FixItRewrite = new FixItRewriter(PP.getDiagnostics(),
Chris Lattnere1be6022009-04-14 23:22:57 +00001921 PP.getSourceManager(),
1922 PP.getLangOptions());
Douglas Gregor133d2552009-04-02 01:08:08 +00001923 break;
Chris Lattnerefe33382009-02-18 01:51:21 +00001924 }
Ted Kremenek88eebed2009-01-28 04:29:29 +00001925
Chris Lattner38a4f182009-04-27 21:25:27 +00001926 if (FixItAtLocations.size() > 0) {
1927 // Even without the "-fixit" flag, with may have some specific
1928 // locations where the user has requested fixes. Process those
1929 // locations now.
1930 if (!FixItRewrite)
1931 FixItRewrite = new FixItRewriter(PP.getDiagnostics(),
1932 PP.getSourceManager(),
1933 PP.getLangOptions());
Chris Lattner143fd6d2009-03-28 01:37:17 +00001934
Chris Lattner38a4f182009-04-27 21:25:27 +00001935 bool AddedFixitLocation = false;
1936 for (unsigned Idx = 0, Last = FixItAtLocations.size();
1937 Idx != Last; ++Idx) {
1938 RequestedSourceLocation Requested;
Argiris Kirtzidiseab61812009-06-23 22:01:39 +00001939 if (ResolveParsedLocation(FixItAtLocations[Idx],
1940 PP.getFileManager(), Requested)) {
Chris Lattner38a4f182009-04-27 21:25:27 +00001941 fprintf(stderr, "FIX-IT could not find file \"%s\"\n",
1942 FixItAtLocations[Idx].FileName.c_str());
1943 } else {
1944 FixItRewrite->addFixItLocation(Requested);
1945 AddedFixitLocation = true;
Douglas Gregor24b48b02009-04-02 19:05:20 +00001946 }
1947 }
1948
Chris Lattner38a4f182009-04-27 21:25:27 +00001949 if (!AddedFixitLocation) {
1950 // All of the fix-it locations were bad. Don't fix anything.
1951 delete FixItRewrite;
1952 FixItRewrite = 0;
1953 }
1954 }
1955
1956 llvm::OwningPtr<ASTContext> ContextOwner;
Chris Lattner270d29a2009-04-27 21:45:14 +00001957 if (Consumer)
Chris Lattner143fd6d2009-03-28 01:37:17 +00001958 ContextOwner.reset(new ASTContext(PP.getLangOptions(),
1959 PP.getSourceManager(),
1960 PP.getTargetInfo(),
1961 PP.getIdentifierTable(),
1962 PP.getSelectorTable(),
Chris Lattnerc46fcdd2009-06-14 01:54:56 +00001963 PP.getBuiltinInfo(),
Douglas Gregorda38c6c2009-04-22 18:49:13 +00001964 /* FreeMemory = */ !DisableFree,
Chris Lattnerc46fcdd2009-06-14 01:54:56 +00001965 /* size_reserve = */0));
1966
Chris Lattner772a7c12009-04-27 22:02:30 +00001967 llvm::OwningPtr<PCHReader> Reader;
1968 llvm::OwningPtr<ExternalASTSource> Source;
1969
Chris Lattner270d29a2009-04-27 21:45:14 +00001970 if (!ImplicitIncludePCH.empty()) {
Chris Lattner772a7c12009-04-27 22:02:30 +00001971 Reader.reset(new PCHReader(PP, ContextOwner.get()));
1972
Chris Lattner270d29a2009-04-27 21:45:14 +00001973 // The user has asked us to include a precompiled header. Load
1974 // the precompiled header into the AST context.
Chris Lattner270d29a2009-04-27 21:45:14 +00001975 switch (Reader->ReadPCH(ImplicitIncludePCH)) {
1976 case PCHReader::Success: {
Douglas Gregor32de6312009-04-28 18:58:38 +00001977 // Set the predefines buffer as suggested by the PCH
1978 // reader. Typically, the predefines buffer will be empty.
1979 PP.setPredefines(Reader->getSuggestedPredefines());
1980
Chris Lattner270d29a2009-04-27 21:45:14 +00001981 // Attach the PCH reader to the AST context as an external AST
1982 // source, so that declarations will be deserialized from the
1983 // PCH file as needed.
Chris Lattner772a7c12009-04-27 22:02:30 +00001984 if (ContextOwner) {
1985 Source.reset(Reader.take());
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001986 ContextOwner->setExternalSource(Source);
Chris Lattner772a7c12009-04-27 22:02:30 +00001987 }
Chris Lattner270d29a2009-04-27 21:45:14 +00001988 break;
Douglas Gregorc34897d2009-04-09 22:27:44 +00001989 }
1990
Chris Lattner270d29a2009-04-27 21:45:14 +00001991 case PCHReader::Failure:
1992 // Unrecoverable failure: don't even try to process the input
1993 // file.
1994 return;
1995
1996 case PCHReader::IgnorePCH:
Douglas Gregor9ea9b162009-04-28 22:01:16 +00001997 // No suitable PCH file could be found. Return an error.
1998 return;
1999
2000#if 0
2001 // FIXME: We can recover from failed attempts to load PCH
2002 // files. This code will do so, if we ever want to enable it.
2003
Chris Lattner270d29a2009-04-27 21:45:14 +00002004 // We delayed the initialization of builtins in the hope of
2005 // loading the PCH file. Since the PCH file could not be
2006 // loaded, initialize builtins now.
2007 if (ContextOwner)
2008 ContextOwner->InitializeBuiltins(PP.getIdentifierTable());
Douglas Gregor9ea9b162009-04-28 22:01:16 +00002009#endif
Chris Lattner270d29a2009-04-27 21:45:14 +00002010 }
2011
2012 // Finish preprocessor initialization. We do this now (rather
2013 // than earlier) because this initialization creates new source
2014 // location entries in the source manager, which must come after
2015 // the source location entries for the PCH file.
2016 if (InitializeSourceManager(PP, InFile))
2017 return;
Ted Kremenek88eebed2009-01-28 04:29:29 +00002018 }
Daniel Dunbar849bfc62008-10-27 22:03:52 +00002019
Chris Lattner270d29a2009-04-27 21:45:14 +00002020
2021 // If we have an ASTConsumer, run the parser with it.
2022 if (Consumer)
2023 ParseAST(PP, Consumer.get(), *ContextOwner.get(), Stats,
2024 CompleteTranslationUnit);
2025
2026 if (PA == RunPreprocessorOnly) { // Just lex as fast as we can, no output.
2027 llvm::TimeRegion Timer(ClangFrontendTimer);
2028 Token Tok;
2029 // Start parsing the specified input file.
2030 PP.EnterMainSourceFile();
2031 do {
2032 PP.Lex(Tok);
2033 } while (Tok.isNot(tok::eof));
2034 ClearSourceMgr = true;
2035 } else if (PA == ParseNoop) { // -parse-noop
2036 llvm::TimeRegion Timer(ClangFrontendTimer);
2037 ParseFile(PP, new MinimalAction(PP));
2038 ClearSourceMgr = true;
Chris Lattner772a7c12009-04-27 22:02:30 +00002039 } else if (PA == PrintPreprocessedInput){ // -E mode.
2040 llvm::TimeRegion Timer(ClangFrontendTimer);
Eli Friedmane2554252009-05-19 03:06:47 +00002041 if (DumpMacros)
2042 DoPrintMacros(PP, OS.get());
2043 else
2044 DoPrintPreprocessedInput(PP, OS.get(), EnableCommentOutput,
2045 EnableMacroCommentOutput,
2046 DisableLineMarkers, DumpDefines);
Chris Lattner772a7c12009-04-27 22:02:30 +00002047 ClearSourceMgr = true;
Chris Lattner270d29a2009-04-27 21:45:14 +00002048 }
2049
Chris Lattner38a4f182009-04-27 21:25:27 +00002050 if (FixItRewrite)
2051 FixItRewrite->WriteFixedFile(InFile, OutputFile);
2052
2053 // If in -disable-free mode, don't deallocate ASTContext.
2054 if (DisableFree)
2055 ContextOwner.take();
2056 else
2057 ContextOwner.reset(); // Delete ASTContext
Eli Friedmana9c310842009-05-18 22:20:00 +00002058
Daniel Dunbar849bfc62008-10-27 22:03:52 +00002059 if (VerifyDiagnostics)
Daniel Dunbar8d4dff52008-10-27 22:10:13 +00002060 if (CheckDiagnostics(PP))
2061 exit(1);
Chris Lattner8d72ee02008-02-06 01:42:25 +00002062
Chris Lattner4b009652007-07-25 00:24:17 +00002063 if (Stats) {
Ted Kremenekd890f6a2007-12-19 22:24:34 +00002064 fprintf(stderr, "\nSTATISTICS FOR '%s':\n", InFile.c_str());
Chris Lattner4b009652007-07-25 00:24:17 +00002065 PP.PrintStats();
2066 PP.getIdentifierTable().PrintStats();
Chris Lattner968982d2007-12-15 20:48:40 +00002067 PP.getHeaderSearchInfo().PrintStats();
Ted Kremenek40997b62009-01-09 18:20:21 +00002068 PP.getSourceManager().PrintStats();
Chris Lattner4b009652007-07-25 00:24:17 +00002069 fprintf(stderr, "\n");
2070 }
2071
2072 // For a multi-file compilation, some things are ok with nuking the source
2073 // manager tables, other require stable fileid/macroid's across multiple
2074 // files.
Chris Lattner968982d2007-12-15 20:48:40 +00002075 if (ClearSourceMgr)
2076 PP.getSourceManager().clearIDTables();
Daniel Dunbar622d6d02008-11-11 06:35:39 +00002077
2078 if (DisableFree)
2079 Consumer.take();
Eli Friedmana9c310842009-05-18 22:20:00 +00002080 else
2081 Consumer.reset();
2082
2083 // Always delete the output stream because we don't want to leak file
2084 // handles. Also, we don't want to try to erase an open file.
2085 OS.reset();
2086
2087 if ((HadErrors || (PP.getDiagnostics().getNumErrors() != 0)) &&
2088 !OutPath.isEmpty()) {
2089 // If we had errors, try to erase the output file.
2090 OutPath.eraseFromDisk();
2091 }
Chris Lattner4b009652007-07-25 00:24:17 +00002092}
2093
2094static llvm::cl::list<std::string>
2095InputFilenames(llvm::cl::Positional, llvm::cl::desc("<input files>"));
2096
Chris Lattner4b009652007-07-25 00:24:17 +00002097int main(int argc, char **argv) {
Chris Lattner4b009652007-07-25 00:24:17 +00002098 llvm::sys::PrintStackTraceOnErrorSignal();
Chris Lattner2b2d0c42009-03-04 21:41:39 +00002099 llvm::PrettyStackTraceProgram X(argc, argv);
Chris Lattnercb7dddb2009-03-06 05:38:04 +00002100 llvm::cl::ParseCommandLineOptions(argc, argv,
Chris Lattner559a7472009-03-06 05:38:25 +00002101 "LLVM 'Clang' Compiler: http://clang.llvm.org\n");
Daniel Dunbarc583b1f2009-05-28 16:37:33 +00002102
Chris Lattner4d495682009-06-17 17:25:50 +00002103 llvm::InitializeAllTargets();
2104 llvm::InitializeAllAsmPrinters();
2105
Chris Lattnerefe33382009-02-18 01:51:21 +00002106 if (TimeReport)
2107 ClangFrontendTimer = new llvm::Timer("Clang front-end time");
2108
Daniel Dunbarc583b1f2009-05-28 16:37:33 +00002109 if (Verbose)
2110 fprintf(stderr, "clang-cc version 1.0 based upon " PACKAGE_STRING
2111 " hosted on " LLVM_HOSTTRIPLE "\n");
2112
Chris Lattner4b009652007-07-25 00:24:17 +00002113 // If no input was specified, read from stdin.
2114 if (InputFilenames.empty())
2115 InputFilenames.push_back("-");
Douglas Gregor965a13c2009-05-02 00:03:46 +00002116
Ted Kremenekb240e822007-12-11 23:28:38 +00002117 // Create the diagnostic client for reporting errors or for
2118 // implementing -verify.
Chris Lattner5f7937d2009-04-17 20:40:01 +00002119 llvm::OwningPtr<DiagnosticClient> DiagClient;
2120 if (VerifyDiagnostics) {
2121 // When checking diagnostics, just buffer them up.
2122 DiagClient.reset(new TextDiagnosticBuffer());
2123 if (InputFilenames.size() != 1) {
2124 fprintf(stderr, "-verify only works on single input files for now.\n");
2125 return 1;
2126 }
2127 if (!HTMLDiag.empty()) {
2128 fprintf(stderr, "-verify and -html-diags don't work together\n");
2129 return 1;
2130 }
2131 } else if (HTMLDiag.empty()) {
Ted Kremenek5c341732008-08-07 17:49:57 +00002132 // Print diagnostics to stderr by default.
Douglas Gregor965a13c2009-05-02 00:03:46 +00002133
2134 // If -fmessage-length=N was not specified, determine whether this
2135 // is a terminal and, if so, implicitly define -fmessage-length
2136 // appropriately.
2137 if (MessageLength.getNumOccurrences() == 0)
Douglas Gregorc604d722009-05-11 18:06:49 +00002138 MessageLength.setValue(llvm::sys::Process::StandardErrColumns());
Douglas Gregor965a13c2009-05-02 00:03:46 +00002139
Edwin Törökeff37122009-06-04 07:18:23 +00002140 if (!NoColorDiagnostic) {
2141 NoColorDiagnostic.setValue(!llvm::sys::Process::StandardErrHasColors());
2142 }
2143
Chris Lattner5f7937d2009-04-17 20:40:01 +00002144 DiagClient.reset(new TextDiagnosticPrinter(llvm::errs(),
Chris Lattner92a33532008-11-19 06:56:25 +00002145 !NoShowColumn,
Chris Lattnerb96a04f2009-01-30 19:01:41 +00002146 !NoCaretDiagnostics,
Chris Lattner695a4f52009-03-13 01:08:23 +00002147 !NoShowLocation,
Chris Lattnera96ec3b2009-04-16 05:44:38 +00002148 PrintSourceRangeInfo,
Chris Lattner041bd732009-04-19 07:44:08 +00002149 PrintDiagnosticOption,
Douglas Gregora4eb3e72009-05-01 21:53:04 +00002150 !NoDiagnosticsFixIt,
Edwin Törökeff37122009-06-04 07:18:23 +00002151 MessageLength,
2152 !NoColorDiagnostic));
Ted Kremenek5c341732008-08-07 17:49:57 +00002153 } else {
Chris Lattner5f7937d2009-04-17 20:40:01 +00002154 DiagClient.reset(CreateHTMLDiagnosticClient(HTMLDiag));
Chris Lattner4b009652007-07-25 00:24:17 +00002155 }
Chris Lattner94859302009-04-17 21:05:01 +00002156
2157 if (!DumpBuildInformation.empty()) {
2158 if (!HTMLDiag.empty()) {
2159 fprintf(stderr,
2160 "-dump-build-information and -html-diags don't work together\n");
2161 return 1;
2162 }
2163
2164 SetUpBuildDumpLog(argc, argv, DiagClient);
2165 }
2166
Ted Kremenek5c341732008-08-07 17:49:57 +00002167
Chris Lattner4b009652007-07-25 00:24:17 +00002168 // Configure our handling of diagnostics.
Ted Kremenek5c341732008-08-07 17:49:57 +00002169 Diagnostic Diags(DiagClient.get());
Eli Friedman4d03d382009-05-19 01:17:04 +00002170 if (ProcessWarningOptions(Diags, OptWarnings, OptPedantic, OptPedanticErrors,
2171 OptNoWarnings))
Sebastian Redl44ff86c2009-03-06 17:41:35 +00002172 return 1;
Ted Kremenekb240e822007-12-11 23:28:38 +00002173
Chris Lattner45a56e02007-12-05 23:24:17 +00002174 // -I- is a deprecated GCC feature, scan for it and reject it.
2175 for (unsigned i = 0, e = I_dirs.size(); i != e; ++i) {
2176 if (I_dirs[i] == "-") {
Chris Lattnera1433472008-11-18 05:05:28 +00002177 Diags.Report(FullSourceLoc(), diag::err_pp_I_dash_not_supported);
Chris Lattner45a56e02007-12-05 23:24:17 +00002178 I_dirs.erase(I_dirs.begin()+i);
2179 --i;
2180 }
2181 }
Chris Lattner2c77d852008-03-14 06:12:05 +00002182
2183 // Get information about the target being compiled for.
2184 std::string Triple = CreateTargetTriple();
Ted Kremenekec6c5252008-08-07 18:13:12 +00002185 llvm::OwningPtr<TargetInfo> Target(TargetInfo::CreateTargetInfo(Triple));
2186
Chris Lattner2c77d852008-03-14 06:12:05 +00002187 if (Target == 0) {
Daniel Dunbarf45afe62009-03-12 10:14:16 +00002188 Diags.Report(FullSourceLoc(), diag::err_fe_unknown_triple)
2189 << Triple.c_str();
Sebastian Redlf10cbca2009-03-07 12:09:25 +00002190 return 1;
Chris Lattner2c77d852008-03-14 06:12:05 +00002191 }
Chris Lattner45a56e02007-12-05 23:24:17 +00002192
Daniel Dunbar9c321102009-01-20 23:17:32 +00002193 if (!InheritanceViewCls.empty()) // C++ visualization?
Ted Kremenekd9ceb3d2008-10-23 23:36:29 +00002194 ProgAction = InheritanceView;
Ted Kremenek5c341732008-08-07 17:49:57 +00002195
Ted Kremenek2a4224a2008-06-06 22:42:39 +00002196 llvm::OwningPtr<SourceManager> SourceMgr;
2197
Chris Lattnere1be6022009-04-14 23:22:57 +00002198 // Create a file manager object to provide access to and cache the filesystem.
2199 FileManager FileMgr;
Douglas Gregor6cc5d192009-04-27 18:38:38 +00002200
Daniel Dunbar07181d72009-05-06 03:16:41 +00002201 // Compute the feature set, unfortunately this effects the language!
2202 llvm::StringMap<bool> Features;
2203 ComputeFeatureMap(Target.get(), Features);
2204
Chris Lattner4b009652007-07-25 00:24:17 +00002205 for (unsigned i = 0, e = InputFilenames.size(); i != e; ++i) {
Ted Kremenekb240e822007-12-11 23:28:38 +00002206 const std::string &InFile = InputFilenames[i];
Ted Kremenekb240e822007-12-11 23:28:38 +00002207
Chris Lattner2b989562009-03-04 21:40:56 +00002208 /// Create a SourceManager object. This tracks and owns all the file
2209 /// buffers allocated to a translation unit.
2210 if (!SourceMgr)
2211 SourceMgr.reset(new SourceManager());
2212 else
2213 SourceMgr->clearIDTables();
2214
2215 // Initialize language options, inferring file types from input filenames.
2216 LangOptions LangInfo;
Chris Lattner5f7937d2009-04-17 20:40:01 +00002217 DiagClient->setLangOptions(&LangInfo);
Chris Lattnere1be6022009-04-14 23:22:57 +00002218
Chris Lattner2b989562009-03-04 21:40:56 +00002219 InitializeBaseLanguage();
2220 LangKind LK = GetLanguage(InFile);
Daniel Dunbardb6126e2009-04-01 05:09:09 +00002221 InitializeLangOptions(LangInfo, LK);
Daniel Dunbar07181d72009-05-06 03:16:41 +00002222 InitializeLanguageStandard(LangInfo, LK, Target.get(), Features);
Chris Lattner2b989562009-03-04 21:40:56 +00002223
2224 // Process the -I options and set them in the HeaderInfo.
2225 HeaderSearch HeaderInfo(FileMgr);
2226
Chris Lattnere1be6022009-04-14 23:22:57 +00002227
Chris Lattner2b989562009-03-04 21:40:56 +00002228 InitializeIncludePaths(argv[0], HeaderInfo, FileMgr, LangInfo);
2229
2230 // Set up the preprocessor with these options.
Eli Friedmane934dca2009-05-18 07:39:39 +00002231 DriverPreprocessorFactory PPFactory(Diags, LangInfo, *Target,
Chris Lattner2b989562009-03-04 21:40:56 +00002232 *SourceMgr.get(), HeaderInfo);
2233
2234 llvm::OwningPtr<Preprocessor> PP(PPFactory.CreatePreprocessor());
2235
2236 if (!PP)
2237 continue;
Ted Kremenek5c341732008-08-07 17:49:57 +00002238
Eli Friedmane595fe92009-05-19 03:35:57 +00002239 // Handle generating dependencies, if requested
2240 if (!DependencyFile.empty()) {
2241 llvm::raw_ostream *DependencyOS;
2242 if (DependencyTargets.empty()) {
2243 // FIXME: Use a proper diagnostic
2244 llvm::cerr << "-dependency-file requires at least one -MT option\n";
2245 HadErrors = true;
2246 continue;
2247 }
2248 std::string ErrStr;
2249 DependencyOS =
2250 new llvm::raw_fd_ostream(DependencyFile.c_str(), false, ErrStr);
2251 if (!ErrStr.empty()) {
2252 // FIXME: Use a proper diagnostic
2253 llvm::cerr << "unable to open dependency file: " + ErrStr;
2254 HadErrors = true;
2255 continue;
2256 }
2257
2258 AttachDependencyFileGen(PP.get(), DependencyOS, DependencyTargets,
2259 DependenciesIncludeSystemHeaders,
2260 PhonyDependencyTarget);
2261 }
2262
Chris Lattnerc46fcdd2009-06-14 01:54:56 +00002263 if (ImplicitIncludePCH.empty()) {
2264 if (InitializeSourceManager(*PP.get(), InFile))
2265 continue;
2266
2267 // Initialize builtin info.
2268 PP->getBuiltinInfo().InitializeBuiltins(PP->getIdentifierTable(),
Chris Lattnerc46fcdd2009-06-14 01:54:56 +00002269 PP->getLangOptions().NoBuiltin);
2270 }
Douglas Gregorab1cef72009-04-10 03:52:48 +00002271
Chris Lattner5f7937d2009-04-17 20:40:01 +00002272 if (!HTMLDiag.empty())
2273 ((PathDiagnosticClient*)DiagClient.get())->SetPreprocessor(PP.get());
Chris Lattner2b989562009-03-04 21:40:56 +00002274
2275 // Process the source file.
Daniel Dunbar07181d72009-05-06 03:16:41 +00002276 ProcessInputFile(*PP, PPFactory, InFile, ProgAction, Features);
Chris Lattner2b989562009-03-04 21:40:56 +00002277
Chris Lattner2961dc52009-04-17 20:16:08 +00002278 HeaderInfo.ClearFileInfo();
Chris Lattner5f7937d2009-04-17 20:40:01 +00002279 DiagClient->setLangOptions(0);
Chris Lattner4b009652007-07-25 00:24:17 +00002280 }
Chris Lattner2c77d852008-03-14 06:12:05 +00002281
Mike Stumpc4ba6cd2009-04-28 01:19:10 +00002282 if (!NoCaretDiagnostics)
2283 if (unsigned NumDiagnostics = Diags.getNumDiagnostics())
2284 fprintf(stderr, "%d diagnostic%s generated.\n", NumDiagnostics,
2285 (NumDiagnostics == 1 ? "" : "s"));
Chris Lattner4b009652007-07-25 00:24:17 +00002286
2287 if (Stats) {
Chris Lattner4b009652007-07-25 00:24:17 +00002288 FileMgr.PrintStats();
2289 fprintf(stderr, "\n");
2290 }
Chris Lattner94859302009-04-17 21:05:01 +00002291
2292 delete ClangFrontendTimer;
2293 delete BuildLogFile;
Chris Lattner4b009652007-07-25 00:24:17 +00002294
Daniel Dunbar8d4dff52008-10-27 22:10:13 +00002295 // If verifying diagnostics and we reached here, all is well.
2296 if (VerifyDiagnostics)
2297 return 0;
Chris Lattnerefe33382009-02-18 01:51:21 +00002298
Daniel Dunbarbb298c02008-10-28 00:38:08 +00002299 // Managed static deconstruction. Useful for making things like
2300 // -time-passes usable.
2301 llvm::llvm_shutdown();
2302
Daniel Dunbar70a66b12008-10-04 23:42:49 +00002303 return HadErrors || (Diags.getNumErrors() != 0);
Chris Lattner4b009652007-07-25 00:24:17 +00002304}