blob: 6a92a284020db1920af805fdfd1099bb1531029d [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- clang.cpp - C-Language Front-end ---------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This utility may be invoked in the following manner:
11// clang --help - Output help info.
12// clang [options] - Read from stdin.
13// clang [options] file - Read from "file".
14// clang [options] file1 file2 - Read these files.
15//
16//===----------------------------------------------------------------------===//
17//
18// TODO: Options to support:
19//
Chris Lattnerdddaa9c2009-02-18 01:17:01 +000020// -Wfatal-errors
Reid Spencer5f016e22007-07-11 17:01:13 +000021// -ftabstop=width
22//
23//===----------------------------------------------------------------------===//
24
Eli Friedman0ec78fa2009-05-19 21:10:40 +000025#include "clang/Frontend/AnalysisConsumer.h"
Eli Friedman8ceb0d92009-05-18 23:02:01 +000026#include "clang/Frontend/ASTConsumers.h"
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +000027#include "clang/Frontend/ASTUnit.h"
Daniel Dunbare1bd4e62009-03-02 06:16:29 +000028#include "clang/Frontend/CompileOptions.h"
Douglas Gregor558cb562009-04-02 01:08:08 +000029#include "clang/Frontend/FixItRewriter.h"
Daniel Dunbar50f4f462009-03-12 10:14:16 +000030#include "clang/Frontend/FrontendDiagnostic.h"
Daniel Dunbare1bd4e62009-03-02 06:16:29 +000031#include "clang/Frontend/InitHeaderSearch.h"
Chris Lattnere116ccf2009-04-21 05:40:52 +000032#include "clang/Frontend/InitPreprocessor.h"
Daniel Dunbar50f4f462009-03-12 10:14:16 +000033#include "clang/Frontend/PathDiagnosticClients.h"
Douglas Gregor2cf26342009-04-09 22:27:44 +000034#include "clang/Frontend/PCHReader.h"
Daniel Dunbare1bd4e62009-03-02 06:16:29 +000035#include "clang/Frontend/TextDiagnosticBuffer.h"
36#include "clang/Frontend/TextDiagnosticPrinter.h"
Argyrios Kyrtzidis34d25d82009-06-23 22:01:39 +000037#include "clang/Frontend/CommandLineSourceLoc.h"
Eli Friedmanb09f6e12009-05-19 04:14:29 +000038#include "clang/Frontend/Utils.h"
Ted Kremenek88f5cde2008-03-27 06:17:42 +000039#include "clang/Analysis/PathDiagnostic.h"
Chris Lattner8ee3c032008-02-06 02:01:47 +000040#include "clang/CodeGen/ModuleBuilder.h"
Douglas Gregor81b747b2009-09-17 21:32:03 +000041#include "clang/Sema/CodeCompleteConsumer.h"
Chris Lattnere91c1342008-02-06 00:23:21 +000042#include "clang/Sema/ParseAST.h"
Chris Lattner88eccaf2009-01-29 06:55:46 +000043#include "clang/Sema/SemaDiagnostic.h"
Chris Lattner556beb72007-09-15 22:56:56 +000044#include "clang/AST/ASTConsumer.h"
Chris Lattner1266eca2009-03-28 04:31:31 +000045#include "clang/AST/ASTContext.h"
46#include "clang/AST/Decl.h"
Chris Lattner682bf922009-03-29 16:50:03 +000047#include "clang/AST/DeclGroup.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000048#include "clang/Parse/Parser.h"
49#include "clang/Lex/HeaderSearch.h"
Chris Lattnerdb766842009-02-06 04:16:41 +000050#include "clang/Lex/LexDiagnostic.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000051#include "clang/Basic/FileManager.h"
52#include "clang/Basic/SourceManager.h"
53#include "clang/Basic/TargetInfo.h"
Daniel Dunbaraa338bc2009-05-06 04:07:06 +000054#include "clang/Basic/Version.h"
Owen Anderson42253cc2009-07-01 17:00:06 +000055#include "llvm/LLVMContext.h"
Chris Lattnerba0f25f2008-09-30 20:16:56 +000056#include "llvm/ADT/OwningPtr.h"
Chris Lattner8f3dab82007-12-15 23:20:07 +000057#include "llvm/ADT/SmallPtrSet.h"
Chris Lattnerba0f25f2008-09-30 20:16:56 +000058#include "llvm/ADT/StringExtras.h"
Daniel Dunbar868bd0a2009-05-06 03:16:41 +000059#include "llvm/ADT/StringMap.h"
Chris Lattnerb8e240e2009-04-08 18:24:34 +000060#include "llvm/ADT/STLExtras.h"
Chris Lattnerba0f25f2008-09-30 20:16:56 +000061#include "llvm/Config/config.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000062#include "llvm/Support/CommandLine.h"
Daniel Dunbar70121eb2009-08-10 03:40:28 +000063#include "llvm/Support/ErrorHandling.h"
Daniel Dunbar524b86f2008-10-28 00:38:08 +000064#include "llvm/Support/ManagedStatic.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000065#include "llvm/Support/MemoryBuffer.h"
Zhongxing Xu20922362008-11-26 05:23:17 +000066#include "llvm/Support/PluginLoader.h"
Chris Lattner09e94a32009-03-04 21:41:39 +000067#include "llvm/Support/PrettyStackTrace.h"
Chris Lattner47099742009-02-18 01:51:21 +000068#include "llvm/Support/Timer.h"
Chris Lattner0fa0daa2009-08-24 04:11:30 +000069#include "llvm/Support/raw_ostream.h"
Daniel Dunbare553a722008-10-02 01:21:33 +000070#include "llvm/System/Host.h"
Chris Lattnerdcaa0962008-03-03 03:16:03 +000071#include "llvm/System/Path.h"
Douglas Gregor44cf08e2009-05-03 03:52:38 +000072#include "llvm/System/Process.h"
Eli Friedman66d6f042009-05-18 22:20:00 +000073#include "llvm/System/Program.h"
Chris Lattnerba0f25f2008-09-30 20:16:56 +000074#include "llvm/System/Signals.h"
Chris Lattner2fe11942009-06-17 17:25:50 +000075#include "llvm/Target/TargetSelect.h"
Douglas Gregor26df2f02009-04-02 19:05:20 +000076#include <cstdlib>
Douglas Gregor44cf08e2009-05-03 03:52:38 +000077#if HAVE_SYS_TYPES_H
Douglas Gregor68a0d782009-05-02 00:03:46 +000078# include <sys/types.h>
79#endif
Douglas Gregor26df2f02009-04-02 19:05:20 +000080
Reid Spencer5f016e22007-07-11 17:01:13 +000081using namespace clang;
82
83//===----------------------------------------------------------------------===//
Douglas Gregor26df2f02009-04-02 19:05:20 +000084// Source Location Parser
85//===----------------------------------------------------------------------===//
86
Argyrios Kyrtzidis34d25d82009-06-23 22:01:39 +000087static bool ResolveParsedLocation(ParsedSourceLocation &ParsedLoc,
88 FileManager &FileMgr,
89 RequestedSourceLocation &Result) {
90 const FileEntry *File = FileMgr.getFile(ParsedLoc.FileName);
Douglas Gregor26df2f02009-04-02 19:05:20 +000091 if (!File)
92 return true;
93
94 Result.File = File;
Argyrios Kyrtzidis34d25d82009-06-23 22:01:39 +000095 Result.Line = ParsedLoc.Line;
96 Result.Column = ParsedLoc.Column;
Douglas Gregor26df2f02009-04-02 19:05:20 +000097 return false;
98}
99
Douglas Gregor26df2f02009-04-02 19:05:20 +0000100//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +0000101// Global options.
102//===----------------------------------------------------------------------===//
103
Chris Lattner47099742009-02-18 01:51:21 +0000104/// ClangFrontendTimer - The front-end activities should charge time to it with
105/// TimeRegion. The -ftime-report option controls whether this will do
106/// anything.
107llvm::Timer *ClangFrontendTimer = 0;
108
Daniel Dunbard3db4012008-10-16 16:54:18 +0000109static bool HadErrors = false;
Daniel Dunbarb0adbba2008-10-04 23:42:49 +0000110
Reid Spencer5f016e22007-07-11 17:01:13 +0000111static llvm::cl::opt<bool>
112Verbose("v", llvm::cl::desc("Enable verbose output"));
113static llvm::cl::opt<bool>
Mike Stump1eb44332009-09-09 15:08:12 +0000114Stats("print-stats",
Nate Begemanaabbb122007-12-30 01:38:50 +0000115 llvm::cl::desc("Print performance metrics and statistics"));
Daniel Dunbard3db4012008-10-16 16:54:18 +0000116static llvm::cl::opt<bool>
117DisableFree("disable-free",
118 llvm::cl::desc("Disable freeing of memory on exit"),
119 llvm::cl::init(false));
Daniel Dunbar57cbfc02009-04-27 21:19:07 +0000120static llvm::cl::opt<bool>
Mike Stump1eb44332009-09-09 15:08:12 +0000121EmptyInputOnly("empty-input-only",
Daniel Dunbar57cbfc02009-04-27 21:19:07 +0000122 llvm::cl::desc("Force running on an empty input file"));
Reid Spencer5f016e22007-07-11 17:01:13 +0000123
124enum ProgActions {
Steve Naroffb29b4272008-04-14 22:03:09 +0000125 RewriteObjC, // ObjC->C Rewriter.
Steve Naroff13188952008-09-18 14:10:13 +0000126 RewriteBlocks, // ObjC->C Rewriter for Blocks.
Chris Lattnerb57e3d42008-05-08 06:52:13 +0000127 RewriteMacros, // Expand macros but not #includes.
Chris Lattnerb13c5ee2008-10-12 05:29:20 +0000128 RewriteTest, // Rewriter playground
Douglas Gregor558cb562009-04-02 01:08:08 +0000129 FixIt, // Fix-It Rewriter
Ted Kremenek13e479b2008-03-19 07:53:42 +0000130 HTMLTest, // HTML displayer testing stuff.
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000131 EmitAssembly, // Emit a .s file.
Reid Spencer5f016e22007-07-11 17:01:13 +0000132 EmitLLVM, // Emit a .ll file.
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +0000133 EmitBC, // Emit a .bc file.
Mike Stump1eb44332009-09-09 15:08:12 +0000134 EmitLLVMOnly, // Generate LLVM IR, but do not
Ted Kremenek6a340832008-03-18 21:19:49 +0000135 EmitHTML, // Translate input source into HTML.
Chris Lattner3b427b32007-10-11 00:18:28 +0000136 ASTPrint, // Parse ASTs and print them.
Douglas Gregoree75c052009-05-21 20:55:50 +0000137 ASTPrintXML, // Parse ASTs and print them in XML.
Chris Lattner3b427b32007-10-11 00:18:28 +0000138 ASTDump, // Parse ASTs and dump them.
139 ASTView, // Parse ASTs and view them in Graphviz.
Zhongxing Xu2d75d6f2009-01-13 01:29:24 +0000140 PrintDeclContext, // Print DeclContext and their Decls.
Anders Carlsson78762eb2009-09-24 18:54:49 +0000141 DumpRecordLayouts, // Dump record layout information.
Reid Spencer5f016e22007-07-11 17:01:13 +0000142 ParsePrintCallbacks, // Parse and print each callback.
143 ParseSyntaxOnly, // Parse and perform semantic analysis.
144 ParseNoop, // Parse with noop callbacks.
145 RunPreprocessorOnly, // Just lex, no output.
146 PrintPreprocessedInput, // -E mode.
Chris Lattnerc106c102008-10-12 05:03:36 +0000147 DumpTokens, // Dump out preprocessed tokens.
148 DumpRawTokens, // Dump out raw tokens.
Mike Stump1eb44332009-09-09 15:08:12 +0000149 RunAnalysis, // Run one or more source code analyses.
Douglas Gregorbf1bd6e2009-04-02 23:43:50 +0000150 GeneratePTH, // Generate pre-tokenized header.
Douglas Gregor2cf26342009-04-09 22:27:44 +0000151 GeneratePCH, // Generate pre-compiled header.
Ted Kremenek7cae2f62008-10-23 23:36:29 +0000152 InheritanceView // View C++ inheritance for a specified class.
Reid Spencer5f016e22007-07-11 17:01:13 +0000153};
154
Mike Stump1eb44332009-09-09 15:08:12 +0000155static llvm::cl::opt<ProgActions>
Reid Spencer5f016e22007-07-11 17:01:13 +0000156ProgAction(llvm::cl::desc("Choose output type:"), llvm::cl::ZeroOrMore,
157 llvm::cl::init(ParseSyntaxOnly),
158 llvm::cl::values(
159 clEnumValN(RunPreprocessorOnly, "Eonly",
160 "Just run preprocessor, no output (for timings)"),
161 clEnumValN(PrintPreprocessedInput, "E",
162 "Run preprocessor, emit preprocessed file"),
Chris Lattnerc106c102008-10-12 05:03:36 +0000163 clEnumValN(DumpRawTokens, "dump-raw-tokens",
164 "Lex file in raw mode and dump raw tokens"),
Daniel Dunbard4270232009-01-20 23:17:32 +0000165 clEnumValN(RunAnalysis, "analyze",
166 "Run static analysis engine"),
Chris Lattnerc106c102008-10-12 05:03:36 +0000167 clEnumValN(DumpTokens, "dump-tokens",
Reid Spencer5f016e22007-07-11 17:01:13 +0000168 "Run preprocessor, dump internal rep of tokens"),
169 clEnumValN(ParseNoop, "parse-noop",
170 "Run parser with noop callbacks (for timings)"),
171 clEnumValN(ParseSyntaxOnly, "fsyntax-only",
172 "Run parser and perform semantic analysis"),
173 clEnumValN(ParsePrintCallbacks, "parse-print-callbacks",
174 "Run parser and print each callback invoked"),
Ted Kremenek6a340832008-03-18 21:19:49 +0000175 clEnumValN(EmitHTML, "emit-html",
176 "Output input source as HTML"),
Chris Lattner3b427b32007-10-11 00:18:28 +0000177 clEnumValN(ASTPrint, "ast-print",
178 "Build ASTs and then pretty-print them"),
Douglas Gregoree75c052009-05-21 20:55:50 +0000179 clEnumValN(ASTPrintXML, "ast-print-xml",
180 "Build ASTs and then print them in XML format"),
Chris Lattner3b427b32007-10-11 00:18:28 +0000181 clEnumValN(ASTDump, "ast-dump",
182 "Build ASTs and then debug dump them"),
Chris Lattnerea254db2007-10-11 00:37:43 +0000183 clEnumValN(ASTView, "ast-view",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000184 "Build ASTs and view them with GraphViz"),
Zhongxing Xu2d75d6f2009-01-13 01:29:24 +0000185 clEnumValN(PrintDeclContext, "print-decl-contexts",
Ted Kremenek08478eb2009-04-01 00:23:28 +0000186 "Print DeclContexts and their Decls"),
Anders Carlsson78762eb2009-09-24 18:54:49 +0000187 clEnumValN(DumpRecordLayouts, "dump-record-layouts",
188 "Dump record layout information"),
Douglas Gregorbf1bd6e2009-04-02 23:43:50 +0000189 clEnumValN(GeneratePTH, "emit-pth",
Ted Kremenek08478eb2009-04-01 00:23:28 +0000190 "Generate pre-tokenized header file"),
Douglas Gregor2cf26342009-04-09 22:27:44 +0000191 clEnumValN(GeneratePCH, "emit-pch",
192 "Generate pre-compiled header file"),
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000193 clEnumValN(EmitAssembly, "S",
194 "Emit native assembly code"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000195 clEnumValN(EmitLLVM, "emit-llvm",
Ted Kremenek27b07c52007-09-06 21:26:58 +0000196 "Build ASTs then convert to LLVM, emit .ll file"),
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +0000197 clEnumValN(EmitBC, "emit-llvm-bc",
198 "Build ASTs then convert to LLVM, emit .bc file"),
Daniel Dunbare8e26002009-02-26 22:39:37 +0000199 clEnumValN(EmitLLVMOnly, "emit-llvm-only",
200 "Build ASTs and convert to LLVM, discarding output"),
Chris Lattnerb13c5ee2008-10-12 05:29:20 +0000201 clEnumValN(RewriteTest, "rewrite-test",
202 "Rewriter playground"),
Steve Naroffb29b4272008-04-14 22:03:09 +0000203 clEnumValN(RewriteObjC, "rewrite-objc",
Chris Lattnerb57e3d42008-05-08 06:52:13 +0000204 "Rewrite ObjC into C (code rewriter example)"),
205 clEnumValN(RewriteMacros, "rewrite-macros",
206 "Expand macros without full preprocessing"),
Steve Naroff13188952008-09-18 14:10:13 +0000207 clEnumValN(RewriteBlocks, "rewrite-blocks",
208 "Rewrite Blocks to C"),
Douglas Gregor558cb562009-04-02 01:08:08 +0000209 clEnumValN(FixIt, "fixit",
210 "Apply fix-it advice to the input source"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000211 clEnumValEnd));
212
Ted Kremenekccc76472007-12-19 19:47:59 +0000213
214static llvm::cl::opt<std::string>
215OutputFile("o",
Ted Kremenek50b56412007-12-19 19:50:41 +0000216 llvm::cl::value_desc("path"),
Douglas Gregor370187c2009-04-22 21:45:53 +0000217 llvm::cl::desc("Specify output file"));
Ted Kremenek55af98c2008-04-14 18:40:58 +0000218
Ted Kremenekc2e72992008-12-02 19:57:31 +0000219
Douglas Gregorb657f112009-09-22 21:11:38 +0000220static llvm::cl::opt<ParsedSourceLocation>
221CodeCompletionAt("code-completion-at",
222 llvm::cl::value_desc("file:line:column"),
223 llvm::cl::desc("Dump code-completion information at a location"));
Douglas Gregor81b747b2009-09-17 21:32:03 +0000224
225/// \brief Buld a new code-completion consumer that prints the results of
226/// code completion to standard output.
227static CodeCompleteConsumer *BuildPrintingCodeCompleter(Sema &S, void *) {
228 return new PrintingCodeCompleteConsumer(S, llvm::outs());
229}
230
Ted Kremenekc2e72992008-12-02 19:57:31 +0000231//===----------------------------------------------------------------------===//
232// PTH.
233//===----------------------------------------------------------------------===//
234
235static llvm::cl::opt<std::string>
236TokenCache("token-cache", llvm::cl::value_desc("path"),
237 llvm::cl::desc("Use specified token cache file"));
238
Sanjiv Guptae8b9f5b2008-05-08 08:54:20 +0000239//===----------------------------------------------------------------------===//
Ted Kremenek55af98c2008-04-14 18:40:58 +0000240// Diagnostic Options
241//===----------------------------------------------------------------------===//
242
Ted Kremenek41193e42007-09-26 19:42:19 +0000243static llvm::cl::opt<bool>
244VerifyDiagnostics("verify",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000245 llvm::cl::desc("Verify emitted diagnostics and warnings"));
Ted Kremenek41193e42007-09-26 19:42:19 +0000246
Ted Kremenek88f5cde2008-03-27 06:17:42 +0000247static llvm::cl::opt<std::string>
248HTMLDiag("html-diags",
249 llvm::cl::desc("Generate HTML to report diagnostics"),
250 llvm::cl::value_desc("HTML directory"));
251
Nico Weberfd54ebc2008-08-05 23:33:20 +0000252static llvm::cl::opt<bool>
253NoShowColumn("fno-show-column",
254 llvm::cl::desc("Do not include column number on diagnostics"));
255
256static llvm::cl::opt<bool>
Chris Lattner65f5e642009-01-30 19:01:41 +0000257NoShowLocation("fno-show-source-location",
258 llvm::cl::desc("Do not include source location information with"
259 " diagnostics"));
260
261static llvm::cl::opt<bool>
Nico Weberfd54ebc2008-08-05 23:33:20 +0000262NoCaretDiagnostics("fno-caret-diagnostics",
263 llvm::cl::desc("Do not include source line and caret with"
264 " diagnostics"));
265
Chris Lattner1fbee5d2009-03-13 01:08:23 +0000266static llvm::cl::opt<bool>
Chris Lattneraa5bf2e2009-04-19 07:44:08 +0000267NoDiagnosticsFixIt("fno-diagnostics-fixit-info",
268 llvm::cl::desc("Do not include fixit information in"
269 " diagnostics"));
270
271static llvm::cl::opt<bool>
Chris Lattner182e0922009-04-21 05:34:31 +0000272PrintSourceRangeInfo("fdiagnostics-print-source-range-info",
273 llvm::cl::desc("Print source range spans in numeric form"));
274
Chris Lattnerd51d74a2009-04-16 05:44:38 +0000275static llvm::cl::opt<bool>
276PrintDiagnosticOption("fdiagnostics-show-option",
277 llvm::cl::desc("Print diagnostic name with mappable diagnostics"));
Nico Weberfd54ebc2008-08-05 23:33:20 +0000278
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000279static llvm::cl::opt<unsigned>
280MessageLength("fmessage-length",
Mike Stump1eb44332009-09-09 15:08:12 +0000281 llvm::cl::desc("Format message diagnostics so that they fit "
282 "within N columns or fewer, when possible."),
283 llvm::cl::value_desc("N"));
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000284
Torok Edwin603fca72009-06-04 07:18:23 +0000285static llvm::cl::opt<bool>
Torok Edwina46c71a2009-06-04 07:27:53 +0000286NoColorDiagnostic("fno-color-diagnostics",
Mike Stump1eb44332009-09-09 15:08:12 +0000287 llvm::cl::desc("Don't use colors when showing diagnostics "
Torok Edwin603fca72009-06-04 07:18:23 +0000288 "(automatically turned off if output is not a "
289 "terminal)."));
Reid Spencer5f016e22007-07-11 17:01:13 +0000290//===----------------------------------------------------------------------===//
Ted Kremenek7cae2f62008-10-23 23:36:29 +0000291// C++ Visualization.
292//===----------------------------------------------------------------------===//
293
294static llvm::cl::opt<std::string>
295InheritanceViewCls("cxx-inheritance-view",
296 llvm::cl::value_desc("class name"),
Daniel Dunbard77b2512009-01-14 18:56:36 +0000297 llvm::cl::desc("View C++ inheritance for a specified class"));
Ted Kremenek7cae2f62008-10-23 23:36:29 +0000298
299//===----------------------------------------------------------------------===//
Douglas Gregor3573c0c2009-02-14 20:49:29 +0000300// Builtin Options
301//===----------------------------------------------------------------------===//
Chris Lattnerb2509e12009-02-18 01:12:43 +0000302
303static llvm::cl::opt<bool>
304TimeReport("ftime-report",
305 llvm::cl::desc("Print the amount of time each "
306 "phase of compilation takes"));
307
Douglas Gregor3573c0c2009-02-14 20:49:29 +0000308static llvm::cl::opt<bool>
309Freestanding("ffreestanding",
Daniel Dunbaref2abfe2009-02-16 22:43:43 +0000310 llvm::cl::desc("Assert that the compilation takes place in a "
Douglas Gregor3573c0c2009-02-14 20:49:29 +0000311 "freestanding environment"));
312
Daniel Dunbaref2abfe2009-02-16 22:43:43 +0000313static llvm::cl::opt<bool>
Daniel Dunbar48d1ef72009-04-07 21:16:11 +0000314AllowBuiltins("fbuiltin", llvm::cl::init(true),
315 llvm::cl::desc("Disable implicit builtin knowledge of functions"));
Chris Lattner7644f072009-03-13 22:38:49 +0000316
317
318static llvm::cl::opt<bool>
Daniel Dunbar48d1ef72009-04-07 21:16:11 +0000319MathErrno("fmath-errno", llvm::cl::init(true),
320 llvm::cl::desc("Require math functions to respect errno"));
Daniel Dunbaref2abfe2009-02-16 22:43:43 +0000321
Douglas Gregor3573c0c2009-02-14 20:49:29 +0000322//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +0000323// Language Options
324//===----------------------------------------------------------------------===//
325
326enum LangKind {
327 langkind_unspecified,
328 langkind_c,
329 langkind_c_cpp,
Chris Lattnera778d7d2008-10-22 17:29:21 +0000330 langkind_asm_cpp,
Reid Spencer5f016e22007-07-11 17:01:13 +0000331 langkind_cxx,
332 langkind_cxx_cpp,
333 langkind_objc,
334 langkind_objc_cpp,
335 langkind_objcxx,
Nate Begeman4e3629e2009-06-25 22:43:10 +0000336 langkind_objcxx_cpp,
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +0000337 langkind_ocl,
338 langkind_ast
Reid Spencer5f016e22007-07-11 17:01:13 +0000339};
340
Reid Spencer5f016e22007-07-11 17:01:13 +0000341static llvm::cl::opt<LangKind>
342BaseLang("x", llvm::cl::desc("Base language to compile"),
343 llvm::cl::init(langkind_unspecified),
344 llvm::cl::values(clEnumValN(langkind_c, "c", "C"),
Nate Begeman4e3629e2009-06-25 22:43:10 +0000345 clEnumValN(langkind_ocl, "cl", "OpenCL C"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000346 clEnumValN(langkind_cxx, "c++", "C++"),
347 clEnumValN(langkind_objc, "objective-c", "Objective C"),
348 clEnumValN(langkind_objcxx,"objective-c++","Objective C++"),
Daniel Dunbard2ea3862009-01-29 23:50:47 +0000349 clEnumValN(langkind_c_cpp, "cpp-output",
Reid Spencer5f016e22007-07-11 17:01:13 +0000350 "Preprocessed C"),
Chris Lattnera778d7d2008-10-22 17:29:21 +0000351 clEnumValN(langkind_asm_cpp, "assembler-with-cpp",
352 "Preprocessed asm"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000353 clEnumValN(langkind_cxx_cpp, "c++-cpp-output",
Chris Lattnerc76d8072009-02-06 06:19:20 +0000354 "Preprocessed C++"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000355 clEnumValN(langkind_objc_cpp, "objective-c-cpp-output",
356 "Preprocessed Objective C"),
Chris Lattnerc76d8072009-02-06 06:19:20 +0000357 clEnumValN(langkind_objcxx_cpp, "objective-c++-cpp-output",
Reid Spencer5f016e22007-07-11 17:01:13 +0000358 "Preprocessed Objective C++"),
Daniel Dunbar0b5b0da2009-04-01 05:09:09 +0000359 clEnumValN(langkind_c, "c-header",
360 "C header"),
361 clEnumValN(langkind_objc, "objective-c-header",
362 "Objective-C header"),
363 clEnumValN(langkind_cxx, "c++-header",
364 "C++ header"),
365 clEnumValN(langkind_objcxx, "objective-c++-header",
366 "Objective-C++ header"),
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +0000367 clEnumValN(langkind_ast, "ast",
368 "Clang AST"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000369 clEnumValEnd));
370
371static llvm::cl::opt<bool>
Chris Lattner2c78b872009-04-14 23:22:57 +0000372ObjCExclusiveGC("fobjc-gc-only",
373 llvm::cl::desc("Use GC exclusively for Objective-C related "
374 "memory management"));
375
David Chisnall8a5a9aa2009-08-31 16:41:57 +0000376static llvm::cl::opt<std::string>
377ObjCConstantStringClass("fconstant-string-class",
378 llvm::cl::value_desc("class name"),
379 llvm::cl::desc("Specify the class to use for constant "
380 "Objective-C string objects."));
381
Chris Lattner2c78b872009-04-14 23:22:57 +0000382static llvm::cl::opt<bool>
383ObjCEnableGC("fobjc-gc",
384 llvm::cl::desc("Enable Objective-C garbage collection"));
385
Fariborz Jahanian448f5e62009-04-17 03:04:15 +0000386static llvm::cl::opt<bool>
387ObjCEnableGCBitmapPrint("print-ivar-layout",
388 llvm::cl::desc("Enable Objective-C Ivar layout bitmap print trace"));
389
Chris Lattner2c78b872009-04-14 23:22:57 +0000390static llvm::cl::opt<LangOptions::VisibilityMode>
391SymbolVisibility("fvisibility",
392 llvm::cl::desc("Set the default symbol visibility:"),
393 llvm::cl::init(LangOptions::Default),
394 llvm::cl::values(clEnumValN(LangOptions::Default, "default",
395 "Use default symbol visibility"),
396 clEnumValN(LangOptions::Hidden, "hidden",
397 "Use hidden symbol visibility"),
398 clEnumValN(LangOptions::Protected,"protected",
399 "Use protected symbol visibility"),
400 clEnumValEnd));
401
402static llvm::cl::opt<bool>
403OverflowChecking("ftrapv",
404 llvm::cl::desc("Trap on integer overflow"),
405 llvm::cl::init(false));
406
Fariborz Jahanian34e65772009-05-22 20:17:16 +0000407static llvm::cl::opt<bool>
Nate Begeman2ef13e52009-08-10 23:49:36 +0000408AltiVec("faltivec", llvm::cl::desc("Enable AltiVec vector initializer syntax"),
409 llvm::cl::init(false));
410
411static llvm::cl::opt<bool>
Daniel Dunbar5345c392009-09-03 04:54:28 +0000412PThread("pthread", llvm::cl::desc("Support POSIX threads in generated code"),
413 llvm::cl::init(false));
414
Daniel Dunbar13fdf282009-09-17 00:47:46 +0000415static LangKind GetLanguage(llvm::StringRef Filename) {
Ted Kremenek8904f152007-12-05 23:49:08 +0000416 if (BaseLang != langkind_unspecified)
417 return BaseLang;
Mike Stump1eb44332009-09-09 15:08:12 +0000418
Daniel Dunbar13fdf282009-09-17 00:47:46 +0000419 llvm::StringRef Ext = Filename.rsplit('.').second;
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +0000420 if (Ext == "ast")
421 return langkind_ast;
422 else if (Ext == "c")
Ted Kremenek8904f152007-12-05 23:49:08 +0000423 return langkind_c;
Daniel Dunbar9f435342009-09-17 00:47:27 +0000424 else if (Ext == "S" || Ext == "s")
Chris Lattnera778d7d2008-10-22 17:29:21 +0000425 return langkind_asm_cpp;
Ted Kremenek8904f152007-12-05 23:49:08 +0000426 else if (Ext == "i")
427 return langkind_c_cpp;
428 else if (Ext == "ii")
429 return langkind_cxx_cpp;
430 else if (Ext == "m")
431 return langkind_objc;
432 else if (Ext == "mi")
433 return langkind_objc_cpp;
434 else if (Ext == "mm" || Ext == "M")
435 return langkind_objcxx;
436 else if (Ext == "mii")
437 return langkind_objcxx_cpp;
438 else if (Ext == "C" || Ext == "cc" || Ext == "cpp" || Ext == "CPP" ||
439 Ext == "c++" || Ext == "cp" || Ext == "cxx")
440 return langkind_cxx;
Nate Begeman4e3629e2009-06-25 22:43:10 +0000441 else if (Ext == "cl")
442 return langkind_ocl;
Ted Kremenek8904f152007-12-05 23:49:08 +0000443 else
444 return langkind_c;
445}
446
447
Ted Kremenek85888962008-10-21 00:54:44 +0000448static void InitializeCOptions(LangOptions &Options) {
449 // Do nothing.
450}
451
452static void InitializeObjCOptions(LangOptions &Options) {
453 Options.ObjC1 = Options.ObjC2 = 1;
454}
Mike Stump1eb44332009-09-09 15:08:12 +0000455
Ted Kremenek85888962008-10-21 00:54:44 +0000456
Daniel Dunbar0b5b0da2009-04-01 05:09:09 +0000457static void InitializeLangOptions(LangOptions &Options, LangKind LK){
Reid Spencer5f016e22007-07-11 17:01:13 +0000458 // FIXME: implement -fpreprocessed mode.
459 bool NoPreprocess = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000460
Ted Kremenek8904f152007-12-05 23:49:08 +0000461 switch (LK) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000462 default: assert(0 && "Unknown language kind!");
Chris Lattnera778d7d2008-10-22 17:29:21 +0000463 case langkind_asm_cpp:
Daniel Dunbarc1571452008-12-01 18:55:22 +0000464 Options.AsmPreprocessor = 1;
Chris Lattnera778d7d2008-10-22 17:29:21 +0000465 // FALLTHROUGH
Reid Spencer5f016e22007-07-11 17:01:13 +0000466 case langkind_c_cpp:
467 NoPreprocess = true;
468 // FALLTHROUGH
469 case langkind_c:
Ted Kremenek85888962008-10-21 00:54:44 +0000470 InitializeCOptions(Options);
Reid Spencer5f016e22007-07-11 17:01:13 +0000471 break;
472 case langkind_cxx_cpp:
473 NoPreprocess = true;
474 // FALLTHROUGH
475 case langkind_cxx:
476 Options.CPlusPlus = 1;
477 break;
478 case langkind_objc_cpp:
479 NoPreprocess = true;
480 // FALLTHROUGH
481 case langkind_objc:
Ted Kremenek85888962008-10-21 00:54:44 +0000482 InitializeObjCOptions(Options);
Reid Spencer5f016e22007-07-11 17:01:13 +0000483 break;
484 case langkind_objcxx_cpp:
485 NoPreprocess = true;
486 // FALLTHROUGH
487 case langkind_objcxx:
488 Options.ObjC1 = Options.ObjC2 = 1;
489 Options.CPlusPlus = 1;
490 break;
Nate Begeman4e3629e2009-06-25 22:43:10 +0000491 case langkind_ocl:
492 Options.OpenCL = 1;
493 Options.AltiVec = 1;
494 Options.CXXOperatorNames = 1;
495 Options.LaxVectorConversions = 1;
496 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000497 }
Mike Stump1eb44332009-09-09 15:08:12 +0000498
Chris Lattner2c78b872009-04-14 23:22:57 +0000499 if (ObjCExclusiveGC)
500 Options.setGCMode(LangOptions::GCOnly);
501 else if (ObjCEnableGC)
502 Options.setGCMode(LangOptions::HybridGC);
Mike Stump1eb44332009-09-09 15:08:12 +0000503
Fariborz Jahanian448f5e62009-04-17 03:04:15 +0000504 if (ObjCEnableGCBitmapPrint)
505 Options.ObjCGCBitmapPrint = 1;
Mike Stump1eb44332009-09-09 15:08:12 +0000506
Nate Begeman2ef13e52009-08-10 23:49:36 +0000507 if (AltiVec)
508 Options.AltiVec = 1;
Daniel Dunbar5345c392009-09-03 04:54:28 +0000509
510 if (PThread)
511 Options.POSIXThreads = 1;
Mike Stump1eb44332009-09-09 15:08:12 +0000512
Chris Lattner2c78b872009-04-14 23:22:57 +0000513 Options.setVisibilityMode(SymbolVisibility);
514 Options.OverflowChecking = OverflowChecking;
Reid Spencer5f016e22007-07-11 17:01:13 +0000515}
516
517/// LangStds - Language standards we support.
518enum LangStds {
Mike Stump1eb44332009-09-09 15:08:12 +0000519 lang_unspecified,
Reid Spencer5f016e22007-07-11 17:01:13 +0000520 lang_c89, lang_c94, lang_c99,
Ted Kremenekea644d82008-09-03 21:22:16 +0000521 lang_gnu_START,
522 lang_gnu89 = lang_gnu_START, lang_gnu99,
Chris Lattnerd4b80f12007-07-16 04:18:29 +0000523 lang_cxx98, lang_gnucxx98,
524 lang_cxx0x, lang_gnucxx0x
Reid Spencer5f016e22007-07-11 17:01:13 +0000525};
526
527static llvm::cl::opt<LangStds>
528LangStd("std", llvm::cl::desc("Language standard to compile for"),
529 llvm::cl::init(lang_unspecified),
530 llvm::cl::values(clEnumValN(lang_c89, "c89", "ISO C 1990"),
531 clEnumValN(lang_c89, "c90", "ISO C 1990"),
532 clEnumValN(lang_c89, "iso9899:1990", "ISO C 1990"),
533 clEnumValN(lang_c94, "iso9899:199409",
534 "ISO C 1990 with amendment 1"),
535 clEnumValN(lang_c99, "c99", "ISO C 1999"),
Chris Lattner50748f42009-04-06 17:17:55 +0000536 clEnumValN(lang_c99, "c9x", "ISO C 1999"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000537 clEnumValN(lang_c99, "iso9899:1999", "ISO C 1999"),
Chris Lattner50748f42009-04-06 17:17:55 +0000538 clEnumValN(lang_c99, "iso9899:199x", "ISO C 1999"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000539 clEnumValN(lang_gnu89, "gnu89",
Gabor Greif10b26142009-02-28 09:22:15 +0000540 "ISO C 1990 with GNU extensions"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000541 clEnumValN(lang_gnu99, "gnu99",
Gabor Greif10b26142009-02-28 09:22:15 +0000542 "ISO C 1999 with GNU extensions (default for C)"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000543 clEnumValN(lang_gnu99, "gnu9x",
544 "ISO C 1999 with GNU extensions"),
545 clEnumValN(lang_cxx98, "c++98",
546 "ISO C++ 1998 with amendments"),
547 clEnumValN(lang_gnucxx98, "gnu++98",
548 "ISO C++ 1998 with amendments and GNU "
549 "extensions (default for C++)"),
Chris Lattnerd4b80f12007-07-16 04:18:29 +0000550 clEnumValN(lang_cxx0x, "c++0x",
551 "Upcoming ISO C++ 200x with amendments"),
552 clEnumValN(lang_gnucxx0x, "gnu++0x",
553 "Upcoming ISO C++ 200x with amendments and GNU "
Gabor Greif5f8d1db2009-03-11 23:07:18 +0000554 "extensions"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000555 clEnumValEnd));
556
557static llvm::cl::opt<bool>
558NoOperatorNames("fno-operator-names",
559 llvm::cl::desc("Do not treat C++ operator name keywords as "
560 "synonyms for operators"));
561
Anders Carlssonee98ac52007-10-15 02:50:23 +0000562static llvm::cl::opt<bool>
563PascalStrings("fpascal-strings",
564 llvm::cl::desc("Recognize and construct Pascal-style "
565 "string literals"));
Mike Stump1eb44332009-09-09 15:08:12 +0000566
Steve Naroffd62701b2008-02-07 03:50:06 +0000567static llvm::cl::opt<bool>
568MSExtensions("fms-extensions",
569 llvm::cl::desc("Accept some non-standard constructs used in "
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000570 "Microsoft header files "));
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000571
572static llvm::cl::opt<bool>
573WritableStrings("fwritable-strings",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000574 llvm::cl::desc("Store string literals as writable data"));
Anders Carlsson695dbb62007-11-30 04:21:22 +0000575
576static llvm::cl::opt<bool>
Anders Carlssonad53eff2009-01-30 23:26:40 +0000577NoLaxVectorConversions("fno-lax-vector-conversions",
Anders Carlssonb0f90cc2009-01-30 23:17:46 +0000578 llvm::cl::desc("Disallow implicit conversions between "
579 "vectors with a different number of "
580 "elements or different element types"));
Chris Lattnerae0ee032008-12-04 23:20:07 +0000581
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000582static llvm::cl::opt<bool>
Daniel Dunbar48d1ef72009-04-07 21:16:11 +0000583EnableBlocks("fblocks", llvm::cl::desc("enable the 'blocks' language feature"));
Mike Stumpa0f02aa2009-02-02 22:57:57 +0000584
585static llvm::cl::opt<bool>
Chris Lattner810f6d52009-03-13 17:38:01 +0000586EnableHeinousExtensions("fheinous-gnu-extensions",
587 llvm::cl::desc("enable GNU extensions that you really really shouldn't use"),
588 llvm::cl::ValueDisallowed, llvm::cl::Hidden);
589
590static llvm::cl::opt<bool>
Mike Stumpa0f02aa2009-02-02 22:57:57 +0000591ObjCNonFragileABI("fobjc-nonfragile-abi",
592 llvm::cl::desc("enable objective-c's nonfragile abi"));
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000593
Daniel Dunbard6884a02009-05-04 05:16:21 +0000594
595static llvm::cl::opt<bool>
Daniel Dunbard604c402009-02-04 21:19:06 +0000596EmitAllDecls("femit-all-decls",
597 llvm::cl::desc("Emit all declarations, even if unused"));
Ted Kremenek01d9dbf2008-04-29 04:37:03 +0000598
Daniel Dunbar6379a7a2008-08-11 17:36:14 +0000599static llvm::cl::opt<bool>
600Exceptions("fexceptions",
Chris Lattnerf5db8f82009-04-19 07:00:02 +0000601 llvm::cl::desc("Enable support for exception handling"));
Daniel Dunbar6379a7a2008-08-11 17:36:14 +0000602
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000603static llvm::cl::opt<bool>
Mike Stump738f8c22009-07-31 23:15:31 +0000604Rtti("frtti", llvm::cl::init(true),
605 llvm::cl::desc("Enable generation of rtti information"));
606
607static llvm::cl::opt<bool>
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000608GNURuntime("fgnu-runtime",
Ted Kremenek85888962008-10-21 00:54:44 +0000609 llvm::cl::desc("Generate output compatible with the standard GNU "
Chris Lattnerf5db8f82009-04-19 07:00:02 +0000610 "Objective-C runtime"));
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000611
612static llvm::cl::opt<bool>
613NeXTRuntime("fnext-runtime",
Ted Kremenek85888962008-10-21 00:54:44 +0000614 llvm::cl::desc("Generate output compatible with the NeXT "
Chris Lattnerf5db8f82009-04-19 07:00:02 +0000615 "runtime"));
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000616
Eli Friedmanc4757bd2009-06-05 07:12:17 +0000617static llvm::cl::opt<bool>
618CharIsSigned("fsigned-char",
619 llvm::cl::desc("Force char to be a signed/unsigned type"));
Ted Kremenekea644d82008-09-03 21:22:16 +0000620
621
622static llvm::cl::opt<bool>
Chris Lattnerf5db8f82009-04-19 07:00:02 +0000623Trigraphs("trigraphs", llvm::cl::desc("Process trigraph sequences"));
Ted Kremenekea644d82008-09-03 21:22:16 +0000624
Douglas Gregor26dce442009-03-10 00:06:19 +0000625static llvm::cl::opt<unsigned>
626TemplateDepth("ftemplate-depth", llvm::cl::init(99),
627 llvm::cl::desc("Maximum depth of recursive template "
628 "instantiation"));
Chris Lattnerf5db8f82009-04-19 07:00:02 +0000629static llvm::cl::opt<bool>
630DollarsInIdents("fdollars-in-identifiers",
631 llvm::cl::desc("Allow '$' in identifiers"));
Chris Lattner16167a62009-03-02 22:11:07 +0000632
Anders Carlsson4ca076f2009-04-06 17:37:10 +0000633
634static llvm::cl::opt<bool>
635OptSize("Os", llvm::cl::desc("Optimize for size"));
636
637static llvm::cl::opt<bool>
Mike Stump1eb44332009-09-09 15:08:12 +0000638DisableLLVMOptimizations("disable-llvm-optzns",
Daniel Dunbar877db382009-06-02 22:07:45 +0000639 llvm::cl::desc("Don't run LLVM optimization passes"));
640
641static llvm::cl::opt<bool>
Anders Carlsson4ca076f2009-04-06 17:37:10 +0000642NoCommon("fno-common",
643 llvm::cl::desc("Compile common globals like normal definitions"),
644 llvm::cl::ValueDisallowed);
645
Daniel Dunbarc9abc042009-04-08 05:11:16 +0000646static llvm::cl::opt<std::string>
647MainFileName("main-file-name",
648 llvm::cl::desc("Main file name to use for debug info"));
Anders Carlsson4ca076f2009-04-06 17:37:10 +0000649
Anders Carlssona33d9b42009-05-13 19:49:53 +0000650// FIXME: Also add an "-fno-access-control" option.
651static llvm::cl::opt<bool>
Mike Stump1eb44332009-09-09 15:08:12 +0000652AccessControl("faccess-control",
Anders Carlssona33d9b42009-05-13 19:49:53 +0000653 llvm::cl::desc("Enable C++ access control"));
654
Anders Carlsson92f58222009-08-22 22:30:33 +0000655static llvm::cl::opt<bool>
656NoElideConstructors("fno-elide-constructors",
657 llvm::cl::desc("Disable C++ copy constructor elision"));
658
Daniel Dunbar73b79592009-09-14 00:02:12 +0000659static llvm::cl::opt<std::string>
660TargetABI("target-abi",
661 llvm::cl::desc("Target a particular ABI type"));
662
Anders Carlsson92f58222009-08-22 22:30:33 +0000663
Anders Carlsson4ca076f2009-04-06 17:37:10 +0000664// It might be nice to add bounds to the CommandLine library directly.
665struct OptLevelParser : public llvm::cl::parser<unsigned> {
Chris Lattner59b21722009-09-20 00:39:15 +0000666 bool parse(llvm::cl::Option &O, llvm::StringRef ArgName,
667 llvm::StringRef Arg, unsigned &Val) {
Anders Carlsson4ca076f2009-04-06 17:37:10 +0000668 if (llvm::cl::parser<unsigned>::parse(O, ArgName, Arg, Val))
669 return true;
Anders Carlsson4ca076f2009-04-06 17:37:10 +0000670 if (Val > 3)
Benjamin Kramer21fde992009-08-02 12:12:11 +0000671 return O.error("'" + Arg + "' invalid optimization level!");
Anders Carlsson4ca076f2009-04-06 17:37:10 +0000672 return false;
673 }
674};
675static llvm::cl::opt<unsigned, false, OptLevelParser>
676OptLevel("O", llvm::cl::Prefix,
677 llvm::cl::desc("Optimization level"),
678 llvm::cl::init(0));
679
Daniel Dunbar9fd0b1f2009-04-08 03:03:23 +0000680static llvm::cl::opt<unsigned>
Daniel Dunbar3bbc7532009-04-08 18:03:55 +0000681PICLevel("pic-level", llvm::cl::desc("Value for __PIC__"));
682
683static llvm::cl::opt<bool>
684StaticDefine("static-define", llvm::cl::desc("Should __STATIC__ be defined"));
Daniel Dunbar9fd0b1f2009-04-08 03:03:23 +0000685
Bill Wendling45483f72009-06-28 07:36:13 +0000686static llvm::cl::opt<int>
687StackProtector("stack-protector",
688 llvm::cl::desc("Enable stack protectors"),
689 llvm::cl::init(-1));
690
Daniel Dunbardcb4a1a2008-08-23 08:43:39 +0000691static void InitializeLanguageStandard(LangOptions &Options, LangKind LK,
Daniel Dunbar868bd0a2009-05-06 03:16:41 +0000692 TargetInfo *Target,
693 const llvm::StringMap<bool> &Features) {
Chris Lattner8fc4dfb2008-12-04 22:54:33 +0000694 // Allow the target to set the default the langauge options as it sees fit.
695 Target->getDefaultLangOptions(Options);
Daniel Dunbar868bd0a2009-05-06 03:16:41 +0000696
697 // Pass the map of target features to the target for validation and
698 // processing.
699 Target->HandleTargetFeatures(Features);
Mike Stump1eb44332009-09-09 15:08:12 +0000700
Reid Spencer5f016e22007-07-11 17:01:13 +0000701 if (LangStd == lang_unspecified) {
702 // Based on the base language, pick one.
Ted Kremenek8904f152007-12-05 23:49:08 +0000703 switch (LK) {
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +0000704 case langkind_ast: assert(0 && "Invalid call for AST inputs");
Ted Kremenekf2a17b12009-03-19 19:02:20 +0000705 case lang_unspecified: assert(0 && "Unknown base language");
Nate Begeman4e3629e2009-06-25 22:43:10 +0000706 case langkind_ocl:
707 LangStd = lang_c99;
708 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000709 case langkind_c:
Chris Lattnera778d7d2008-10-22 17:29:21 +0000710 case langkind_asm_cpp:
Reid Spencer5f016e22007-07-11 17:01:13 +0000711 case langkind_c_cpp:
712 case langkind_objc:
713 case langkind_objc_cpp:
714 LangStd = lang_gnu99;
715 break;
716 case langkind_cxx:
717 case langkind_cxx_cpp:
718 case langkind_objcxx:
719 case langkind_objcxx_cpp:
720 LangStd = lang_gnucxx98;
721 break;
722 }
723 }
Mike Stump1eb44332009-09-09 15:08:12 +0000724
Reid Spencer5f016e22007-07-11 17:01:13 +0000725 switch (LangStd) {
726 default: assert(0 && "Unknown language standard!");
727
728 // Fall through from newer standards to older ones. This isn't really right.
729 // FIXME: Enable specifically the right features based on the language stds.
Chris Lattnerd4b80f12007-07-16 04:18:29 +0000730 case lang_gnucxx0x:
731 case lang_cxx0x:
732 Options.CPlusPlus0x = 1;
733 // FALL THROUGH
Reid Spencer5f016e22007-07-11 17:01:13 +0000734 case lang_gnucxx98:
735 case lang_cxx98:
736 Options.CPlusPlus = 1;
737 Options.CXXOperatorNames = !NoOperatorNames;
738 // FALL THROUGH.
739 case lang_gnu99:
740 case lang_c99:
Reid Spencer5f016e22007-07-11 17:01:13 +0000741 Options.C99 = 1;
742 Options.HexFloats = 1;
743 // FALL THROUGH.
744 case lang_gnu89:
745 Options.BCPLComment = 1; // Only for C99/C++.
746 // FALL THROUGH.
747 case lang_c94:
Chris Lattner3426b9b2008-02-25 04:01:39 +0000748 Options.Digraphs = 1; // C94, C99, C++.
749 // FALL THROUGH.
Reid Spencer5f016e22007-07-11 17:01:13 +0000750 case lang_c89:
751 break;
752 }
Argyrios Kyrtzidisd1465522008-09-11 04:21:06 +0000753
Chris Lattner7e9c90b2009-03-20 15:44:26 +0000754 // GNUMode - Set if we're in gnu99, gnu89, gnucxx98, etc.
755 Options.GNUMode = LangStd >= lang_gnu_START;
Mike Stump1eb44332009-09-09 15:08:12 +0000756
Argyrios Kyrtzidisd1465522008-09-11 04:21:06 +0000757 if (Options.CPlusPlus) {
758 Options.C99 = 0;
Eli Friedmanab24c8d2009-08-26 20:15:14 +0000759 Options.HexFloats = 0;
Argyrios Kyrtzidisd1465522008-09-11 04:21:06 +0000760 }
Mike Stump1eb44332009-09-09 15:08:12 +0000761
Chris Lattnerd658b562008-04-05 06:32:51 +0000762 if (LangStd == lang_c89 || LangStd == lang_c94 || LangStd == lang_gnu89)
763 Options.ImplicitInt = 1;
764 else
765 Options.ImplicitInt = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000766
Daniel Dunbard573d262009-04-07 22:13:21 +0000767 // Mimicing gcc's behavior, trigraphs are only enabled if -trigraphs
768 // is specified, or -std is set to a conforming mode.
Chris Lattner7e9c90b2009-03-20 15:44:26 +0000769 Options.Trigraphs = !Options.GNUMode;
Chris Lattner802db9b2008-12-05 00:10:44 +0000770 if (Trigraphs.getPosition())
Chris Lattner7e9c90b2009-03-20 15:44:26 +0000771 Options.Trigraphs = Trigraphs; // Command line option wins if specified.
Ted Kremenekea644d82008-09-03 21:22:16 +0000772
Chris Lattner802db9b2008-12-05 00:10:44 +0000773 // If in a conformant language mode (e.g. -std=c99) Blocks defaults to off
774 // even if they are normally on for the target. In GNU modes (e.g.
775 // -std=gnu99) the default for blocks depends on the target settings.
Anders Carlssone56f6ff2009-01-21 18:47:36 +0000776 // However, blocks are not turned off when compiling Obj-C or Obj-C++ code.
Chris Lattner7e9c90b2009-03-20 15:44:26 +0000777 if (!Options.ObjC1 && !Options.GNUMode)
Chris Lattner802db9b2008-12-05 00:10:44 +0000778 Options.Blocks = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000779
Chris Lattner01638a62009-04-19 07:06:52 +0000780 // Default to not accepting '$' in identifiers when preprocessing assembler,
781 // but do accept when preprocessing C. FIXME: these defaults are right for
782 // darwin, are they right everywhere?
783 Options.DollarIdents = LK != langkind_asm_cpp;
784 if (DollarsInIdents.getPosition()) // Explicit setting overrides default.
Chris Lattnerf5db8f82009-04-19 07:00:02 +0000785 Options.DollarIdents = DollarsInIdents;
Mike Stump1eb44332009-09-09 15:08:12 +0000786
Chris Lattnerae0ee032008-12-04 23:20:07 +0000787 if (PascalStrings.getPosition())
788 Options.PascalStrings = PascalStrings;
Eli Friedmanabc4e322009-06-08 06:11:14 +0000789 if (MSExtensions.getPosition())
790 Options.Microsoft = MSExtensions;
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000791 Options.WritableStrings = WritableStrings;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +0000792 if (NoLaxVectorConversions.getPosition())
793 Options.LaxVectorConversions = 0;
Daniel Dunbar6379a7a2008-08-11 17:36:14 +0000794 Options.Exceptions = Exceptions;
Mike Stump738f8c22009-07-31 23:15:31 +0000795 Options.Rtti = Rtti;
Mike Stumpa0f02aa2009-02-02 22:57:57 +0000796 if (EnableBlocks.getPosition())
Chris Lattnerae0ee032008-12-04 23:20:07 +0000797 Options.Blocks = EnableBlocks;
Eli Friedmanc4757bd2009-06-05 07:12:17 +0000798 if (CharIsSigned.getPosition())
799 Options.CharIsSigned = CharIsSigned;
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000800
Daniel Dunbar9f9768c2009-03-20 23:49:28 +0000801 if (!AllowBuiltins)
Chris Lattner7644f072009-03-13 22:38:49 +0000802 Options.NoBuiltin = 1;
Douglas Gregor3573c0c2009-02-14 20:49:29 +0000803 if (Freestanding)
Chris Lattner7644f072009-03-13 22:38:49 +0000804 Options.Freestanding = Options.NoBuiltin = 1;
Mike Stump1eb44332009-09-09 15:08:12 +0000805
Chris Lattner810f6d52009-03-13 17:38:01 +0000806 if (EnableHeinousExtensions)
807 Options.HeinousExtensions = 1;
Douglas Gregor3573c0c2009-02-14 20:49:29 +0000808
Anders Carlssona33d9b42009-05-13 19:49:53 +0000809 if (AccessControl)
810 Options.AccessControl = 1;
Mike Stump1eb44332009-09-09 15:08:12 +0000811
Anders Carlsson92f58222009-08-22 22:30:33 +0000812 Options.ElideConstructors = !NoElideConstructors;
Mike Stump1eb44332009-09-09 15:08:12 +0000813
Chris Lattnere4f21422009-06-30 01:26:17 +0000814 // OpenCL and C++ both have bool, true, false keywords.
815 Options.Bool = Options.OpenCL | Options.CPlusPlus;
Mike Stump1eb44332009-09-09 15:08:12 +0000816
Daniel Dunbaref2abfe2009-02-16 22:43:43 +0000817 Options.MathErrno = MathErrno;
818
Douglas Gregor26dce442009-03-10 00:06:19 +0000819 Options.InstantiationDepth = TemplateDepth;
820
Chris Lattner8fc4dfb2008-12-04 22:54:33 +0000821 // Override the default runtime if the user requested it.
822 if (NeXTRuntime)
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000823 Options.NeXTRuntime = 1;
Chris Lattner8fc4dfb2008-12-04 22:54:33 +0000824 else if (GNURuntime)
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000825 Options.NeXTRuntime = 0;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000826
David Chisnall8a5a9aa2009-08-31 16:41:57 +0000827 if (!ObjCConstantStringClass.empty())
828 Options.ObjCConstantStringClass = ObjCConstantStringClass.c_str();
829
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000830 if (ObjCNonFragileABI)
831 Options.ObjCNonFragileABI = 1;
Fariborz Jahanian34e65772009-05-22 20:17:16 +0000832
Daniel Dunbard604c402009-02-04 21:19:06 +0000833 if (EmitAllDecls)
834 Options.EmitAllDecls = 1;
Anders Carlsson4ca076f2009-04-06 17:37:10 +0000835
Daniel Dunbar3bbc7532009-04-08 18:03:55 +0000836 // The __OPTIMIZE_SIZE__ define is tied to -Oz, which we don't
837 // support.
838 Options.OptimizeSize = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000839
Anders Carlsson4ca076f2009-04-06 17:37:10 +0000840 // -Os implies -O2
Daniel Dunbar3bbc7532009-04-08 18:03:55 +0000841 if (OptSize || OptLevel)
Anders Carlsson4ca076f2009-04-06 17:37:10 +0000842 Options.Optimize = 1;
Daniel Dunbar9fd0b1f2009-04-08 03:03:23 +0000843
844 assert(PICLevel <= 2 && "Invalid value for -pic-level");
845 Options.PICLevel = PICLevel;
Daniel Dunbarc9abc042009-04-08 05:11:16 +0000846
Daniel Dunbar3bbc7532009-04-08 18:03:55 +0000847 Options.GNUInline = !Options.C99;
Mike Stump1eb44332009-09-09 15:08:12 +0000848 // FIXME: This is affected by other options (-fno-inline).
Daniel Dunbar3bbc7532009-04-08 18:03:55 +0000849 Options.NoInline = !OptSize && !OptLevel;
850
851 Options.Static = StaticDefine;
852
Bill Wendling4ebe3e42009-06-28 23:01:01 +0000853 switch (StackProtector) {
854 default:
855 assert(StackProtector <= 2 && "Invalid value for -stack-protector");
856 case -1: break;
857 case 0: Options.setStackProtectorMode(LangOptions::SSPOff); break;
858 case 1: Options.setStackProtectorMode(LangOptions::SSPOn); break;
859 case 2: Options.setStackProtectorMode(LangOptions::SSPReq); break;
860 }
Bill Wendling45483f72009-06-28 07:36:13 +0000861
Daniel Dunbarc9abc042009-04-08 05:11:16 +0000862 if (MainFileName.getPosition())
863 Options.setMainFileName(MainFileName.c_str());
Reid Spencer5f016e22007-07-11 17:01:13 +0000864}
865
866//===----------------------------------------------------------------------===//
Ted Kremenekae360762007-12-03 22:06:55 +0000867// Target Triple Processing.
868//===----------------------------------------------------------------------===//
869
870static llvm::cl::opt<std::string>
871TargetTriple("triple",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000872 llvm::cl::desc("Specify target triple (e.g. i686-apple-darwin9)"));
Ted Kremenekae360762007-12-03 22:06:55 +0000873
Chris Lattner42e67372008-03-05 01:18:20 +0000874static llvm::cl::opt<std::string>
Mike Stump1eb44332009-09-09 15:08:12 +0000875MacOSVersionMin("mmacosx-version-min",
Daniel Dunbar8d33cd72009-04-10 19:52:24 +0000876 llvm::cl::desc("Specify target Mac OS X version (e.g. 10.5)"));
Chris Lattner6a30c1f2008-09-30 01:13:12 +0000877
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000878// If -mmacosx-version-min=10.3.9 is specified, change the triple from being
879// something like powerpc-apple-darwin9 to powerpc-apple-darwin7
Daniel Dunbar64ffc142009-03-31 20:10:05 +0000880
881// FIXME: We should have the driver do this instead.
Chris Lattner2f60af72009-09-12 22:45:58 +0000882static void HandleMacOSVersionMin(llvm::Triple &Triple) {
883 if (Triple.getOS() != llvm::Triple::Darwin) {
Mike Stump1eb44332009-09-09 15:08:12 +0000884 fprintf(stderr,
Daniel Dunbar8d33cd72009-04-10 19:52:24 +0000885 "-mmacosx-version-min only valid for darwin (Mac OS X) targets\n");
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000886 exit(1);
887 }
Chris Lattner2f60af72009-09-12 22:45:58 +0000888
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000889 // Validate that MacOSVersionMin is a 'version number', starting with 10.[3-9]
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000890 if (MacOSVersionMin.size() < 4 ||
891 MacOSVersionMin.substr(0, 3) != "10." ||
892 !isdigit(MacOSVersionMin[3])) {
Mike Stump1eb44332009-09-09 15:08:12 +0000893 fprintf(stderr,
Daniel Dunbaraf07f932009-03-31 17:35:15 +0000894 "-mmacosx-version-min=%s is invalid, expected something like '10.4'.\n",
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000895 MacOSVersionMin.c_str());
896 exit(1);
897 }
Chris Lattner2f60af72009-09-12 22:45:58 +0000898
899 unsigned VersionNum = MacOSVersionMin[3]-'0';
900
901 if (VersionNum <= 4 && Triple.getArch() == llvm::Triple::x86_64) {
Mike Stump1eb44332009-09-09 15:08:12 +0000902 fprintf(stderr,
Chris Lattner2f60af72009-09-12 22:45:58 +0000903 "-mmacosx-version-min=%s is invalid with -arch x86_64.\n",
Fariborz Jahanian6a1284a2009-04-10 20:33:45 +0000904 MacOSVersionMin.c_str());
905 exit(1);
906 }
907
Chris Lattner2f60af72009-09-12 22:45:58 +0000908
909 llvm::SmallString<16> NewDarwinString;
910 NewDarwinString += "darwin";
911
912 // Turn MacOSVersionMin into a darwin number: e.g. 10.3.9 is 3 -> darwin7.
913 VersionNum += 4;
914 if (VersionNum > 9) {
915 NewDarwinString += '1';
916 VersionNum -= 10;
917 }
918 NewDarwinString += (VersionNum+'0');
919
920 if (MacOSVersionMin.size() == 4) {
921 // "10.4" is ok.
922 } else if (MacOSVersionMin.size() == 6 &&
923 MacOSVersionMin[4] == '.' &&
924 isdigit(MacOSVersionMin[5])) { // 10.4.7 is ok.
925 // Add the period piece (.7) to the end of the triple. This gives us
926 // something like ...-darwin8.7
927 NewDarwinString += '.';
928 NewDarwinString += MacOSVersionMin[5];
929 } else { // "10.4" is ok. 10.4x is not.
930 fprintf(stderr,
931 "-mmacosx-version-min=%s is invalid, expected something like '10.4'.\n",
932 MacOSVersionMin.c_str());
933 exit(1);
934 }
935
936 Triple.setOSName(NewDarwinString.str());
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000937}
938
Daniel Dunbar8d33cd72009-04-10 19:52:24 +0000939static llvm::cl::opt<std::string>
Mike Stump1eb44332009-09-09 15:08:12 +0000940IPhoneOSVersionMin("miphoneos-version-min",
Daniel Dunbar8d33cd72009-04-10 19:52:24 +0000941 llvm::cl::desc("Specify target iPhone OS version (e.g. 2.0)"));
942
943// If -miphoneos-version-min=2.2 is specified, change the triple from being
944// something like armv6-apple-darwin10 to armv6-apple-darwin9.2.2. We use
945// 9 as the default major Darwin number, and encode the iPhone OS version
946// number in the minor version and revision.
947
948// FIXME: We should have the driver do this instead.
Chris Lattner2f60af72009-09-12 22:45:58 +0000949static void HandleIPhoneOSVersionMin(llvm::Triple &Triple) {
950 if (Triple.getOS() != llvm::Triple::Darwin) {
Mike Stump1eb44332009-09-09 15:08:12 +0000951 fprintf(stderr,
Chris Lattner2f60af72009-09-12 22:45:58 +0000952 "-miphoneos-version-min only valid for darwin (Mac OS X) targets\n");
Daniel Dunbar8d33cd72009-04-10 19:52:24 +0000953 exit(1);
954 }
Mike Stump1eb44332009-09-09 15:08:12 +0000955
Chris Lattner2f60af72009-09-12 22:45:58 +0000956 // Validate that IPhoneOSVersionMin is a 'version number', starting with
957 // [2-9].[0-9]
958 if (IPhoneOSVersionMin.size() != 3 || !isdigit(IPhoneOSVersionMin[0]) ||
959 IPhoneOSVersionMin[1] != '.' || !isdigit(IPhoneOSVersionMin[2])) {
Mike Stump1eb44332009-09-09 15:08:12 +0000960 fprintf(stderr,
Chris Lattner2f60af72009-09-12 22:45:58 +0000961 "-miphoneos-version-min=%s is invalid, expected something like '2.0'.\n",
Daniel Dunbar8d33cd72009-04-10 19:52:24 +0000962 IPhoneOSVersionMin.c_str());
963 exit(1);
964 }
Chris Lattner2f60af72009-09-12 22:45:58 +0000965
966 // Turn IPhoneOSVersionMin into a darwin number: e.g. 2.0 is 2 -> 9.2.0
967 llvm::SmallString<16> NewDarwinString;
968 NewDarwinString += "darwin9.";
969 NewDarwinString += IPhoneOSVersionMin;
970 Triple.setOSName(NewDarwinString.str());
Daniel Dunbar8d33cd72009-04-10 19:52:24 +0000971}
972
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000973/// CreateTargetTriple - Process the various options that affect the target
974/// triple and build a final aggregate triple that we are compiling for.
Chris Lattner2f60af72009-09-12 22:45:58 +0000975static llvm::Triple CreateTargetTriple() {
Ted Kremenekae360762007-12-03 22:06:55 +0000976 // Initialize base triple. If a -triple option has been specified, use
977 // that triple. Otherwise, default to the host triple.
Chris Lattner2f60af72009-09-12 22:45:58 +0000978 llvm::Triple Triple(TargetTriple);
979 if (Triple.getTriple().empty())
980 Triple = llvm::Triple(llvm::sys::getHostTriple());
Chris Lattner6a30c1f2008-09-30 01:13:12 +0000981
982 // If -mmacosx-version-min=10.3.9 is specified, change the triple from being
983 // something like powerpc-apple-darwin9 to powerpc-apple-darwin7
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000984 if (!MacOSVersionMin.empty())
985 HandleMacOSVersionMin(Triple);
Daniel Dunbar8d33cd72009-04-10 19:52:24 +0000986 else if (!IPhoneOSVersionMin.empty())
Chris Lattner2f60af72009-09-12 22:45:58 +0000987 HandleIPhoneOSVersionMin(Triple);
Mike Stump1eb44332009-09-09 15:08:12 +0000988
Chris Lattner6a30c1f2008-09-30 01:13:12 +0000989 return Triple;
Ted Kremenekae360762007-12-03 22:06:55 +0000990}
991
992//===----------------------------------------------------------------------===//
Chris Lattnere116ccf2009-04-21 05:40:52 +0000993// SourceManager initialization.
Reid Spencer5f016e22007-07-11 17:01:13 +0000994//===----------------------------------------------------------------------===//
995
Douglas Gregore1d918e2009-04-10 23:10:45 +0000996static bool InitializeSourceManager(Preprocessor &PP,
997 const std::string &InFile) {
998 // Figure out where to get and map in the main file.
999 SourceManager &SourceMgr = PP.getSourceManager();
1000 FileManager &FileMgr = PP.getFileManager();
Daniel Dunbar57cbfc02009-04-27 21:19:07 +00001001
1002 if (EmptyInputOnly) {
1003 const char *EmptyStr = "";
Mike Stump1eb44332009-09-09 15:08:12 +00001004 llvm::MemoryBuffer *SB =
Daniel Dunbar57cbfc02009-04-27 21:19:07 +00001005 llvm::MemoryBuffer::getMemBuffer(EmptyStr, EmptyStr, "<empty input>");
1006 SourceMgr.createMainFileIDForMemBuffer(SB);
1007 } else if (InFile != "-") {
Douglas Gregore1d918e2009-04-10 23:10:45 +00001008 const FileEntry *File = FileMgr.getFile(InFile);
1009 if (File) SourceMgr.createMainFileID(File, SourceLocation());
1010 if (SourceMgr.getMainFileID().isInvalid()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001011 PP.getDiagnostics().Report(FullSourceLoc(), diag::err_fe_error_reading)
Douglas Gregore1d918e2009-04-10 23:10:45 +00001012 << InFile.c_str();
1013 return true;
1014 }
1015 } else {
1016 llvm::MemoryBuffer *SB = llvm::MemoryBuffer::getSTDIN();
1017
1018 // If stdin was empty, SB is null. Cons up an empty memory
1019 // buffer now.
1020 if (!SB) {
1021 const char *EmptyStr = "";
1022 SB = llvm::MemoryBuffer::getMemBuffer(EmptyStr, EmptyStr, "<stdin>");
1023 }
1024
1025 SourceMgr.createMainFileIDForMemBuffer(SB);
1026 if (SourceMgr.getMainFileID().isInvalid()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001027 PP.getDiagnostics().Report(FullSourceLoc(),
Douglas Gregore1d918e2009-04-10 23:10:45 +00001028 diag::err_fe_error_reading_stdin);
1029 return true;
1030 }
1031 }
1032
1033 return false;
1034}
1035
Chris Lattneraa391972008-04-19 23:09:31 +00001036
Chris Lattnere116ccf2009-04-21 05:40:52 +00001037//===----------------------------------------------------------------------===//
1038// Preprocessor Initialization
1039//===----------------------------------------------------------------------===//
Sam Bishop1102d6b2008-04-14 14:41:57 +00001040
Chris Lattnere116ccf2009-04-21 05:40:52 +00001041// FIXME: Preprocessor builtins to support.
1042// -A... - Play with #assertions
1043// -undef - Undefine all predefined macros
Chris Lattnerb31ac222009-04-08 20:15:42 +00001044
Chris Lattnere116ccf2009-04-21 05:40:52 +00001045static llvm::cl::list<std::string>
1046D_macros("D", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
1047 llvm::cl::desc("Predefine the specified macro"));
1048static llvm::cl::list<std::string>
1049U_macros("U", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
1050 llvm::cl::desc("Undefine the specified macro"));
Chris Lattnerb8e240e2009-04-08 18:24:34 +00001051
Chris Lattnere116ccf2009-04-21 05:40:52 +00001052static llvm::cl::list<std::string>
1053ImplicitIncludes("include", llvm::cl::value_desc("file"),
1054 llvm::cl::desc("Include file before parsing"));
1055static llvm::cl::list<std::string>
1056ImplicitMacroIncludes("imacros", llvm::cl::value_desc("file"),
1057 llvm::cl::desc("Include macros from file before parsing"));
Chris Lattnerb8e240e2009-04-08 18:24:34 +00001058
Chris Lattnere116ccf2009-04-21 05:40:52 +00001059static llvm::cl::opt<std::string>
1060ImplicitIncludePCH("include-pch", llvm::cl::value_desc("file"),
1061 llvm::cl::desc("Include precompiled header file"));
1062
1063static llvm::cl::opt<std::string>
1064ImplicitIncludePTH("include-pth", llvm::cl::value_desc("file"),
1065 llvm::cl::desc("Include file before parsing"));
1066
Douglas Gregore650c8c2009-07-07 00:12:59 +00001067static llvm::cl::opt<bool>
Mike Stump1eb44332009-09-09 15:08:12 +00001068RelocatablePCH("relocatable-pch",
Douglas Gregore650c8c2009-07-07 00:12:59 +00001069 llvm::cl::desc("Whether to build a relocatable precompiled "
1070 "header"));
Reid Spencer5f016e22007-07-11 17:01:13 +00001071
1072//===----------------------------------------------------------------------===//
1073// Preprocessor include path information.
1074//===----------------------------------------------------------------------===//
1075
1076// This tool exports a large number of command line options to control how the
1077// preprocessor searches for header files. At root, however, the Preprocessor
1078// object takes a very simple interface: a list of directories to search for
Mike Stump1eb44332009-09-09 15:08:12 +00001079//
Daniel Dunbarfb4ac7b2009-05-06 03:48:17 +00001080// FIXME: -nostdinc++
Chris Lattner0c946412007-08-26 17:47:35 +00001081// FIXME: -imultilib
Reid Spencer5f016e22007-07-11 17:01:13 +00001082//
Reid Spencer5f016e22007-07-11 17:01:13 +00001083
1084static llvm::cl::opt<bool>
1085nostdinc("nostdinc", llvm::cl::desc("Disable standard #include directories"));
1086
1087// Various command line options. These four add directories to each chain.
1088static llvm::cl::list<std::string>
1089F_dirs("F", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1090 llvm::cl::desc("Add directory to framework include search path"));
1091static llvm::cl::list<std::string>
1092I_dirs("I", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1093 llvm::cl::desc("Add directory to include search path"));
1094static llvm::cl::list<std::string>
1095idirafter_dirs("idirafter", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1096 llvm::cl::desc("Add directory to AFTER include search path"));
1097static llvm::cl::list<std::string>
1098iquote_dirs("iquote", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1099 llvm::cl::desc("Add directory to QUOTE include search path"));
1100static llvm::cl::list<std::string>
1101isystem_dirs("isystem", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1102 llvm::cl::desc("Add directory to SYSTEM include search path"));
1103
1104// These handle -iprefix/-iwithprefix/-iwithprefixbefore.
1105static llvm::cl::list<std::string>
1106iprefix_vals("iprefix", llvm::cl::value_desc("prefix"), llvm::cl::Prefix,
1107 llvm::cl::desc("Set the -iwithprefix/-iwithprefixbefore prefix"));
1108static llvm::cl::list<std::string>
1109iwithprefix_vals("iwithprefix", llvm::cl::value_desc("dir"), llvm::cl::Prefix,
1110 llvm::cl::desc("Set directory to SYSTEM include search path with prefix"));
1111static llvm::cl::list<std::string>
1112iwithprefixbefore_vals("iwithprefixbefore", llvm::cl::value_desc("dir"),
1113 llvm::cl::Prefix,
1114 llvm::cl::desc("Set directory to include search path with prefix"));
1115
Chris Lattner0c946412007-08-26 17:47:35 +00001116static llvm::cl::opt<std::string>
1117isysroot("isysroot", llvm::cl::value_desc("dir"), llvm::cl::init("/"),
1118 llvm::cl::desc("Set the system root directory (usually /)"));
1119
Reid Spencer5f016e22007-07-11 17:01:13 +00001120// Finally, implement the code that groks the options above.
Chris Lattner5f9eae52008-03-01 08:07:28 +00001121
Reid Spencer5f016e22007-07-11 17:01:13 +00001122/// InitializeIncludePaths - Process the -I options and set them in the
1123/// HeaderSearch object.
Nico Weber0fca0222008-08-22 09:25:22 +00001124void InitializeIncludePaths(const char *Argv0, HeaderSearch &Headers,
1125 FileManager &FM, const LangOptions &Lang) {
1126 InitHeaderSearch Init(Headers, Verbose, isysroot);
1127
Ted Kremenekf3721112008-05-31 00:27:00 +00001128 // Handle -I... and -F... options, walking the lists in parallel.
1129 unsigned Iidx = 0, Fidx = 0;
1130 while (Iidx < I_dirs.size() && Fidx < F_dirs.size()) {
1131 if (I_dirs.getPosition(Iidx) < F_dirs.getPosition(Fidx)) {
Nico Weber0fca0222008-08-22 09:25:22 +00001132 Init.AddPath(I_dirs[Iidx], InitHeaderSearch::Angled, false, true, false);
Ted Kremenekf3721112008-05-31 00:27:00 +00001133 ++Iidx;
1134 } else {
Nico Weber0fca0222008-08-22 09:25:22 +00001135 Init.AddPath(F_dirs[Fidx], InitHeaderSearch::Angled, false, true, true);
Ted Kremenekf3721112008-05-31 00:27:00 +00001136 ++Fidx;
1137 }
1138 }
Mike Stump1eb44332009-09-09 15:08:12 +00001139
Ted Kremenekf3721112008-05-31 00:27:00 +00001140 // Consume what's left from whatever list was longer.
1141 for (; Iidx != I_dirs.size(); ++Iidx)
Nico Weber0fca0222008-08-22 09:25:22 +00001142 Init.AddPath(I_dirs[Iidx], InitHeaderSearch::Angled, false, true, false);
Ted Kremenekf3721112008-05-31 00:27:00 +00001143 for (; Fidx != F_dirs.size(); ++Fidx)
Nico Weber0fca0222008-08-22 09:25:22 +00001144 Init.AddPath(F_dirs[Fidx], InitHeaderSearch::Angled, false, true, true);
Mike Stump1eb44332009-09-09 15:08:12 +00001145
Reid Spencer5f016e22007-07-11 17:01:13 +00001146 // Handle -idirafter... options.
1147 for (unsigned i = 0, e = idirafter_dirs.size(); i != e; ++i)
Nico Weber0fca0222008-08-22 09:25:22 +00001148 Init.AddPath(idirafter_dirs[i], InitHeaderSearch::After,
1149 false, true, false);
Mike Stump1eb44332009-09-09 15:08:12 +00001150
Reid Spencer5f016e22007-07-11 17:01:13 +00001151 // Handle -iquote... options.
1152 for (unsigned i = 0, e = iquote_dirs.size(); i != e; ++i)
Nico Weber0fca0222008-08-22 09:25:22 +00001153 Init.AddPath(iquote_dirs[i], InitHeaderSearch::Quoted, false, true, false);
Mike Stump1eb44332009-09-09 15:08:12 +00001154
Reid Spencer5f016e22007-07-11 17:01:13 +00001155 // Handle -isystem... options.
1156 for (unsigned i = 0, e = isystem_dirs.size(); i != e; ++i)
Nico Weber0fca0222008-08-22 09:25:22 +00001157 Init.AddPath(isystem_dirs[i], InitHeaderSearch::System, false, true, false);
Reid Spencer5f016e22007-07-11 17:01:13 +00001158
1159 // Walk the -iprefix/-iwithprefix/-iwithprefixbefore argument lists in
1160 // parallel, processing the values in order of occurance to get the right
1161 // prefixes.
1162 {
1163 std::string Prefix = ""; // FIXME: this isn't the correct default prefix.
1164 unsigned iprefix_idx = 0;
1165 unsigned iwithprefix_idx = 0;
1166 unsigned iwithprefixbefore_idx = 0;
1167 bool iprefix_done = iprefix_vals.empty();
1168 bool iwithprefix_done = iwithprefix_vals.empty();
1169 bool iwithprefixbefore_done = iwithprefixbefore_vals.empty();
1170 while (!iprefix_done || !iwithprefix_done || !iwithprefixbefore_done) {
1171 if (!iprefix_done &&
Mike Stump1eb44332009-09-09 15:08:12 +00001172 (iwithprefix_done ||
1173 iprefix_vals.getPosition(iprefix_idx) <
Reid Spencer5f016e22007-07-11 17:01:13 +00001174 iwithprefix_vals.getPosition(iwithprefix_idx)) &&
Mike Stump1eb44332009-09-09 15:08:12 +00001175 (iwithprefixbefore_done ||
1176 iprefix_vals.getPosition(iprefix_idx) <
Reid Spencer5f016e22007-07-11 17:01:13 +00001177 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
1178 Prefix = iprefix_vals[iprefix_idx];
1179 ++iprefix_idx;
1180 iprefix_done = iprefix_idx == iprefix_vals.size();
1181 } else if (!iwithprefix_done &&
Mike Stump1eb44332009-09-09 15:08:12 +00001182 (iwithprefixbefore_done ||
1183 iwithprefix_vals.getPosition(iwithprefix_idx) <
Reid Spencer5f016e22007-07-11 17:01:13 +00001184 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
Mike Stump1eb44332009-09-09 15:08:12 +00001185 Init.AddPath(Prefix+iwithprefix_vals[iwithprefix_idx],
Nico Weber0fca0222008-08-22 09:25:22 +00001186 InitHeaderSearch::System, false, false, false);
Reid Spencer5f016e22007-07-11 17:01:13 +00001187 ++iwithprefix_idx;
1188 iwithprefix_done = iwithprefix_idx == iwithprefix_vals.size();
1189 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00001190 Init.AddPath(Prefix+iwithprefixbefore_vals[iwithprefixbefore_idx],
Nico Weber0fca0222008-08-22 09:25:22 +00001191 InitHeaderSearch::Angled, false, false, false);
Reid Spencer5f016e22007-07-11 17:01:13 +00001192 ++iwithprefixbefore_idx;
Mike Stump1eb44332009-09-09 15:08:12 +00001193 iwithprefixbefore_done =
Reid Spencer5f016e22007-07-11 17:01:13 +00001194 iwithprefixbefore_idx == iwithprefixbefore_vals.size();
1195 }
1196 }
1197 }
Chris Lattner5f9eae52008-03-01 08:07:28 +00001198
Nico Weber0fca0222008-08-22 09:25:22 +00001199 Init.AddDefaultEnvVarPaths(Lang);
Chris Lattner5f9eae52008-03-01 08:07:28 +00001200
Daniel Dunbaradcf5b32009-02-21 20:52:41 +00001201 // Add the clang headers, which are relative to the clang binary.
Mike Stump1eb44332009-09-09 15:08:12 +00001202 llvm::sys::Path MainExecutablePath =
Chris Lattner985e1822008-03-03 05:57:43 +00001203 llvm::sys::Path::GetMainExecutable(Argv0,
1204 (void*)(intptr_t)InitializeIncludePaths);
Chris Lattnerdcaa0962008-03-03 03:16:03 +00001205 if (!MainExecutablePath.isEmpty()) {
1206 MainExecutablePath.eraseComponent(); // Remove /clang from foo/bin/clang
1207 MainExecutablePath.eraseComponent(); // Remove /bin from foo/bin
Daniel Dunbaradcf5b32009-02-21 20:52:41 +00001208
Mike Stump1eb44332009-09-09 15:08:12 +00001209 // Get foo/lib/clang/<version>/include
Daniel Dunbaradcf5b32009-02-21 20:52:41 +00001210 MainExecutablePath.appendComponent("lib");
1211 MainExecutablePath.appendComponent("clang");
Daniel Dunbarfb4ac7b2009-05-06 03:48:17 +00001212 MainExecutablePath.appendComponent(CLANG_VERSION_STRING);
Daniel Dunbaradcf5b32009-02-21 20:52:41 +00001213 MainExecutablePath.appendComponent("include");
Mike Stump1eb44332009-09-09 15:08:12 +00001214
Chris Lattner6858dd32009-02-19 06:48:28 +00001215 // We pass true to ignore sysroot so that we *always* look for clang headers
1216 // relative to our executable, never relative to -isysroot.
1217 Init.AddPath(MainExecutablePath.c_str(), InitHeaderSearch::System,
1218 false, false, false, true /*ignore sysroot*/);
Chris Lattnerdcaa0962008-03-03 03:16:03 +00001219 }
Mike Stump1eb44332009-09-09 15:08:12 +00001220
1221 if (!nostdinc)
Nico Weber0fca0222008-08-22 09:25:22 +00001222 Init.AddDefaultSystemIncludePaths(Lang);
Reid Spencer5f016e22007-07-11 17:01:13 +00001223
1224 // Now that we have collected all of the include paths, merge them all
1225 // together and tell the preprocessor about them.
Mike Stump1eb44332009-09-09 15:08:12 +00001226
Nico Weber0fca0222008-08-22 09:25:22 +00001227 Init.Realize();
Reid Spencer5f016e22007-07-11 17:01:13 +00001228}
1229
Mike Stump1eb44332009-09-09 15:08:12 +00001230void InitializePreprocessorInitOptions(PreprocessorInitOptions &InitOpts) {
Chris Lattnere116ccf2009-04-21 05:40:52 +00001231 // Add macros from the command line.
1232 unsigned d = 0, D = D_macros.size();
1233 unsigned u = 0, U = U_macros.size();
1234 while (d < D || u < U) {
1235 if (u == U || (d < D && D_macros.getPosition(d) < U_macros.getPosition(u)))
1236 InitOpts.addMacroDef(D_macros[d++]);
1237 else
1238 InitOpts.addMacroUndef(U_macros[u++]);
1239 }
1240
1241 // If -imacros are specified, include them now. These are processed before
1242 // any -include directives.
1243 for (unsigned i = 0, e = ImplicitMacroIncludes.size(); i != e; ++i)
1244 InitOpts.addMacroInclude(ImplicitMacroIncludes[i]);
1245
Douglas Gregorb64c1932009-05-12 01:31:05 +00001246 if (!ImplicitIncludePTH.empty() || !ImplicitIncludes.empty() ||
1247 (!ImplicitIncludePCH.empty() && ProgAction == PrintPreprocessedInput)) {
Chris Lattnere116ccf2009-04-21 05:40:52 +00001248 // We want to add these paths to the predefines buffer in order, make a
1249 // temporary vector to sort by their occurrence.
1250 llvm::SmallVector<std::pair<unsigned, std::string*>, 8> OrderedPaths;
1251
1252 if (!ImplicitIncludePTH.empty())
1253 OrderedPaths.push_back(std::make_pair(ImplicitIncludePTH.getPosition(),
1254 &ImplicitIncludePTH));
Douglas Gregorb64c1932009-05-12 01:31:05 +00001255 if (!ImplicitIncludePCH.empty() && ProgAction == PrintPreprocessedInput)
1256 OrderedPaths.push_back(std::make_pair(ImplicitIncludePCH.getPosition(),
1257 &ImplicitIncludePCH));
Chris Lattnere116ccf2009-04-21 05:40:52 +00001258 for (unsigned i = 0, e = ImplicitIncludes.size(); i != e; ++i)
1259 OrderedPaths.push_back(std::make_pair(ImplicitIncludes.getPosition(i),
1260 &ImplicitIncludes[i]));
1261 llvm::array_pod_sort(OrderedPaths.begin(), OrderedPaths.end());
1262
1263
1264 // Now that they are ordered by position, add to the predefines buffer.
1265 for (unsigned i = 0, e = OrderedPaths.size(); i != e; ++i) {
1266 std::string *Ptr = OrderedPaths[i].second;
1267 if (!ImplicitIncludes.empty() &&
1268 Ptr >= &ImplicitIncludes[0] &&
1269 Ptr <= &ImplicitIncludes[ImplicitIncludes.size()-1]) {
1270 InitOpts.addInclude(*Ptr, false);
Douglas Gregorb64c1932009-05-12 01:31:05 +00001271 } else if (Ptr == &ImplicitIncludePTH) {
Chris Lattnere116ccf2009-04-21 05:40:52 +00001272 InitOpts.addInclude(*Ptr, true);
Douglas Gregorb64c1932009-05-12 01:31:05 +00001273 } else {
1274 // We end up here when we're producing preprocessed output and
1275 // we loaded a PCH file. In this case, just include the header
1276 // file that was used to build the precompiled header.
1277 assert(Ptr == &ImplicitIncludePCH);
1278 std::string OriginalFile = PCHReader::getOriginalSourceFile(*Ptr);
1279 if (!OriginalFile.empty()) {
1280 InitOpts.addInclude(OriginalFile, false);
1281 ImplicitIncludePCH.clear();
1282 }
Chris Lattnere116ccf2009-04-21 05:40:52 +00001283 }
1284 }
1285 }
1286}
1287
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001288//===----------------------------------------------------------------------===//
1289// Driver PreprocessorFactory - For lazily generating preprocessors ...
1290//===----------------------------------------------------------------------===//
1291
1292namespace {
1293class VISIBILITY_HIDDEN DriverPreprocessorFactory : public PreprocessorFactory {
1294 Diagnostic &Diags;
1295 const LangOptions &LangInfo;
1296 TargetInfo &Target;
1297 SourceManager &SourceMgr;
1298 HeaderSearch &HeaderInfo;
Mike Stump1eb44332009-09-09 15:08:12 +00001299
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001300public:
Eli Friedmanf086e3b2009-05-18 07:39:39 +00001301 DriverPreprocessorFactory(Diagnostic &diags, const LangOptions &opts,
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001302 TargetInfo &target, SourceManager &SM,
Mike Stump1eb44332009-09-09 15:08:12 +00001303 HeaderSearch &Headers)
Eli Friedmanf086e3b2009-05-18 07:39:39 +00001304 : Diags(diags), LangInfo(opts), Target(target),
Douglas Gregore1d918e2009-04-10 23:10:45 +00001305 SourceMgr(SM), HeaderInfo(Headers) {}
Mike Stump1eb44332009-09-09 15:08:12 +00001306
1307
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001308 virtual ~DriverPreprocessorFactory() {}
Mike Stump1eb44332009-09-09 15:08:12 +00001309
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001310 virtual Preprocessor* CreatePreprocessor() {
Ted Kremenek72b1b152009-01-15 18:47:46 +00001311 llvm::OwningPtr<PTHManager> PTHMgr;
1312
Ted Kremenek748d5d62009-03-20 00:26:38 +00001313 if (!TokenCache.empty() && !ImplicitIncludePTH.empty()) {
1314 fprintf(stderr, "error: cannot use both -token-cache and -include-pth "
1315 "options\n");
Ted Kremenek22f0d092009-03-22 06:42:39 +00001316 exit(1);
Ted Kremenek748d5d62009-03-20 00:26:38 +00001317 }
Mike Stump1eb44332009-09-09 15:08:12 +00001318
Ted Kremenek72b1b152009-01-15 18:47:46 +00001319 // Use PTH?
Ted Kremenek748d5d62009-03-20 00:26:38 +00001320 if (!TokenCache.empty() || !ImplicitIncludePTH.empty()) {
1321 const std::string& x = TokenCache.empty() ? ImplicitIncludePTH:TokenCache;
Mike Stump1eb44332009-09-09 15:08:12 +00001322 PTHMgr.reset(PTHManager::Create(x, &Diags,
Ted Kremenek22f0d092009-03-22 06:42:39 +00001323 TokenCache.empty() ? Diagnostic::Error
1324 : Diagnostic::Warning));
Ted Kremenek748d5d62009-03-20 00:26:38 +00001325 }
Mike Stump1eb44332009-09-09 15:08:12 +00001326
Ted Kremenek22f0d092009-03-22 06:42:39 +00001327 if (Diags.hasErrorOccurred())
1328 exit(1);
Mike Stump1eb44332009-09-09 15:08:12 +00001329
Ted Kremenek72b1b152009-01-15 18:47:46 +00001330 // Create the Preprocessor.
1331 llvm::OwningPtr<Preprocessor> PP(new Preprocessor(Diags, LangInfo, Target,
1332 SourceMgr, HeaderInfo,
1333 PTHMgr.get()));
Mike Stump1eb44332009-09-09 15:08:12 +00001334
Ted Kremenek72b1b152009-01-15 18:47:46 +00001335 // Note that this is different then passing PTHMgr to Preprocessor's ctor.
1336 // That argument is used as the IdentifierInfoLookup argument to
1337 // IdentifierTable's ctor.
1338 if (PTHMgr) {
1339 PTHMgr->setPreprocessor(PP.get());
1340 PP->setPTHManager(PTHMgr.take());
1341 }
Douglas Gregor14f79002009-04-10 03:52:48 +00001342
Chris Lattnere116ccf2009-04-21 05:40:52 +00001343 PreprocessorInitOptions InitOpts;
1344 InitializePreprocessorInitOptions(InitOpts);
Eli Friedmanf086e3b2009-05-18 07:39:39 +00001345 if (InitializePreprocessor(*PP, InitOpts))
Douglas Gregore1d918e2009-04-10 23:10:45 +00001346 return 0;
Chris Lattnere116ccf2009-04-21 05:40:52 +00001347
Douglas Gregore1d918e2009-04-10 23:10:45 +00001348 return PP.take();
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001349 }
1350};
1351}
Reid Spencer5f016e22007-07-11 17:01:13 +00001352
Reid Spencer5f016e22007-07-11 17:01:13 +00001353//===----------------------------------------------------------------------===//
1354// Basic Parser driver
1355//===----------------------------------------------------------------------===//
1356
Chris Lattner51574ea2008-04-19 23:25:44 +00001357static void ParseFile(Preprocessor &PP, MinimalAction *PA) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001358 Parser P(PP, *PA);
Ted Kremenek95041a22007-12-19 22:51:13 +00001359 PP.EnterMainSourceFile();
Mike Stump1eb44332009-09-09 15:08:12 +00001360
Reid Spencer5f016e22007-07-11 17:01:13 +00001361 // Parsing the specified input file.
1362 P.ParseTranslationUnit();
1363 delete PA;
1364}
1365
1366//===----------------------------------------------------------------------===//
Daniel Dunbar70f92432008-10-23 05:50:47 +00001367// Code generation options
1368//===----------------------------------------------------------------------===//
1369
1370static llvm::cl::opt<bool>
Chris Lattner15104882009-03-09 22:05:03 +00001371GenerateDebugInfo("g",
1372 llvm::cl::desc("Generate source level debug information"));
1373
Daniel Dunbara034ba82009-02-17 19:47:34 +00001374static llvm::cl::opt<std::string>
1375TargetCPU("mcpu",
1376 llvm::cl::desc("Target a specific cpu type (-mcpu=help for details)"));
1377
Daniel Dunbar868bd0a2009-05-06 03:16:41 +00001378static llvm::cl::list<std::string>
1379TargetFeatures("target-feature", llvm::cl::desc("Target specific attributes"));
1380
Devang Patel24095da2009-06-04 23:32:02 +00001381
1382static llvm::cl::opt<bool>
1383DisableRedZone("disable-red-zone",
1384 llvm::cl::desc("Do not emit code that uses the red zone."),
1385 llvm::cl::init(false));
1386
Devang Patelacebb392009-06-05 22:05:48 +00001387static llvm::cl::opt<bool>
1388NoImplicitFloat("no-implicit-float",
1389 llvm::cl::desc("Don't generate implicit floating point instructions (x86-only)"),
1390 llvm::cl::init(false));
1391
Daniel Dunbar868bd0a2009-05-06 03:16:41 +00001392/// ComputeTargetFeatures - Recompute the target feature list to only
1393/// be the list of things that are enabled, based on the target cpu
1394/// and feature list.
1395static void ComputeFeatureMap(TargetInfo *Target,
1396 llvm::StringMap<bool> &Features) {
Mike Stump1eb44332009-09-09 15:08:12 +00001397 assert(Features.empty() && "invalid map");
Daniel Dunbar868bd0a2009-05-06 03:16:41 +00001398
1399 // Initialize the feature map based on the target.
1400 Target->getDefaultFeatures(TargetCPU, Features);
1401
1402 // Apply the user specified deltas.
Mike Stump1eb44332009-09-09 15:08:12 +00001403 for (llvm::cl::list<std::string>::iterator it = TargetFeatures.begin(),
Daniel Dunbar868bd0a2009-05-06 03:16:41 +00001404 ie = TargetFeatures.end(); it != ie; ++it) {
1405 const char *Name = it->c_str();
Mike Stump1eb44332009-09-09 15:08:12 +00001406
Daniel Dunbar868bd0a2009-05-06 03:16:41 +00001407 // FIXME: Don't handle errors like this.
1408 if (Name[0] != '-' && Name[0] != '+') {
Mike Stump1eb44332009-09-09 15:08:12 +00001409 fprintf(stderr, "error: clang-cc: invalid target feature string: %s\n",
Daniel Dunbar868bd0a2009-05-06 03:16:41 +00001410 Name);
1411 exit(1);
1412 }
Daniel Dunbar17ca3632009-05-06 21:07:50 +00001413 if (!Target->setFeatureEnabled(Features, Name + 1, (Name[0] == '+'))) {
Mike Stump1eb44332009-09-09 15:08:12 +00001414 fprintf(stderr, "error: clang-cc: invalid target feature name: %s\n",
Daniel Dunbar17ca3632009-05-06 21:07:50 +00001415 Name + 1);
Daniel Dunbar868bd0a2009-05-06 03:16:41 +00001416 exit(1);
1417 }
Daniel Dunbar868bd0a2009-05-06 03:16:41 +00001418 }
1419}
1420
Chris Lattner7afae712009-03-16 18:41:18 +00001421static void InitializeCompileOptions(CompileOptions &Opts,
Daniel Dunbar868bd0a2009-05-06 03:16:41 +00001422 const LangOptions &LangOpts,
1423 const llvm::StringMap<bool> &Features) {
Daniel Dunbar70f92432008-10-23 05:50:47 +00001424 Opts.OptimizeSize = OptSize;
Chris Lattner20126042009-03-09 22:00:34 +00001425 Opts.DebugInfo = GenerateDebugInfo;
Daniel Dunbar877db382009-06-02 22:07:45 +00001426
1427 if (DisableLLVMOptimizations) {
1428 Opts.OptimizationLevel = 0;
1429 Opts.Inlining = CompileOptions::NoInlining;
Daniel Dunbarac7ffe02008-10-29 07:56:11 +00001430 } else {
Daniel Dunbar877db382009-06-02 22:07:45 +00001431 if (OptSize) {
1432 // -Os implies -O2
1433 Opts.OptimizationLevel = 2;
1434 } else {
1435 Opts.OptimizationLevel = OptLevel;
1436 }
1437
1438 // We must always run at least the always inlining pass.
1439 if (Opts.OptimizationLevel > 1)
1440 Opts.Inlining = CompileOptions::NormalInlining;
1441 else
1442 Opts.Inlining = CompileOptions::OnlyAlwaysInlining;
Daniel Dunbarac7ffe02008-10-29 07:56:11 +00001443 }
Daniel Dunbar8e8f3b72008-10-29 03:42:18 +00001444
1445 // FIXME: There are llvm-gcc options to control these selectively.
Daniel Dunbar8e8f3b72008-10-29 03:42:18 +00001446 Opts.UnrollLoops = (Opts.OptimizationLevel > 1 && !OptSize);
Chris Lattner7afae712009-03-16 18:41:18 +00001447 Opts.SimplifyLibCalls = !LangOpts.NoBuiltin;
Daniel Dunbardd913e52008-10-31 09:34:21 +00001448
1449#ifdef NDEBUG
1450 Opts.VerifyModule = 0;
1451#endif
Daniel Dunbara034ba82009-02-17 19:47:34 +00001452
1453 Opts.CPU = TargetCPU;
Daniel Dunbar868bd0a2009-05-06 03:16:41 +00001454 Opts.Features.clear();
Mike Stump1eb44332009-09-09 15:08:12 +00001455 for (llvm::StringMap<bool>::const_iterator it = Features.begin(),
Daniel Dunbar868bd0a2009-05-06 03:16:41 +00001456 ie = Features.end(); it != ie; ++it) {
1457 // FIXME: If we are completely confident that we have the right
1458 // set, we only need to pass the minuses.
1459 std::string Name(it->second ? "+" : "-");
1460 Name += it->first();
1461 Opts.Features.push_back(Name);
1462 }
Mike Stump1eb44332009-09-09 15:08:12 +00001463
Chris Lattnerbd360642009-03-26 05:00:52 +00001464 Opts.NoCommon = NoCommon | LangOpts.CPlusPlus;
Mike Stump1eb44332009-09-09 15:08:12 +00001465
Chris Lattner44502662009-02-18 01:23:44 +00001466 // Handle -ftime-report.
1467 Opts.TimePasses = TimeReport;
Devang Patel24095da2009-06-04 23:32:02 +00001468
1469 Opts.DisableRedZone = DisableRedZone;
Devang Patelacebb392009-06-05 22:05:48 +00001470 Opts.NoImplicitFloat = NoImplicitFloat;
Daniel Dunbar70f92432008-10-23 05:50:47 +00001471}
1472
1473//===----------------------------------------------------------------------===//
Douglas Gregor26df2f02009-04-02 19:05:20 +00001474// Fix-It Options
1475//===----------------------------------------------------------------------===//
1476static llvm::cl::list<ParsedSourceLocation>
1477FixItAtLocations("fixit-at", llvm::cl::value_desc("source-location"),
1478 llvm::cl::desc("Perform Fix-It modifications at the given source location"));
1479
1480//===----------------------------------------------------------------------===//
Eli Friedmanc6d656e2009-05-18 22:39:16 +00001481// ObjC Rewriter Options
1482//===----------------------------------------------------------------------===//
1483static llvm::cl::opt<bool>
1484SilenceRewriteMacroWarning("Wno-rewrite-macros", llvm::cl::init(false),
1485 llvm::cl::desc("Silence ObjC rewriting warnings"));
1486
1487//===----------------------------------------------------------------------===//
Eli Friedman0eeb86e2009-05-19 01:17:04 +00001488// Warning Options
1489//===----------------------------------------------------------------------===//
1490
1491// This gets all -W options, including -Werror, -W[no-]system-headers, etc. The
1492// driver has stripped off -Wa,foo etc. The driver has also translated -W to
1493// -Wextra, so we don't need to worry about it.
1494static llvm::cl::list<std::string>
1495OptWarnings("W", llvm::cl::Prefix, llvm::cl::ValueOptional);
1496
1497static llvm::cl::opt<bool> OptPedantic("pedantic");
1498static llvm::cl::opt<bool> OptPedanticErrors("pedantic-errors");
1499static llvm::cl::opt<bool> OptNoWarnings("w");
1500
1501//===----------------------------------------------------------------------===//
Eli Friedman12d3b1d2009-05-19 03:06:47 +00001502// Preprocessing (-E mode) Options
1503//===----------------------------------------------------------------------===//
1504static llvm::cl::opt<bool>
1505DisableLineMarkers("P", llvm::cl::desc("Disable linemarker output in -E mode"));
1506static llvm::cl::opt<bool>
1507EnableCommentOutput("C", llvm::cl::desc("Enable comment output in -E mode"));
1508static llvm::cl::opt<bool>
1509EnableMacroCommentOutput("CC",
1510 llvm::cl::desc("Enable comment output in -E mode, "
1511 "even from macro expansions"));
1512static llvm::cl::opt<bool>
1513DumpMacros("dM", llvm::cl::desc("Print macro definitions in -E mode instead of"
1514 " normal output"));
1515static llvm::cl::opt<bool>
1516DumpDefines("dD", llvm::cl::desc("Print macro definitions in -E mode in "
1517 "addition to normal output"));
Eli Friedmanb5c8f8b2009-05-19 03:35:57 +00001518
1519//===----------------------------------------------------------------------===//
1520// Dependency file options
1521//===----------------------------------------------------------------------===//
1522static llvm::cl::opt<std::string>
1523DependencyFile("dependency-file",
1524 llvm::cl::desc("Filename (or -) to write dependency output to"));
1525
1526static llvm::cl::opt<bool>
1527DependenciesIncludeSystemHeaders("sys-header-deps",
1528 llvm::cl::desc("Include system headers in dependency output"));
1529
1530static llvm::cl::list<std::string>
1531DependencyTargets("MT",
1532 llvm::cl::desc("Specify target for dependency"));
1533
1534// FIXME: Implement feature
1535static llvm::cl::opt<bool>
1536PhonyDependencyTarget("MP",
1537 llvm::cl::desc("Create phony target for each dependency "
1538 "(other than main file)"));
1539
Eli Friedman12d3b1d2009-05-19 03:06:47 +00001540//===----------------------------------------------------------------------===//
Eli Friedmane71b85f2009-05-19 10:18:02 +00001541// Analysis options
1542//===----------------------------------------------------------------------===//
1543
1544static llvm::cl::list<Analyses>
1545AnalysisList(llvm::cl::desc("Source Code Analysis - Checks and Analyses"),
1546llvm::cl::values(
1547#define ANALYSIS(NAME, CMDFLAG, DESC, SCOPE)\
1548clEnumValN(NAME, CMDFLAG, DESC),
Eli Friedman0ec78fa2009-05-19 21:10:40 +00001549#include "clang/Frontend/Analyses.def"
Eli Friedmane71b85f2009-05-19 10:18:02 +00001550clEnumValEnd));
1551
Mike Stump1eb44332009-09-09 15:08:12 +00001552static llvm::cl::opt<AnalysisStores>
Eli Friedmane71b85f2009-05-19 10:18:02 +00001553AnalysisStoreOpt("analyzer-store",
1554 llvm::cl::desc("Source Code Analysis - Abstract Memory Store Models"),
1555 llvm::cl::init(BasicStoreModel),
1556 llvm::cl::values(
1557#define ANALYSIS_STORE(NAME, CMDFLAG, DESC, CREATFN)\
1558clEnumValN(NAME##Model, CMDFLAG, DESC),
Eli Friedman0ec78fa2009-05-19 21:10:40 +00001559#include "clang/Frontend/Analyses.def"
Eli Friedmane71b85f2009-05-19 10:18:02 +00001560clEnumValEnd));
1561
Mike Stump1eb44332009-09-09 15:08:12 +00001562static llvm::cl::opt<AnalysisConstraints>
Eli Friedmane71b85f2009-05-19 10:18:02 +00001563AnalysisConstraintsOpt("analyzer-constraints",
1564 llvm::cl::desc("Source Code Analysis - Symbolic Constraint Engines"),
1565 llvm::cl::init(RangeConstraintsModel),
1566 llvm::cl::values(
1567#define ANALYSIS_CONSTRAINTS(NAME, CMDFLAG, DESC, CREATFN)\
1568clEnumValN(NAME##Model, CMDFLAG, DESC),
Eli Friedman0ec78fa2009-05-19 21:10:40 +00001569#include "clang/Frontend/Analyses.def"
Eli Friedmane71b85f2009-05-19 10:18:02 +00001570clEnumValEnd));
1571
1572static llvm::cl::opt<AnalysisDiagClients>
1573AnalysisDiagOpt("analyzer-output",
1574 llvm::cl::desc("Source Code Analysis - Output Options"),
1575 llvm::cl::init(PD_HTML),
1576 llvm::cl::values(
1577#define ANALYSIS_DIAGNOSTICS(NAME, CMDFLAG, DESC, CREATFN, AUTOCREATE)\
1578clEnumValN(PD_##NAME, CMDFLAG, DESC),
Eli Friedman0ec78fa2009-05-19 21:10:40 +00001579#include "clang/Frontend/Analyses.def"
Eli Friedmane71b85f2009-05-19 10:18:02 +00001580clEnumValEnd));
1581
1582static llvm::cl::opt<bool>
1583VisualizeEGDot("analyzer-viz-egraph-graphviz",
1584 llvm::cl::desc("Display exploded graph using GraphViz"));
1585
1586static llvm::cl::opt<bool>
1587VisualizeEGUbi("analyzer-viz-egraph-ubigraph",
1588 llvm::cl::desc("Display exploded graph using Ubigraph"));
1589
1590static llvm::cl::opt<bool>
1591AnalyzeAll("analyzer-opt-analyze-headers",
1592 llvm::cl::desc("Force the static analyzer to analyze "
1593 "functions defined in header files"));
1594
1595static llvm::cl::opt<bool>
1596AnalyzerDisplayProgress("analyzer-display-progress",
1597 llvm::cl::desc("Emit verbose output about the analyzer's progress."));
1598
1599static llvm::cl::opt<bool>
1600PurgeDead("analyzer-purge-dead",
1601 llvm::cl::init(true),
1602 llvm::cl::desc("Remove dead symbols, bindings, and constraints before"
1603 " processing a statement."));
1604
1605static llvm::cl::opt<bool>
1606EagerlyAssume("analyzer-eagerly-assume",
1607 llvm::cl::init(false),
1608 llvm::cl::desc("Eagerly assume the truth/falseness of some "
1609 "symbolic constraints."));
1610
1611static llvm::cl::opt<std::string>
1612AnalyzeSpecificFunction("analyze-function",
1613 llvm::cl::desc("Run analysis on specific function"));
1614
1615static llvm::cl::opt<bool>
1616TrimGraph("trim-egraph",
1617 llvm::cl::desc("Only show error-related paths in the analysis graph"));
1618
1619static AnalyzerOptions ReadAnalyzerOptions() {
1620 AnalyzerOptions Opts;
1621 Opts.AnalysisList = AnalysisList;
1622 Opts.AnalysisStoreOpt = AnalysisStoreOpt;
1623 Opts.AnalysisConstraintsOpt = AnalysisConstraintsOpt;
1624 Opts.AnalysisDiagOpt = AnalysisDiagOpt;
1625 Opts.VisualizeEGDot = VisualizeEGDot;
1626 Opts.VisualizeEGUbi = VisualizeEGUbi;
1627 Opts.AnalyzeAll = AnalyzeAll;
1628 Opts.AnalyzerDisplayProgress = AnalyzerDisplayProgress;
1629 Opts.PurgeDead = PurgeDead;
1630 Opts.EagerlyAssume = EagerlyAssume;
1631 Opts.AnalyzeSpecificFunction = AnalyzeSpecificFunction;
1632 Opts.TrimGraph = TrimGraph;
1633 return Opts;
1634}
1635
1636//===----------------------------------------------------------------------===//
Chris Lattner75a97cb2009-04-17 21:05:01 +00001637// -dump-build-information Stuff
1638//===----------------------------------------------------------------------===//
1639
1640static llvm::cl::opt<std::string>
1641DumpBuildInformation("dump-build-information",
1642 llvm::cl::value_desc("filename"),
1643 llvm::cl::desc("output a dump of some build information to a file"));
1644
1645static llvm::raw_ostream *BuildLogFile = 0;
1646
1647/// LoggingDiagnosticClient - This is a simple diagnostic client that forwards
1648/// all diagnostics to both BuildLogFile and a chained DiagnosticClient.
1649namespace {
1650class LoggingDiagnosticClient : public DiagnosticClient {
1651 llvm::OwningPtr<DiagnosticClient> Chain1;
1652 llvm::OwningPtr<DiagnosticClient> Chain2;
1653public:
Mike Stump1eb44332009-09-09 15:08:12 +00001654
Chris Lattner75a97cb2009-04-17 21:05:01 +00001655 LoggingDiagnosticClient(DiagnosticClient *Normal) {
1656 // Output diags both where requested...
1657 Chain1.reset(Normal);
1658 // .. and to our log file.
1659 Chain2.reset(new TextDiagnosticPrinter(*BuildLogFile,
1660 !NoShowColumn,
1661 !NoCaretDiagnostics,
1662 !NoShowLocation,
1663 PrintSourceRangeInfo,
Chris Lattneraa5bf2e2009-04-19 07:44:08 +00001664 PrintDiagnosticOption,
Douglas Gregorfffd93f2009-05-01 21:53:04 +00001665 !NoDiagnosticsFixIt,
Nate Begeman4e3629e2009-06-25 22:43:10 +00001666 MessageLength));
Chris Lattner75a97cb2009-04-17 21:05:01 +00001667 }
Mike Stump1eb44332009-09-09 15:08:12 +00001668
Chris Lattner75a97cb2009-04-17 21:05:01 +00001669 virtual void setLangOptions(const LangOptions *LO) {
1670 Chain1->setLangOptions(LO);
1671 Chain2->setLangOptions(LO);
1672 }
Mike Stump1eb44332009-09-09 15:08:12 +00001673
Chris Lattner75a97cb2009-04-17 21:05:01 +00001674 virtual bool IncludeInDiagnosticCounts() const {
1675 return Chain1->IncludeInDiagnosticCounts();
1676 }
1677
1678 virtual void HandleDiagnostic(Diagnostic::Level DiagLevel,
1679 const DiagnosticInfo &Info) {
1680 Chain1->HandleDiagnostic(DiagLevel, Info);
1681 Chain2->HandleDiagnostic(DiagLevel, Info);
1682 }
1683};
1684} // end anonymous namespace.
1685
1686static void SetUpBuildDumpLog(unsigned argc, char **argv,
1687 llvm::OwningPtr<DiagnosticClient> &DiagClient) {
Mike Stump1eb44332009-09-09 15:08:12 +00001688
Chris Lattner75a97cb2009-04-17 21:05:01 +00001689 std::string ErrorInfo;
Chris Lattner92bcc272009-08-23 02:59:41 +00001690 BuildLogFile = new llvm::raw_fd_ostream(DumpBuildInformation.c_str(),
Dan Gohmanb044c472009-08-25 15:36:09 +00001691 ErrorInfo);
Mike Stump1eb44332009-09-09 15:08:12 +00001692
Chris Lattner75a97cb2009-04-17 21:05:01 +00001693 if (!ErrorInfo.empty()) {
1694 llvm::errs() << "error opening -dump-build-information file '"
1695 << DumpBuildInformation << "', option ignored!\n";
1696 delete BuildLogFile;
1697 BuildLogFile = 0;
1698 DumpBuildInformation = "";
1699 return;
1700 }
1701
1702 (*BuildLogFile) << "clang-cc command line arguments: ";
1703 for (unsigned i = 0; i != argc; ++i)
1704 (*BuildLogFile) << argv[i] << ' ';
1705 (*BuildLogFile) << '\n';
Mike Stump1eb44332009-09-09 15:08:12 +00001706
Chris Lattner75a97cb2009-04-17 21:05:01 +00001707 // LoggingDiagnosticClient - Insert a new logging diagnostic client in between
1708 // the diagnostic producers and the normal receiver.
1709 DiagClient.reset(new LoggingDiagnosticClient(DiagClient.take()));
1710}
1711
1712
1713
1714//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +00001715// Main driver
1716//===----------------------------------------------------------------------===//
1717
Chris Lattner92bcc272009-08-23 02:59:41 +00001718static llvm::raw_ostream *ComputeOutFile(const std::string &InFile,
1719 const char *Extension,
Eli Friedman66d6f042009-05-18 22:20:00 +00001720 bool Binary,
1721 llvm::sys::Path& OutPath) {
Chris Lattner92bcc272009-08-23 02:59:41 +00001722 llvm::raw_ostream *Ret;
Eli Friedman66d6f042009-05-18 22:20:00 +00001723 std::string OutFile;
Chris Lattner92bcc272009-08-23 02:59:41 +00001724 if (!OutputFile.empty())
Eli Friedman66d6f042009-05-18 22:20:00 +00001725 OutFile = OutputFile;
Chris Lattner92bcc272009-08-23 02:59:41 +00001726 else if (InFile == "-") {
1727 OutFile = "-";
Eli Friedman66d6f042009-05-18 22:20:00 +00001728 } else if (Extension) {
1729 llvm::sys::Path Path(InFile);
1730 Path.eraseSuffix();
1731 Path.appendSuffix(Extension);
Chris Lattnerd57a7ef2009-08-23 22:45:33 +00001732 OutFile = Path.str();
Eli Friedman66d6f042009-05-18 22:20:00 +00001733 } else {
Chris Lattner92bcc272009-08-23 02:59:41 +00001734 OutFile = "-";
Chris Lattner8a5c8092009-02-18 01:20:05 +00001735 }
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +00001736
Chris Lattner92bcc272009-08-23 02:59:41 +00001737 std::string Error;
1738 Ret = new llvm::raw_fd_ostream(OutFile.c_str(), Error,
Dan Gohmanb044c472009-08-25 15:36:09 +00001739 (Binary ? llvm::raw_fd_ostream::F_Binary : 0));
Chris Lattner92bcc272009-08-23 02:59:41 +00001740 if (!Error.empty()) {
1741 // FIXME: Don't fail this way.
1742 llvm::errs() << "ERROR: " << Error << "\n";
1743 ::exit(1);
Ted Kremenekdb094a22007-12-05 18:27:04 +00001744 }
Mike Stump1eb44332009-09-09 15:08:12 +00001745
Chris Lattner92bcc272009-08-23 02:59:41 +00001746 if (OutFile != "-")
1747 OutPath = OutFile;
Eli Friedman66d6f042009-05-18 22:20:00 +00001748
1749 return Ret;
Ted Kremenekdb094a22007-12-05 18:27:04 +00001750}
1751
Daniel Dunbar0794d8d2009-09-17 00:48:00 +00001752static ASTConsumer *CreateConsumerAction(Preprocessor &PP,
1753 const std::string &InFile,
1754 ProgActions PA,
1755 llvm::OwningPtr<llvm::raw_ostream> &OS,
1756 llvm::sys::Path &OutPath,
1757 const llvm::StringMap<bool> &Features,
1758 llvm::LLVMContext& Context) {
Ted Kremenek85888962008-10-21 00:54:44 +00001759 switch (PA) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001760 default:
Daniel Dunbar0794d8d2009-09-17 00:48:00 +00001761 return 0;
Eli Friedman66d6f042009-05-18 22:20:00 +00001762
1763 case ASTPrint:
1764 OS.reset(ComputeOutFile(InFile, 0, false, OutPath));
Daniel Dunbar0794d8d2009-09-17 00:48:00 +00001765 return CreateASTPrinter(OS.get());
Mike Stump1eb44332009-09-09 15:08:12 +00001766
Douglas Gregoree75c052009-05-21 20:55:50 +00001767 case ASTPrintXML:
1768 OS.reset(ComputeOutFile(InFile, "xml", false, OutPath));
Daniel Dunbar0794d8d2009-09-17 00:48:00 +00001769 return CreateASTPrinterXML(OS.get());
Douglas Gregoree75c052009-05-21 20:55:50 +00001770
Eli Friedman66d6f042009-05-18 22:20:00 +00001771 case ASTDump:
Daniel Dunbar0794d8d2009-09-17 00:48:00 +00001772 return CreateASTDumper();
Eli Friedman66d6f042009-05-18 22:20:00 +00001773
Eli Friedman66d6f042009-05-18 22:20:00 +00001774 case ASTView:
Daniel Dunbar0794d8d2009-09-17 00:48:00 +00001775 return CreateASTViewer();
Eli Friedman66d6f042009-05-18 22:20:00 +00001776
1777 case PrintDeclContext:
Daniel Dunbar0794d8d2009-09-17 00:48:00 +00001778 return CreateDeclContextPrinter();
Eli Friedman66d6f042009-05-18 22:20:00 +00001779
Anders Carlsson78762eb2009-09-24 18:54:49 +00001780 case DumpRecordLayouts:
1781 return CreateRecordLayoutDumper();
1782
Eli Friedman66d6f042009-05-18 22:20:00 +00001783 case InheritanceView:
Daniel Dunbar0794d8d2009-09-17 00:48:00 +00001784 return CreateInheritanceViewer(InheritanceViewCls);
Eli Friedman66d6f042009-05-18 22:20:00 +00001785
1786 case EmitAssembly:
1787 case EmitLLVM:
Mike Stump1eb44332009-09-09 15:08:12 +00001788 case EmitBC:
Eli Friedman66d6f042009-05-18 22:20:00 +00001789 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 Kremenekdb094a22007-12-05 18:27:04 +00001802 }
Ted Kremenekfdfc1982007-12-19 22:24:34 +00001803
Eli Friedman66d6f042009-05-18 22:20:00 +00001804 CompileOptions Opts;
1805 InitializeCompileOptions(Opts, PP.getLangOptions(), Features);
Daniel Dunbar0794d8d2009-09-17 00:48:00 +00001806 return CreateBackendConsumer(Act, PP.getDiagnostics(), PP.getLangOptions(),
1807 Opts, InFile, OS.get(), Context);
Eli Friedman66d6f042009-05-18 22:20:00 +00001808 }
1809
Daniel Dunbar0794d8d2009-09-17 00:48:00 +00001810 case RewriteObjC:
1811 OS.reset(ComputeOutFile(InFile, "cpp", true, OutPath));
1812 return CreateObjCRewriter(InFile, OS.get(), PP.getDiagnostics(),
1813 PP.getLangOptions(), SilenceRewriteMacroWarning);
1814
1815 case RewriteBlocks:
1816 return CreateBlockRewriter(InFile, PP.getDiagnostics(),
1817 PP.getLangOptions());
1818 }
1819}
1820
1821/// ProcessInputFile - Process a single input file with the specified state.
1822///
1823static void ProcessInputFile(Preprocessor &PP, PreprocessorFactory &PPF,
1824 const std::string &InFile, ProgActions PA,
1825 const llvm::StringMap<bool> &Features,
1826 llvm::LLVMContext& Context) {
1827 llvm::OwningPtr<llvm::raw_ostream> OS;
1828 llvm::OwningPtr<ASTConsumer> Consumer;
1829 bool ClearSourceMgr = false;
1830 FixItRewriter *FixItRewrite = 0;
1831 bool CompleteTranslationUnit = true;
1832 llvm::sys::Path OutPath;
1833
1834 switch (PA) {
1835 default:
1836 Consumer.reset(CreateConsumerAction(PP, InFile, PA, OS, OutPath,
1837 Features, Context));
1838
1839 if (!Consumer.get()) {
1840 fprintf(stderr, "Unexpected program action!\n");
1841 HadErrors = true;
1842 return;
1843 }
1844
1845 break;;
1846
1847 case EmitHTML:
1848 OS.reset(ComputeOutFile(InFile, 0, true, OutPath));
1849 Consumer.reset(CreateHTMLPrinter(OS.get(), PP.getDiagnostics(), &PP, &PPF));
1850 break;
1851
1852 case RunAnalysis:
1853 Consumer.reset(CreateAnalysisConsumer(PP.getDiagnostics(), &PP, &PPF,
1854 PP.getLangOptions(), OutputFile,
1855 ReadAnalyzerOptions()));
1856 break;
1857
Eli Friedman66d6f042009-05-18 22:20:00 +00001858 case GeneratePCH:
Douglas Gregore650c8c2009-07-07 00:12:59 +00001859 if (RelocatablePCH.getValue() && !isysroot.getNumOccurrences()) {
1860 PP.Diag(SourceLocation(), diag::err_relocatable_without_without_isysroot);
1861 RelocatablePCH.setValue(false);
1862 }
Mike Stump1eb44332009-09-09 15:08:12 +00001863
Eli Friedman66d6f042009-05-18 22:20:00 +00001864 OS.reset(ComputeOutFile(InFile, 0, true, OutPath));
Douglas Gregore650c8c2009-07-07 00:12:59 +00001865 if (RelocatablePCH.getValue())
1866 Consumer.reset(CreatePCHGenerator(PP, OS.get(), isysroot.c_str()));
1867 else
1868 Consumer.reset(CreatePCHGenerator(PP, OS.get()));
Eli Friedman66d6f042009-05-18 22:20:00 +00001869 CompleteTranslationUnit = false;
1870 break;
1871
Chris Lattnerc106c102008-10-12 05:03:36 +00001872 case DumpRawTokens: {
Chris Lattner47099742009-02-18 01:51:21 +00001873 llvm::TimeRegion Timer(ClangFrontendTimer);
Chris Lattnerc106c102008-10-12 05:03:36 +00001874 SourceManager &SM = PP.getSourceManager();
Chris Lattnerc106c102008-10-12 05:03:36 +00001875 // Start lexing the specified input file.
Chris Lattner025c3a62009-01-17 07:35:14 +00001876 Lexer RawLex(SM.getMainFileID(), SM, PP.getLangOptions());
Chris Lattnerc106c102008-10-12 05:03:36 +00001877 RawLex.SetKeepWhitespaceMode(true);
1878
1879 Token RawTok;
Chris Lattnerc106c102008-10-12 05:03:36 +00001880 RawLex.LexFromRawLexer(RawTok);
1881 while (RawTok.isNot(tok::eof)) {
1882 PP.DumpToken(RawTok, true);
1883 fprintf(stderr, "\n");
1884 RawLex.LexFromRawLexer(RawTok);
1885 }
1886 ClearSourceMgr = true;
1887 break;
1888 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001889 case DumpTokens: { // Token dump mode.
Chris Lattner47099742009-02-18 01:51:21 +00001890 llvm::TimeRegion Timer(ClangFrontendTimer);
Chris Lattnerd2177732007-07-20 16:59:19 +00001891 Token Tok;
Chris Lattnerc106c102008-10-12 05:03:36 +00001892 // Start preprocessing the specified input file.
Ted Kremenek95041a22007-12-19 22:51:13 +00001893 PP.EnterMainSourceFile();
Reid Spencer5f016e22007-07-11 17:01:13 +00001894 do {
1895 PP.Lex(Tok);
1896 PP.DumpToken(Tok, true);
1897 fprintf(stderr, "\n");
Chris Lattner057aaf62007-10-09 18:03:42 +00001898 } while (Tok.isNot(tok::eof));
Chris Lattnerbd247762007-07-22 06:05:44 +00001899 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001900 break;
1901 }
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001902 case RunPreprocessorOnly:
Reid Spencer5f016e22007-07-11 17:01:13 +00001903 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001904
Douglas Gregorbf1bd6e2009-04-02 23:43:50 +00001905 case GeneratePTH: {
Chris Lattner47099742009-02-18 01:51:21 +00001906 llvm::TimeRegion Timer(ClangFrontendTimer);
Eli Friedmanf54fce82009-05-19 01:02:07 +00001907 if (OutputFile.empty() || OutputFile == "-") {
1908 // FIXME: Don't fail this way.
1909 // FIXME: Verify that we can actually seek in the given file.
Chris Lattner92bcc272009-08-23 02:59:41 +00001910 llvm::errs() << "ERROR: PTH requires an seekable file for output!\n";
Eli Friedmanf54fce82009-05-19 01:02:07 +00001911 ::exit(1);
1912 }
1913 OS.reset(ComputeOutFile(InFile, 0, true, OutPath));
1914 CacheTokens(PP, static_cast<llvm::raw_fd_ostream*>(OS.get()));
Ted Kremenek85888962008-10-21 00:54:44 +00001915 ClearSourceMgr = true;
1916 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001917 }
Douglas Gregor6ab35242009-04-09 21:40:53 +00001918
Chris Lattnercc7dea82009-04-27 22:02:30 +00001919 case PrintPreprocessedInput:
Eli Friedmanf54fce82009-05-19 01:02:07 +00001920 OS.reset(ComputeOutFile(InFile, 0, true, OutPath));
Reid Spencer5f016e22007-07-11 17:01:13 +00001921 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001922
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001923 case ParseNoop:
Reid Spencer5f016e22007-07-11 17:01:13 +00001924 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001925
Chris Lattner47099742009-02-18 01:51:21 +00001926 case ParsePrintCallbacks: {
1927 llvm::TimeRegion Timer(ClangFrontendTimer);
Eli Friedmanf54fce82009-05-19 01:02:07 +00001928 OS.reset(ComputeOutFile(InFile, 0, true, OutPath));
1929 ParseFile(PP, CreatePrintParserActionsAction(PP, OS.get()));
Chris Lattnerbd247762007-07-22 06:05:44 +00001930 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001931 break;
Chris Lattner47099742009-02-18 01:51:21 +00001932 }
1933
1934 case ParseSyntaxOnly: { // -fsyntax-only
1935 llvm::TimeRegion Timer(ClangFrontendTimer);
Ted Kremenek7e7e6252008-08-08 02:46:37 +00001936 Consumer.reset(new ASTConsumer());
Ted Kremenek2bf55142007-09-17 20:49:30 +00001937 break;
Chris Lattner47099742009-02-18 01:51:21 +00001938 }
Mike Stump1eb44332009-09-09 15:08:12 +00001939
Chris Lattnerb57e3d42008-05-08 06:52:13 +00001940 case RewriteMacros:
Eli Friedmanf54fce82009-05-19 01:02:07 +00001941 OS.reset(ComputeOutFile(InFile, 0, true, OutPath));
1942 RewriteMacrosInInput(PP, OS.get());
Chris Lattnerb57e3d42008-05-08 06:52:13 +00001943 ClearSourceMgr = true;
1944 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001945
Eli Friedmanf54fce82009-05-19 01:02:07 +00001946 case RewriteTest:
1947 OS.reset(ComputeOutFile(InFile, 0, true, OutPath));
1948 DoRewriteTest(PP, OS.get());
Chris Lattnerb13c5ee2008-10-12 05:29:20 +00001949 ClearSourceMgr = true;
1950 break;
Douglas Gregor558cb562009-04-02 01:08:08 +00001951
1952 case FixIt:
1953 llvm::TimeRegion Timer(ClangFrontendTimer);
1954 Consumer.reset(new ASTConsumer());
Douglas Gregorde4bf6a2009-04-02 17:13:00 +00001955 FixItRewrite = new FixItRewriter(PP.getDiagnostics(),
Chris Lattner2c78b872009-04-14 23:22:57 +00001956 PP.getSourceManager(),
1957 PP.getLangOptions());
Douglas Gregor558cb562009-04-02 01:08:08 +00001958 break;
Chris Lattner47099742009-02-18 01:51:21 +00001959 }
Ted Kremenek46157b52009-01-28 04:29:29 +00001960
Chris Lattner1aee61a2009-04-27 21:25:27 +00001961 if (FixItAtLocations.size() > 0) {
1962 // Even without the "-fixit" flag, with may have some specific
1963 // locations where the user has requested fixes. Process those
1964 // locations now.
1965 if (!FixItRewrite)
1966 FixItRewrite = new FixItRewriter(PP.getDiagnostics(),
1967 PP.getSourceManager(),
1968 PP.getLangOptions());
Chris Lattner9ecd26a2009-03-28 01:37:17 +00001969
Chris Lattner1aee61a2009-04-27 21:25:27 +00001970 bool AddedFixitLocation = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001971 for (unsigned Idx = 0, Last = FixItAtLocations.size();
Chris Lattner1aee61a2009-04-27 21:25:27 +00001972 Idx != Last; ++Idx) {
1973 RequestedSourceLocation Requested;
Argyrios Kyrtzidis34d25d82009-06-23 22:01:39 +00001974 if (ResolveParsedLocation(FixItAtLocations[Idx],
1975 PP.getFileManager(), Requested)) {
Chris Lattner1aee61a2009-04-27 21:25:27 +00001976 fprintf(stderr, "FIX-IT could not find file \"%s\"\n",
1977 FixItAtLocations[Idx].FileName.c_str());
1978 } else {
1979 FixItRewrite->addFixItLocation(Requested);
1980 AddedFixitLocation = true;
Douglas Gregor26df2f02009-04-02 19:05:20 +00001981 }
1982 }
1983
Chris Lattner1aee61a2009-04-27 21:25:27 +00001984 if (!AddedFixitLocation) {
1985 // All of the fix-it locations were bad. Don't fix anything.
1986 delete FixItRewrite;
1987 FixItRewrite = 0;
1988 }
1989 }
1990
1991 llvm::OwningPtr<ASTContext> ContextOwner;
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001992 if (Consumer)
Chris Lattner9ecd26a2009-03-28 01:37:17 +00001993 ContextOwner.reset(new ASTContext(PP.getLangOptions(),
1994 PP.getSourceManager(),
1995 PP.getTargetInfo(),
1996 PP.getIdentifierTable(),
1997 PP.getSelectorTable(),
Chris Lattner1b63e4f2009-06-14 01:54:56 +00001998 PP.getBuiltinInfo(),
Douglas Gregor2deaea32009-04-22 18:49:13 +00001999 /* FreeMemory = */ !DisableFree,
Chris Lattner1b63e4f2009-06-14 01:54:56 +00002000 /* size_reserve = */0));
Mike Stump1eb44332009-09-09 15:08:12 +00002001
Chris Lattnercc7dea82009-04-27 22:02:30 +00002002 llvm::OwningPtr<PCHReader> Reader;
2003 llvm::OwningPtr<ExternalASTSource> Source;
Mike Stump1eb44332009-09-09 15:08:12 +00002004
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002005 if (!ImplicitIncludePCH.empty()) {
Douglas Gregore650c8c2009-07-07 00:12:59 +00002006 // If the user specified -isysroot, it will be used for relocatable PCH
2007 // files.
2008 const char *isysrootPCH = 0;
2009 if (isysroot.getNumOccurrences() != 0)
2010 isysrootPCH = isysroot.c_str();
Mike Stump1eb44332009-09-09 15:08:12 +00002011
Douglas Gregore650c8c2009-07-07 00:12:59 +00002012 Reader.reset(new PCHReader(PP, ContextOwner.get(), isysrootPCH));
Mike Stump1eb44332009-09-09 15:08:12 +00002013
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002014 // The user has asked us to include a precompiled header. Load
2015 // the precompiled header into the AST context.
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002016 switch (Reader->ReadPCH(ImplicitIncludePCH)) {
2017 case PCHReader::Success: {
Douglas Gregore721f952009-04-28 18:58:38 +00002018 // Set the predefines buffer as suggested by the PCH
2019 // reader. Typically, the predefines buffer will be empty.
2020 PP.setPredefines(Reader->getSuggestedPredefines());
2021
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002022 // Attach the PCH reader to the AST context as an external AST
2023 // source, so that declarations will be deserialized from the
2024 // PCH file as needed.
Chris Lattnercc7dea82009-04-27 22:02:30 +00002025 if (ContextOwner) {
2026 Source.reset(Reader.take());
Douglas Gregore1d918e2009-04-10 23:10:45 +00002027 ContextOwner->setExternalSource(Source);
Chris Lattnercc7dea82009-04-27 22:02:30 +00002028 }
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002029 break;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002030 }
2031
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002032 case PCHReader::Failure:
2033 // Unrecoverable failure: don't even try to process the input
2034 // file.
2035 return;
2036
2037 case PCHReader::IgnorePCH:
Douglas Gregor1ab86ac2009-04-28 22:01:16 +00002038 // No suitable PCH file could be found. Return an error.
2039 return;
2040
2041#if 0
2042 // FIXME: We can recover from failed attempts to load PCH
2043 // files. This code will do so, if we ever want to enable it.
2044
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002045 // We delayed the initialization of builtins in the hope of
2046 // loading the PCH file. Since the PCH file could not be
2047 // loaded, initialize builtins now.
2048 if (ContextOwner)
2049 ContextOwner->InitializeBuiltins(PP.getIdentifierTable());
Douglas Gregor1ab86ac2009-04-28 22:01:16 +00002050#endif
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002051 }
2052
2053 // Finish preprocessor initialization. We do this now (rather
2054 // than earlier) because this initialization creates new source
2055 // location entries in the source manager, which must come after
2056 // the source location entries for the PCH file.
2057 if (InitializeSourceManager(PP, InFile))
2058 return;
Ted Kremenek46157b52009-01-28 04:29:29 +00002059 }
Douglas Gregor81b747b2009-09-17 21:32:03 +00002060
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002061 // If we have an ASTConsumer, run the parser with it.
Douglas Gregor81b747b2009-09-17 21:32:03 +00002062 if (Consumer) {
2063 CodeCompleteConsumer *(*CreateCodeCompleter)(Sema &, void *) = 0;
2064 void *CreateCodeCompleterData = 0;
2065
Douglas Gregorb657f112009-09-22 21:11:38 +00002066 if (!CodeCompletionAt.FileName.empty()) {
2067 // Tell the source manager to chop off the given file at a specific
2068 // line and column.
2069 if (const FileEntry *Entry
2070 = PP.getFileManager().getFile(CodeCompletionAt.FileName)) {
2071 // Truncate the named file at the given line/column.
2072 PP.getSourceManager().truncateFileAt(Entry, CodeCompletionAt.Line,
2073 CodeCompletionAt.Column);
2074
2075 // Set up the creation routine for code-completion.
2076 CreateCodeCompleter = BuildPrintingCodeCompleter;
2077 } else {
2078 PP.getDiagnostics().Report(FullSourceLoc(),
2079 diag::err_fe_invalid_code_complete_file)
2080 << CodeCompletionAt.FileName;
2081 }
Douglas Gregor81b747b2009-09-17 21:32:03 +00002082 }
2083
Mike Stump1eb44332009-09-09 15:08:12 +00002084 ParseAST(PP, Consumer.get(), *ContextOwner.get(), Stats,
Douglas Gregor81b747b2009-09-17 21:32:03 +00002085 CompleteTranslationUnit,
2086 CreateCodeCompleter, CreateCodeCompleterData);
2087 }
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002088
2089 if (PA == RunPreprocessorOnly) { // Just lex as fast as we can, no output.
2090 llvm::TimeRegion Timer(ClangFrontendTimer);
2091 Token Tok;
2092 // Start parsing the specified input file.
2093 PP.EnterMainSourceFile();
2094 do {
2095 PP.Lex(Tok);
2096 } while (Tok.isNot(tok::eof));
2097 ClearSourceMgr = true;
2098 } else if (PA == ParseNoop) { // -parse-noop
2099 llvm::TimeRegion Timer(ClangFrontendTimer);
2100 ParseFile(PP, new MinimalAction(PP));
2101 ClearSourceMgr = true;
Chris Lattnercc7dea82009-04-27 22:02:30 +00002102 } else if (PA == PrintPreprocessedInput){ // -E mode.
2103 llvm::TimeRegion Timer(ClangFrontendTimer);
Eli Friedman12d3b1d2009-05-19 03:06:47 +00002104 if (DumpMacros)
2105 DoPrintMacros(PP, OS.get());
2106 else
2107 DoPrintPreprocessedInput(PP, OS.get(), EnableCommentOutput,
2108 EnableMacroCommentOutput,
2109 DisableLineMarkers, DumpDefines);
Chris Lattnercc7dea82009-04-27 22:02:30 +00002110 ClearSourceMgr = true;
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002111 }
Mike Stump1eb44332009-09-09 15:08:12 +00002112
Chris Lattner1aee61a2009-04-27 21:25:27 +00002113 if (FixItRewrite)
2114 FixItRewrite->WriteFixedFile(InFile, OutputFile);
Daniel Dunbar70186ab2009-07-29 02:40:09 +00002115
2116 // Disable the consumer prior to the context, the consumer may perform actions
2117 // in its destructor which require the context.
2118 if (DisableFree)
2119 Consumer.take();
2120 else
2121 Consumer.reset();
Mike Stump1eb44332009-09-09 15:08:12 +00002122
Chris Lattner1aee61a2009-04-27 21:25:27 +00002123 // If in -disable-free mode, don't deallocate ASTContext.
2124 if (DisableFree)
2125 ContextOwner.take();
2126 else
2127 ContextOwner.reset(); // Delete ASTContext
Eli Friedman66d6f042009-05-18 22:20:00 +00002128
Daniel Dunbar879c3ea2008-10-27 22:03:52 +00002129 if (VerifyDiagnostics)
Daniel Dunbar276373d2008-10-27 22:10:13 +00002130 if (CheckDiagnostics(PP))
2131 exit(1);
Chris Lattnere66b65c2008-02-06 01:42:25 +00002132
Reid Spencer5f016e22007-07-11 17:01:13 +00002133 if (Stats) {
Ted Kremenekfdfc1982007-12-19 22:24:34 +00002134 fprintf(stderr, "\nSTATISTICS FOR '%s':\n", InFile.c_str());
Reid Spencer5f016e22007-07-11 17:01:13 +00002135 PP.PrintStats();
2136 PP.getIdentifierTable().PrintStats();
Chris Lattnerdee73592007-12-15 20:48:40 +00002137 PP.getHeaderSearchInfo().PrintStats();
Ted Kremenek1b95a652009-01-09 18:20:21 +00002138 PP.getSourceManager().PrintStats();
Reid Spencer5f016e22007-07-11 17:01:13 +00002139 fprintf(stderr, "\n");
2140 }
Chris Lattnerbd247762007-07-22 06:05:44 +00002141
Mike Stump1eb44332009-09-09 15:08:12 +00002142 // For a multi-file compilation, some things are ok with nuking the source
Chris Lattnerbd247762007-07-22 06:05:44 +00002143 // manager tables, other require stable fileid/macroid's across multiple
2144 // files.
Chris Lattnerdee73592007-12-15 20:48:40 +00002145 if (ClearSourceMgr)
2146 PP.getSourceManager().clearIDTables();
Daniel Dunbard68ba0e2008-11-11 06:35:39 +00002147
Eli Friedman66d6f042009-05-18 22:20:00 +00002148 // Always delete the output stream because we don't want to leak file
2149 // handles. Also, we don't want to try to erase an open file.
2150 OS.reset();
2151
2152 if ((HadErrors || (PP.getDiagnostics().getNumErrors() != 0)) &&
2153 !OutPath.isEmpty()) {
2154 // If we had errors, try to erase the output file.
2155 OutPath.eraseFromDisk();
2156 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002157}
2158
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +00002159/// ProcessInputFile - Process a single AST input file with the specified state.
2160///
2161static void ProcessASTInputFile(const std::string &InFile, ProgActions PA,
2162 const llvm::StringMap<bool> &Features,
2163 Diagnostic &Diags, FileManager &FileMgr,
2164 llvm::LLVMContext& Context) {
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +00002165 std::string Error;
Daniel Dunbar31b87d82009-09-21 03:03:39 +00002166 llvm::OwningPtr<ASTUnit> AST(ASTUnit::LoadFromPCHFile(InFile, Diags, FileMgr,
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +00002167 &Error));
2168 if (!AST) {
2169 Diags.Report(FullSourceLoc(), diag::err_fe_invalid_ast_file) << Error;
2170 return;
2171 }
2172
2173 Preprocessor &PP = AST->getPreprocessor();
2174
2175 llvm::OwningPtr<llvm::raw_ostream> OS;
2176 llvm::sys::Path OutPath;
2177 llvm::OwningPtr<ASTConsumer> Consumer(CreateConsumerAction(PP, InFile, PA, OS,
2178 OutPath, Features,
2179 Context));
2180
2181 if (!Consumer.get()) {
2182 Diags.Report(FullSourceLoc(), diag::err_fe_invalid_ast_action);
2183 return;
2184 }
2185
Daniel Dunbara674bf42009-09-21 03:03:56 +00002186 // Set the main file ID to an empty file.
2187 //
2188 // FIXME: We probably shouldn't need this, but for now this is the simplest
2189 // way to reuse the logic in ParseAST.
2190 const char *EmptyStr = "";
2191 llvm::MemoryBuffer *SB =
2192 llvm::MemoryBuffer::getMemBuffer(EmptyStr, EmptyStr, "<dummy input>");
2193 AST->getSourceManager().createMainFileIDForMemBuffer(SB);
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +00002194
Daniel Dunbara674bf42009-09-21 03:03:56 +00002195 // Stream the input AST to the consumer.
2196 ParseAST(PP, Consumer.get(), AST->getASTContext(), Stats);
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +00002197
2198 // Release the consumer and the AST, in that order since the consumer may
2199 // perform actions in its destructor which require the context.
2200 if (DisableFree) {
2201 Consumer.take();
2202 AST.take();
2203 } else {
2204 Consumer.reset();
2205 AST.reset();
2206 }
2207
2208 // Always delete the output stream because we don't want to leak file
2209 // handles. Also, we don't want to try to erase an open file.
2210 OS.reset();
2211
2212 if ((HadErrors || (PP.getDiagnostics().getNumErrors() != 0)) &&
2213 !OutPath.isEmpty()) {
2214 // If we had errors, try to erase the output file.
2215 OutPath.eraseFromDisk();
2216 }
2217}
2218
Reid Spencer5f016e22007-07-11 17:01:13 +00002219static llvm::cl::list<std::string>
2220InputFilenames(llvm::cl::Positional, llvm::cl::desc("<input files>"));
2221
Daniel Dunbar70121eb2009-08-10 03:40:28 +00002222static void LLVMErrorHandler(void *UserData, const std::string &Message) {
2223 Diagnostic &Diags = *static_cast<Diagnostic*>(UserData);
2224
2225 Diags.Report(FullSourceLoc(), diag::err_fe_error_backend) << Message;
2226
2227 // We cannot recover from llvm errors.
2228 exit(1);
2229}
2230
Reid Spencer5f016e22007-07-11 17:01:13 +00002231int main(int argc, char **argv) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002232 llvm::sys::PrintStackTraceOnErrorSignal();
Chris Lattner09e94a32009-03-04 21:41:39 +00002233 llvm::PrettyStackTraceProgram X(argc, argv);
Owen Andersond7200462009-07-16 00:14:12 +00002234 llvm::LLVMContext &Context = llvm::getGlobalContext();
Daniel Dunbard6970812009-09-02 23:20:15 +00002235
Daniel Dunbar4d861512009-09-03 04:54:12 +00002236 // Initialize targets first, so that --version shows registered targets.
Chris Lattner2fe11942009-06-17 17:25:50 +00002237 llvm::InitializeAllTargets();
2238 llvm::InitializeAllAsmPrinters();
Daniel Dunbard6970812009-09-02 23:20:15 +00002239
2240 llvm::cl::ParseCommandLineOptions(argc, argv,
2241 "LLVM 'Clang' Compiler: http://clang.llvm.org\n");
Mike Stump1eb44332009-09-09 15:08:12 +00002242
Chris Lattner47099742009-02-18 01:51:21 +00002243 if (TimeReport)
2244 ClangFrontendTimer = new llvm::Timer("Clang front-end time");
Mike Stump1eb44332009-09-09 15:08:12 +00002245
Daniel Dunbar08e6dc62009-05-28 16:37:33 +00002246 if (Verbose)
Mike Stump3cbf5a02009-09-15 21:49:22 +00002247 llvm::errs() << "clang-cc version " CLANG_VERSION_STRING
2248 << " based upon " << PACKAGE_STRING
Daniel Dunbar2e30e592009-09-04 17:43:10 +00002249 << " hosted on " << llvm::sys::getHostTriple() << "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00002250
Reid Spencer5f016e22007-07-11 17:01:13 +00002251 // If no input was specified, read from stdin.
2252 if (InputFilenames.empty())
2253 InputFilenames.push_back("-");
Douglas Gregor68a0d782009-05-02 00:03:46 +00002254
Ted Kremenek31e703b2007-12-11 23:28:38 +00002255 // Create the diagnostic client for reporting errors or for
2256 // implementing -verify.
Chris Lattner409d4e72009-04-17 20:40:01 +00002257 llvm::OwningPtr<DiagnosticClient> DiagClient;
2258 if (VerifyDiagnostics) {
2259 // When checking diagnostics, just buffer them up.
2260 DiagClient.reset(new TextDiagnosticBuffer());
2261 if (InputFilenames.size() != 1) {
2262 fprintf(stderr, "-verify only works on single input files for now.\n");
2263 return 1;
2264 }
2265 if (!HTMLDiag.empty()) {
2266 fprintf(stderr, "-verify and -html-diags don't work together\n");
2267 return 1;
2268 }
2269 } else if (HTMLDiag.empty()) {
Ted Kremenekb4398aa2008-08-07 17:49:57 +00002270 // Print diagnostics to stderr by default.
Douglas Gregor68a0d782009-05-02 00:03:46 +00002271
2272 // If -fmessage-length=N was not specified, determine whether this
2273 // is a terminal and, if so, implicitly define -fmessage-length
2274 // appropriately.
2275 if (MessageLength.getNumOccurrences() == 0)
Douglas Gregor67187ce2009-05-11 18:06:49 +00002276 MessageLength.setValue(llvm::sys::Process::StandardErrColumns());
Douglas Gregor68a0d782009-05-02 00:03:46 +00002277
Torok Edwin603fca72009-06-04 07:18:23 +00002278 if (!NoColorDiagnostic) {
2279 NoColorDiagnostic.setValue(!llvm::sys::Process::StandardErrHasColors());
2280 }
2281
Chris Lattner409d4e72009-04-17 20:40:01 +00002282 DiagClient.reset(new TextDiagnosticPrinter(llvm::errs(),
Chris Lattnera03a5b52008-11-19 06:56:25 +00002283 !NoShowColumn,
Chris Lattner65f5e642009-01-30 19:01:41 +00002284 !NoCaretDiagnostics,
Chris Lattner1fbee5d2009-03-13 01:08:23 +00002285 !NoShowLocation,
Chris Lattnerd51d74a2009-04-16 05:44:38 +00002286 PrintSourceRangeInfo,
Chris Lattneraa5bf2e2009-04-19 07:44:08 +00002287 PrintDiagnosticOption,
Douglas Gregorfffd93f2009-05-01 21:53:04 +00002288 !NoDiagnosticsFixIt,
Torok Edwin603fca72009-06-04 07:18:23 +00002289 MessageLength,
2290 !NoColorDiagnostic));
Ted Kremenekb4398aa2008-08-07 17:49:57 +00002291 } else {
Chris Lattner409d4e72009-04-17 20:40:01 +00002292 DiagClient.reset(CreateHTMLDiagnosticClient(HTMLDiag));
Reid Spencer5f016e22007-07-11 17:01:13 +00002293 }
Mike Stump1eb44332009-09-09 15:08:12 +00002294
Chris Lattner75a97cb2009-04-17 21:05:01 +00002295 if (!DumpBuildInformation.empty()) {
2296 if (!HTMLDiag.empty()) {
2297 fprintf(stderr,
2298 "-dump-build-information and -html-diags don't work together\n");
2299 return 1;
2300 }
Mike Stump1eb44332009-09-09 15:08:12 +00002301
Chris Lattner75a97cb2009-04-17 21:05:01 +00002302 SetUpBuildDumpLog(argc, argv, DiagClient);
2303 }
Mike Stump1eb44332009-09-09 15:08:12 +00002304
Ted Kremenekb4398aa2008-08-07 17:49:57 +00002305
Reid Spencer5f016e22007-07-11 17:01:13 +00002306 // Configure our handling of diagnostics.
Ted Kremenekb4398aa2008-08-07 17:49:57 +00002307 Diagnostic Diags(DiagClient.get());
Eli Friedman0eeb86e2009-05-19 01:17:04 +00002308 if (ProcessWarningOptions(Diags, OptWarnings, OptPedantic, OptPedanticErrors,
2309 OptNoWarnings))
Sebastian Redl63a9e0f2009-03-06 17:41:35 +00002310 return 1;
Ted Kremenek31e703b2007-12-11 23:28:38 +00002311
Daniel Dunbar70121eb2009-08-10 03:40:28 +00002312 // Set an error handler, so that any LLVM backend diagnostics go through our
2313 // error handler.
2314 llvm::llvm_install_error_handler(LLVMErrorHandler,
2315 static_cast<void*>(&Diags));
2316
Chris Lattner4f037832007-12-05 23:24:17 +00002317 // -I- is a deprecated GCC feature, scan for it and reject it.
2318 for (unsigned i = 0, e = I_dirs.size(); i != e; ++i) {
2319 if (I_dirs[i] == "-") {
Mike Stump1eb44332009-09-09 15:08:12 +00002320 Diags.Report(FullSourceLoc(), diag::err_pp_I_dash_not_supported);
Chris Lattner4f037832007-12-05 23:24:17 +00002321 I_dirs.erase(I_dirs.begin()+i);
2322 --i;
2323 }
2324 }
Chris Lattner11215192008-03-14 06:12:05 +00002325
2326 // Get information about the target being compiled for.
Chris Lattner2f60af72009-09-12 22:45:58 +00002327 llvm::Triple Triple = CreateTargetTriple();
2328 llvm::OwningPtr<TargetInfo>
2329 Target(TargetInfo::CreateTargetInfo(Triple.getTriple()));
Mike Stump1eb44332009-09-09 15:08:12 +00002330
Chris Lattner11215192008-03-14 06:12:05 +00002331 if (Target == 0) {
Mike Stump1eb44332009-09-09 15:08:12 +00002332 Diags.Report(FullSourceLoc(), diag::err_fe_unknown_triple)
Chris Lattner2f60af72009-09-12 22:45:58 +00002333 << Triple.getTriple().c_str();
Sebastian Redlc5613db2009-03-07 12:09:25 +00002334 return 1;
Chris Lattner11215192008-03-14 06:12:05 +00002335 }
Mike Stump1eb44332009-09-09 15:08:12 +00002336
Daniel Dunbar73b79592009-09-14 00:02:12 +00002337 // Set the target ABI if specified.
2338 if (!TargetABI.empty()) {
2339 if (!Target->setABI(TargetABI)) {
2340 Diags.Report(FullSourceLoc(), diag::err_fe_unknown_target_abi)
2341 << TargetABI;
2342 return 1;
2343 }
2344 }
2345
Daniel Dunbard4270232009-01-20 23:17:32 +00002346 if (!InheritanceViewCls.empty()) // C++ visualization?
Ted Kremenek7cae2f62008-10-23 23:36:29 +00002347 ProgAction = InheritanceView;
Mike Stump1eb44332009-09-09 15:08:12 +00002348
Ted Kremenekc0c03bc2008-06-06 22:42:39 +00002349 llvm::OwningPtr<SourceManager> SourceMgr;
Mike Stump1eb44332009-09-09 15:08:12 +00002350
Chris Lattner2c78b872009-04-14 23:22:57 +00002351 // Create a file manager object to provide access to and cache the filesystem.
2352 FileManager FileMgr;
Douglas Gregor4fed3f42009-04-27 18:38:38 +00002353
Daniel Dunbar868bd0a2009-05-06 03:16:41 +00002354 // Compute the feature set, unfortunately this effects the language!
2355 llvm::StringMap<bool> Features;
2356 ComputeFeatureMap(Target.get(), Features);
2357
Reid Spencer5f016e22007-07-11 17:01:13 +00002358 for (unsigned i = 0, e = InputFilenames.size(); i != e; ++i) {
Ted Kremenek31e703b2007-12-11 23:28:38 +00002359 const std::string &InFile = InputFilenames[i];
Mike Stump1eb44332009-09-09 15:08:12 +00002360
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +00002361 LangKind LK = GetLanguage(InFile);
2362 // AST inputs are handled specially.
2363 if (LK == langkind_ast) {
2364 ProcessASTInputFile(InFile, ProgAction, Features,
2365 Diags, FileMgr, Context);
2366 continue;
2367 }
2368
Chris Lattnerf63aea32009-03-04 21:40:56 +00002369 /// Create a SourceManager object. This tracks and owns all the file
2370 /// buffers allocated to a translation unit.
2371 if (!SourceMgr)
2372 SourceMgr.reset(new SourceManager());
2373 else
2374 SourceMgr->clearIDTables();
Mike Stump1eb44332009-09-09 15:08:12 +00002375
Chris Lattnerf63aea32009-03-04 21:40:56 +00002376 // Initialize language options, inferring file types from input filenames.
2377 LangOptions LangInfo;
Chris Lattner409d4e72009-04-17 20:40:01 +00002378 DiagClient->setLangOptions(&LangInfo);
Mike Stump1eb44332009-09-09 15:08:12 +00002379
Daniel Dunbar0b5b0da2009-04-01 05:09:09 +00002380 InitializeLangOptions(LangInfo, LK);
Daniel Dunbar868bd0a2009-05-06 03:16:41 +00002381 InitializeLanguageStandard(LangInfo, LK, Target.get(), Features);
Mike Stump1eb44332009-09-09 15:08:12 +00002382
Chris Lattnerf63aea32009-03-04 21:40:56 +00002383 // Process the -I options and set them in the HeaderInfo.
2384 HeaderSearch HeaderInfo(FileMgr);
Mike Stump1eb44332009-09-09 15:08:12 +00002385
2386
Chris Lattnerf63aea32009-03-04 21:40:56 +00002387 InitializeIncludePaths(argv[0], HeaderInfo, FileMgr, LangInfo);
Mike Stump1eb44332009-09-09 15:08:12 +00002388
Chris Lattnerf63aea32009-03-04 21:40:56 +00002389 // Set up the preprocessor with these options.
Eli Friedmanf086e3b2009-05-18 07:39:39 +00002390 DriverPreprocessorFactory PPFactory(Diags, LangInfo, *Target,
Chris Lattnerf63aea32009-03-04 21:40:56 +00002391 *SourceMgr.get(), HeaderInfo);
Mike Stump1eb44332009-09-09 15:08:12 +00002392
Chris Lattnerf63aea32009-03-04 21:40:56 +00002393 llvm::OwningPtr<Preprocessor> PP(PPFactory.CreatePreprocessor());
Mike Stump1eb44332009-09-09 15:08:12 +00002394
Chris Lattnerf63aea32009-03-04 21:40:56 +00002395 if (!PP)
2396 continue;
Ted Kremenekb4398aa2008-08-07 17:49:57 +00002397
Eli Friedmanb5c8f8b2009-05-19 03:35:57 +00002398 // Handle generating dependencies, if requested
2399 if (!DependencyFile.empty()) {
2400 llvm::raw_ostream *DependencyOS;
2401 if (DependencyTargets.empty()) {
2402 // FIXME: Use a proper diagnostic
Chris Lattner92bcc272009-08-23 02:59:41 +00002403 llvm::errs() << "-dependency-file requires at least one -MT option\n";
Eli Friedmanb5c8f8b2009-05-19 03:35:57 +00002404 HadErrors = true;
2405 continue;
2406 }
2407 std::string ErrStr;
2408 DependencyOS =
Dan Gohmanb044c472009-08-25 15:36:09 +00002409 new llvm::raw_fd_ostream(DependencyFile.c_str(), ErrStr);
Eli Friedmanb5c8f8b2009-05-19 03:35:57 +00002410 if (!ErrStr.empty()) {
2411 // FIXME: Use a proper diagnostic
Chris Lattner92bcc272009-08-23 02:59:41 +00002412 llvm::errs() << "unable to open dependency file: " + ErrStr;
Eli Friedmanb5c8f8b2009-05-19 03:35:57 +00002413 HadErrors = true;
2414 continue;
2415 }
2416
2417 AttachDependencyFileGen(PP.get(), DependencyOS, DependencyTargets,
2418 DependenciesIncludeSystemHeaders,
2419 PhonyDependencyTarget);
2420 }
2421
Chris Lattner1b63e4f2009-06-14 01:54:56 +00002422 if (ImplicitIncludePCH.empty()) {
2423 if (InitializeSourceManager(*PP.get(), InFile))
2424 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00002425
Chris Lattner1b63e4f2009-06-14 01:54:56 +00002426 // Initialize builtin info.
2427 PP->getBuiltinInfo().InitializeBuiltins(PP->getIdentifierTable(),
Chris Lattner1b63e4f2009-06-14 01:54:56 +00002428 PP->getLangOptions().NoBuiltin);
2429 }
Douglas Gregor14f79002009-04-10 03:52:48 +00002430
Chris Lattner409d4e72009-04-17 20:40:01 +00002431 if (!HTMLDiag.empty())
2432 ((PathDiagnosticClient*)DiagClient.get())->SetPreprocessor(PP.get());
Chris Lattnerf63aea32009-03-04 21:40:56 +00002433
2434 // Process the source file.
Owen Andersonc93f4982009-07-01 21:23:16 +00002435 ProcessInputFile(*PP, PPFactory, InFile, ProgAction, Features, Context);
Mike Stump1eb44332009-09-09 15:08:12 +00002436
Chris Lattner40469652009-04-17 20:16:08 +00002437 HeaderInfo.ClearFileInfo();
Chris Lattner409d4e72009-04-17 20:40:01 +00002438 DiagClient->setLangOptions(0);
Reid Spencer5f016e22007-07-11 17:01:13 +00002439 }
Chris Lattner11215192008-03-14 06:12:05 +00002440
Mike Stumpfc0fed32009-04-28 01:19:10 +00002441 if (!NoCaretDiagnostics)
2442 if (unsigned NumDiagnostics = Diags.getNumDiagnostics())
2443 fprintf(stderr, "%d diagnostic%s generated.\n", NumDiagnostics,
2444 (NumDiagnostics == 1 ? "" : "s"));
Mike Stump1eb44332009-09-09 15:08:12 +00002445
Reid Spencer5f016e22007-07-11 17:01:13 +00002446 if (Stats) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002447 FileMgr.PrintStats();
2448 fprintf(stderr, "\n");
2449 }
Chris Lattner75a97cb2009-04-17 21:05:01 +00002450
2451 delete ClangFrontendTimer;
2452 delete BuildLogFile;
Mike Stump1eb44332009-09-09 15:08:12 +00002453
Daniel Dunbar276373d2008-10-27 22:10:13 +00002454 // If verifying diagnostics and we reached here, all is well.
2455 if (VerifyDiagnostics)
2456 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002457
Daniel Dunbar524b86f2008-10-28 00:38:08 +00002458 // Managed static deconstruction. Useful for making things like
2459 // -time-passes usable.
2460 llvm::llvm_shutdown();
2461
Daniel Dunbarb0adbba2008-10-04 23:42:49 +00002462 return HadErrors || (Diags.getNumErrors() != 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00002463}