blob: 3e7c0262709977a9103d058767bde118afbf2566 [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.
Reid Spencer5f016e22007-07-11 17:01:13 +0000141 ParsePrintCallbacks, // Parse and print each callback.
142 ParseSyntaxOnly, // Parse and perform semantic analysis.
143 ParseNoop, // Parse with noop callbacks.
144 RunPreprocessorOnly, // Just lex, no output.
145 PrintPreprocessedInput, // -E mode.
Chris Lattnerc106c102008-10-12 05:03:36 +0000146 DumpTokens, // Dump out preprocessed tokens.
147 DumpRawTokens, // Dump out raw tokens.
Mike Stump1eb44332009-09-09 15:08:12 +0000148 RunAnalysis, // Run one or more source code analyses.
Douglas Gregorbf1bd6e2009-04-02 23:43:50 +0000149 GeneratePTH, // Generate pre-tokenized header.
Douglas Gregor2cf26342009-04-09 22:27:44 +0000150 GeneratePCH, // Generate pre-compiled header.
Ted Kremenek7cae2f62008-10-23 23:36:29 +0000151 InheritanceView // View C++ inheritance for a specified class.
Reid Spencer5f016e22007-07-11 17:01:13 +0000152};
153
Mike Stump1eb44332009-09-09 15:08:12 +0000154static llvm::cl::opt<ProgActions>
Reid Spencer5f016e22007-07-11 17:01:13 +0000155ProgAction(llvm::cl::desc("Choose output type:"), llvm::cl::ZeroOrMore,
156 llvm::cl::init(ParseSyntaxOnly),
157 llvm::cl::values(
158 clEnumValN(RunPreprocessorOnly, "Eonly",
159 "Just run preprocessor, no output (for timings)"),
160 clEnumValN(PrintPreprocessedInput, "E",
161 "Run preprocessor, emit preprocessed file"),
Chris Lattnerc106c102008-10-12 05:03:36 +0000162 clEnumValN(DumpRawTokens, "dump-raw-tokens",
163 "Lex file in raw mode and dump raw tokens"),
Daniel Dunbard4270232009-01-20 23:17:32 +0000164 clEnumValN(RunAnalysis, "analyze",
165 "Run static analysis engine"),
Chris Lattnerc106c102008-10-12 05:03:36 +0000166 clEnumValN(DumpTokens, "dump-tokens",
Reid Spencer5f016e22007-07-11 17:01:13 +0000167 "Run preprocessor, dump internal rep of tokens"),
168 clEnumValN(ParseNoop, "parse-noop",
169 "Run parser with noop callbacks (for timings)"),
170 clEnumValN(ParseSyntaxOnly, "fsyntax-only",
171 "Run parser and perform semantic analysis"),
172 clEnumValN(ParsePrintCallbacks, "parse-print-callbacks",
173 "Run parser and print each callback invoked"),
Ted Kremenek6a340832008-03-18 21:19:49 +0000174 clEnumValN(EmitHTML, "emit-html",
175 "Output input source as HTML"),
Chris Lattner3b427b32007-10-11 00:18:28 +0000176 clEnumValN(ASTPrint, "ast-print",
177 "Build ASTs and then pretty-print them"),
Douglas Gregoree75c052009-05-21 20:55:50 +0000178 clEnumValN(ASTPrintXML, "ast-print-xml",
179 "Build ASTs and then print them in XML format"),
Chris Lattner3b427b32007-10-11 00:18:28 +0000180 clEnumValN(ASTDump, "ast-dump",
181 "Build ASTs and then debug dump them"),
Chris Lattnerea254db2007-10-11 00:37:43 +0000182 clEnumValN(ASTView, "ast-view",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000183 "Build ASTs and view them with GraphViz"),
Zhongxing Xu2d75d6f2009-01-13 01:29:24 +0000184 clEnumValN(PrintDeclContext, "print-decl-contexts",
Ted Kremenek08478eb2009-04-01 00:23:28 +0000185 "Print DeclContexts and their Decls"),
Douglas Gregorbf1bd6e2009-04-02 23:43:50 +0000186 clEnumValN(GeneratePTH, "emit-pth",
Ted Kremenek08478eb2009-04-01 00:23:28 +0000187 "Generate pre-tokenized header file"),
Douglas Gregor2cf26342009-04-09 22:27:44 +0000188 clEnumValN(GeneratePCH, "emit-pch",
189 "Generate pre-compiled header file"),
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000190 clEnumValN(EmitAssembly, "S",
191 "Emit native assembly code"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000192 clEnumValN(EmitLLVM, "emit-llvm",
Ted Kremenek27b07c52007-09-06 21:26:58 +0000193 "Build ASTs then convert to LLVM, emit .ll file"),
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +0000194 clEnumValN(EmitBC, "emit-llvm-bc",
195 "Build ASTs then convert to LLVM, emit .bc file"),
Daniel Dunbare8e26002009-02-26 22:39:37 +0000196 clEnumValN(EmitLLVMOnly, "emit-llvm-only",
197 "Build ASTs and convert to LLVM, discarding output"),
Chris Lattnerb13c5ee2008-10-12 05:29:20 +0000198 clEnumValN(RewriteTest, "rewrite-test",
199 "Rewriter playground"),
Steve Naroffb29b4272008-04-14 22:03:09 +0000200 clEnumValN(RewriteObjC, "rewrite-objc",
Chris Lattnerb57e3d42008-05-08 06:52:13 +0000201 "Rewrite ObjC into C (code rewriter example)"),
202 clEnumValN(RewriteMacros, "rewrite-macros",
203 "Expand macros without full preprocessing"),
Steve Naroff13188952008-09-18 14:10:13 +0000204 clEnumValN(RewriteBlocks, "rewrite-blocks",
205 "Rewrite Blocks to C"),
Douglas Gregor558cb562009-04-02 01:08:08 +0000206 clEnumValN(FixIt, "fixit",
207 "Apply fix-it advice to the input source"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000208 clEnumValEnd));
209
Ted Kremenekccc76472007-12-19 19:47:59 +0000210
211static llvm::cl::opt<std::string>
212OutputFile("o",
Ted Kremenek50b56412007-12-19 19:50:41 +0000213 llvm::cl::value_desc("path"),
Douglas Gregor370187c2009-04-22 21:45:53 +0000214 llvm::cl::desc("Specify output file"));
Ted Kremenek55af98c2008-04-14 18:40:58 +0000215
Ted Kremenekc2e72992008-12-02 19:57:31 +0000216
Douglas Gregor81b747b2009-09-17 21:32:03 +0000217static llvm::cl::opt<int>
218DumpCodeCompletion("code-completion-dump",
219 llvm::cl::value_desc("N"),
220 llvm::cl::desc("Dump code-completion information at $$N$$"));
221
222/// \brief Buld a new code-completion consumer that prints the results of
223/// code completion to standard output.
224static CodeCompleteConsumer *BuildPrintingCodeCompleter(Sema &S, void *) {
225 return new PrintingCodeCompleteConsumer(S, llvm::outs());
226}
227
Ted Kremenekc2e72992008-12-02 19:57:31 +0000228//===----------------------------------------------------------------------===//
229// PTH.
230//===----------------------------------------------------------------------===//
231
232static llvm::cl::opt<std::string>
233TokenCache("token-cache", llvm::cl::value_desc("path"),
234 llvm::cl::desc("Use specified token cache file"));
235
Sanjiv Guptae8b9f5b2008-05-08 08:54:20 +0000236//===----------------------------------------------------------------------===//
Ted Kremenek55af98c2008-04-14 18:40:58 +0000237// Diagnostic Options
238//===----------------------------------------------------------------------===//
239
Ted Kremenek41193e42007-09-26 19:42:19 +0000240static llvm::cl::opt<bool>
241VerifyDiagnostics("verify",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000242 llvm::cl::desc("Verify emitted diagnostics and warnings"));
Ted Kremenek41193e42007-09-26 19:42:19 +0000243
Ted Kremenek88f5cde2008-03-27 06:17:42 +0000244static llvm::cl::opt<std::string>
245HTMLDiag("html-diags",
246 llvm::cl::desc("Generate HTML to report diagnostics"),
247 llvm::cl::value_desc("HTML directory"));
248
Nico Weberfd54ebc2008-08-05 23:33:20 +0000249static llvm::cl::opt<bool>
250NoShowColumn("fno-show-column",
251 llvm::cl::desc("Do not include column number on diagnostics"));
252
253static llvm::cl::opt<bool>
Chris Lattner65f5e642009-01-30 19:01:41 +0000254NoShowLocation("fno-show-source-location",
255 llvm::cl::desc("Do not include source location information with"
256 " diagnostics"));
257
258static llvm::cl::opt<bool>
Nico Weberfd54ebc2008-08-05 23:33:20 +0000259NoCaretDiagnostics("fno-caret-diagnostics",
260 llvm::cl::desc("Do not include source line and caret with"
261 " diagnostics"));
262
Chris Lattner1fbee5d2009-03-13 01:08:23 +0000263static llvm::cl::opt<bool>
Chris Lattneraa5bf2e2009-04-19 07:44:08 +0000264NoDiagnosticsFixIt("fno-diagnostics-fixit-info",
265 llvm::cl::desc("Do not include fixit information in"
266 " diagnostics"));
267
268static llvm::cl::opt<bool>
Chris Lattner182e0922009-04-21 05:34:31 +0000269PrintSourceRangeInfo("fdiagnostics-print-source-range-info",
270 llvm::cl::desc("Print source range spans in numeric form"));
271
Chris Lattnerd51d74a2009-04-16 05:44:38 +0000272static llvm::cl::opt<bool>
273PrintDiagnosticOption("fdiagnostics-show-option",
274 llvm::cl::desc("Print diagnostic name with mappable diagnostics"));
Nico Weberfd54ebc2008-08-05 23:33:20 +0000275
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000276static llvm::cl::opt<unsigned>
277MessageLength("fmessage-length",
Mike Stump1eb44332009-09-09 15:08:12 +0000278 llvm::cl::desc("Format message diagnostics so that they fit "
279 "within N columns or fewer, when possible."),
280 llvm::cl::value_desc("N"));
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000281
Torok Edwin603fca72009-06-04 07:18:23 +0000282static llvm::cl::opt<bool>
Torok Edwina46c71a2009-06-04 07:27:53 +0000283NoColorDiagnostic("fno-color-diagnostics",
Mike Stump1eb44332009-09-09 15:08:12 +0000284 llvm::cl::desc("Don't use colors when showing diagnostics "
Torok Edwin603fca72009-06-04 07:18:23 +0000285 "(automatically turned off if output is not a "
286 "terminal)."));
Reid Spencer5f016e22007-07-11 17:01:13 +0000287//===----------------------------------------------------------------------===//
Ted Kremenek7cae2f62008-10-23 23:36:29 +0000288// C++ Visualization.
289//===----------------------------------------------------------------------===//
290
291static llvm::cl::opt<std::string>
292InheritanceViewCls("cxx-inheritance-view",
293 llvm::cl::value_desc("class name"),
Daniel Dunbard77b2512009-01-14 18:56:36 +0000294 llvm::cl::desc("View C++ inheritance for a specified class"));
Ted Kremenek7cae2f62008-10-23 23:36:29 +0000295
296//===----------------------------------------------------------------------===//
Douglas Gregor3573c0c2009-02-14 20:49:29 +0000297// Builtin Options
298//===----------------------------------------------------------------------===//
Chris Lattnerb2509e12009-02-18 01:12:43 +0000299
300static llvm::cl::opt<bool>
301TimeReport("ftime-report",
302 llvm::cl::desc("Print the amount of time each "
303 "phase of compilation takes"));
304
Douglas Gregor3573c0c2009-02-14 20:49:29 +0000305static llvm::cl::opt<bool>
306Freestanding("ffreestanding",
Daniel Dunbaref2abfe2009-02-16 22:43:43 +0000307 llvm::cl::desc("Assert that the compilation takes place in a "
Douglas Gregor3573c0c2009-02-14 20:49:29 +0000308 "freestanding environment"));
309
Daniel Dunbaref2abfe2009-02-16 22:43:43 +0000310static llvm::cl::opt<bool>
Daniel Dunbar48d1ef72009-04-07 21:16:11 +0000311AllowBuiltins("fbuiltin", llvm::cl::init(true),
312 llvm::cl::desc("Disable implicit builtin knowledge of functions"));
Chris Lattner7644f072009-03-13 22:38:49 +0000313
314
315static llvm::cl::opt<bool>
Daniel Dunbar48d1ef72009-04-07 21:16:11 +0000316MathErrno("fmath-errno", llvm::cl::init(true),
317 llvm::cl::desc("Require math functions to respect errno"));
Daniel Dunbaref2abfe2009-02-16 22:43:43 +0000318
Douglas Gregor3573c0c2009-02-14 20:49:29 +0000319//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +0000320// Language Options
321//===----------------------------------------------------------------------===//
322
323enum LangKind {
324 langkind_unspecified,
325 langkind_c,
326 langkind_c_cpp,
Chris Lattnera778d7d2008-10-22 17:29:21 +0000327 langkind_asm_cpp,
Reid Spencer5f016e22007-07-11 17:01:13 +0000328 langkind_cxx,
329 langkind_cxx_cpp,
330 langkind_objc,
331 langkind_objc_cpp,
332 langkind_objcxx,
Nate Begeman4e3629e2009-06-25 22:43:10 +0000333 langkind_objcxx_cpp,
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +0000334 langkind_ocl,
335 langkind_ast
Reid Spencer5f016e22007-07-11 17:01:13 +0000336};
337
Reid Spencer5f016e22007-07-11 17:01:13 +0000338static llvm::cl::opt<LangKind>
339BaseLang("x", llvm::cl::desc("Base language to compile"),
340 llvm::cl::init(langkind_unspecified),
341 llvm::cl::values(clEnumValN(langkind_c, "c", "C"),
Nate Begeman4e3629e2009-06-25 22:43:10 +0000342 clEnumValN(langkind_ocl, "cl", "OpenCL C"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000343 clEnumValN(langkind_cxx, "c++", "C++"),
344 clEnumValN(langkind_objc, "objective-c", "Objective C"),
345 clEnumValN(langkind_objcxx,"objective-c++","Objective C++"),
Daniel Dunbard2ea3862009-01-29 23:50:47 +0000346 clEnumValN(langkind_c_cpp, "cpp-output",
Reid Spencer5f016e22007-07-11 17:01:13 +0000347 "Preprocessed C"),
Chris Lattnera778d7d2008-10-22 17:29:21 +0000348 clEnumValN(langkind_asm_cpp, "assembler-with-cpp",
349 "Preprocessed asm"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000350 clEnumValN(langkind_cxx_cpp, "c++-cpp-output",
Chris Lattnerc76d8072009-02-06 06:19:20 +0000351 "Preprocessed C++"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000352 clEnumValN(langkind_objc_cpp, "objective-c-cpp-output",
353 "Preprocessed Objective C"),
Chris Lattnerc76d8072009-02-06 06:19:20 +0000354 clEnumValN(langkind_objcxx_cpp, "objective-c++-cpp-output",
Reid Spencer5f016e22007-07-11 17:01:13 +0000355 "Preprocessed Objective C++"),
Daniel Dunbar0b5b0da2009-04-01 05:09:09 +0000356 clEnumValN(langkind_c, "c-header",
357 "C header"),
358 clEnumValN(langkind_objc, "objective-c-header",
359 "Objective-C header"),
360 clEnumValN(langkind_cxx, "c++-header",
361 "C++ header"),
362 clEnumValN(langkind_objcxx, "objective-c++-header",
363 "Objective-C++ header"),
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +0000364 clEnumValN(langkind_ast, "ast",
365 "Clang AST"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000366 clEnumValEnd));
367
368static llvm::cl::opt<bool>
Chris Lattner2c78b872009-04-14 23:22:57 +0000369ObjCExclusiveGC("fobjc-gc-only",
370 llvm::cl::desc("Use GC exclusively for Objective-C related "
371 "memory management"));
372
David Chisnall8a5a9aa2009-08-31 16:41:57 +0000373static llvm::cl::opt<std::string>
374ObjCConstantStringClass("fconstant-string-class",
375 llvm::cl::value_desc("class name"),
376 llvm::cl::desc("Specify the class to use for constant "
377 "Objective-C string objects."));
378
Chris Lattner2c78b872009-04-14 23:22:57 +0000379static llvm::cl::opt<bool>
380ObjCEnableGC("fobjc-gc",
381 llvm::cl::desc("Enable Objective-C garbage collection"));
382
Fariborz Jahanian448f5e62009-04-17 03:04:15 +0000383static llvm::cl::opt<bool>
Fariborz Jahanianb123ea32009-09-16 21:37:16 +0000384ObjCEnableNewGCAPI("fobjc-newgc-api",
385 llvm::cl::desc("Enable Objective-C garbage collection's new API"));
386
387static llvm::cl::opt<bool>
Fariborz Jahanian448f5e62009-04-17 03:04:15 +0000388ObjCEnableGCBitmapPrint("print-ivar-layout",
389 llvm::cl::desc("Enable Objective-C Ivar layout bitmap print trace"));
390
Chris Lattner2c78b872009-04-14 23:22:57 +0000391static llvm::cl::opt<LangOptions::VisibilityMode>
392SymbolVisibility("fvisibility",
393 llvm::cl::desc("Set the default symbol visibility:"),
394 llvm::cl::init(LangOptions::Default),
395 llvm::cl::values(clEnumValN(LangOptions::Default, "default",
396 "Use default symbol visibility"),
397 clEnumValN(LangOptions::Hidden, "hidden",
398 "Use hidden symbol visibility"),
399 clEnumValN(LangOptions::Protected,"protected",
400 "Use protected symbol visibility"),
401 clEnumValEnd));
402
403static llvm::cl::opt<bool>
404OverflowChecking("ftrapv",
405 llvm::cl::desc("Trap on integer overflow"),
406 llvm::cl::init(false));
407
Fariborz Jahanian34e65772009-05-22 20:17:16 +0000408static llvm::cl::opt<bool>
Nate Begeman2ef13e52009-08-10 23:49:36 +0000409AltiVec("faltivec", llvm::cl::desc("Enable AltiVec vector initializer syntax"),
410 llvm::cl::init(false));
411
412static llvm::cl::opt<bool>
Daniel Dunbar5345c392009-09-03 04:54:28 +0000413PThread("pthread", llvm::cl::desc("Support POSIX threads in generated code"),
414 llvm::cl::init(false));
415
Daniel Dunbar13fdf282009-09-17 00:47:46 +0000416static LangKind GetLanguage(llvm::StringRef Filename) {
Ted Kremenek8904f152007-12-05 23:49:08 +0000417 if (BaseLang != langkind_unspecified)
418 return BaseLang;
Mike Stump1eb44332009-09-09 15:08:12 +0000419
Daniel Dunbar13fdf282009-09-17 00:47:46 +0000420 llvm::StringRef Ext = Filename.rsplit('.').second;
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +0000421 if (Ext == "ast")
422 return langkind_ast;
423 else if (Ext == "c")
Ted Kremenek8904f152007-12-05 23:49:08 +0000424 return langkind_c;
Daniel Dunbar9f435342009-09-17 00:47:27 +0000425 else if (Ext == "S" || Ext == "s")
Chris Lattnera778d7d2008-10-22 17:29:21 +0000426 return langkind_asm_cpp;
Ted Kremenek8904f152007-12-05 23:49:08 +0000427 else if (Ext == "i")
428 return langkind_c_cpp;
429 else if (Ext == "ii")
430 return langkind_cxx_cpp;
431 else if (Ext == "m")
432 return langkind_objc;
433 else if (Ext == "mi")
434 return langkind_objc_cpp;
435 else if (Ext == "mm" || Ext == "M")
436 return langkind_objcxx;
437 else if (Ext == "mii")
438 return langkind_objcxx_cpp;
439 else if (Ext == "C" || Ext == "cc" || Ext == "cpp" || Ext == "CPP" ||
440 Ext == "c++" || Ext == "cp" || Ext == "cxx")
441 return langkind_cxx;
Nate Begeman4e3629e2009-06-25 22:43:10 +0000442 else if (Ext == "cl")
443 return langkind_ocl;
Ted Kremenek8904f152007-12-05 23:49:08 +0000444 else
445 return langkind_c;
446}
447
448
Ted Kremenek85888962008-10-21 00:54:44 +0000449static void InitializeCOptions(LangOptions &Options) {
450 // Do nothing.
451}
452
453static void InitializeObjCOptions(LangOptions &Options) {
454 Options.ObjC1 = Options.ObjC2 = 1;
455}
Mike Stump1eb44332009-09-09 15:08:12 +0000456
Ted Kremenek85888962008-10-21 00:54:44 +0000457
Daniel Dunbar0b5b0da2009-04-01 05:09:09 +0000458static void InitializeLangOptions(LangOptions &Options, LangKind LK){
Reid Spencer5f016e22007-07-11 17:01:13 +0000459 // FIXME: implement -fpreprocessed mode.
460 bool NoPreprocess = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000461
Ted Kremenek8904f152007-12-05 23:49:08 +0000462 switch (LK) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000463 default: assert(0 && "Unknown language kind!");
Chris Lattnera778d7d2008-10-22 17:29:21 +0000464 case langkind_asm_cpp:
Daniel Dunbarc1571452008-12-01 18:55:22 +0000465 Options.AsmPreprocessor = 1;
Chris Lattnera778d7d2008-10-22 17:29:21 +0000466 // FALLTHROUGH
Reid Spencer5f016e22007-07-11 17:01:13 +0000467 case langkind_c_cpp:
468 NoPreprocess = true;
469 // FALLTHROUGH
470 case langkind_c:
Ted Kremenek85888962008-10-21 00:54:44 +0000471 InitializeCOptions(Options);
Reid Spencer5f016e22007-07-11 17:01:13 +0000472 break;
473 case langkind_cxx_cpp:
474 NoPreprocess = true;
475 // FALLTHROUGH
476 case langkind_cxx:
477 Options.CPlusPlus = 1;
478 break;
479 case langkind_objc_cpp:
480 NoPreprocess = true;
481 // FALLTHROUGH
482 case langkind_objc:
Ted Kremenek85888962008-10-21 00:54:44 +0000483 InitializeObjCOptions(Options);
Reid Spencer5f016e22007-07-11 17:01:13 +0000484 break;
485 case langkind_objcxx_cpp:
486 NoPreprocess = true;
487 // FALLTHROUGH
488 case langkind_objcxx:
489 Options.ObjC1 = Options.ObjC2 = 1;
490 Options.CPlusPlus = 1;
491 break;
Nate Begeman4e3629e2009-06-25 22:43:10 +0000492 case langkind_ocl:
493 Options.OpenCL = 1;
494 Options.AltiVec = 1;
495 Options.CXXOperatorNames = 1;
496 Options.LaxVectorConversions = 1;
497 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000498 }
Mike Stump1eb44332009-09-09 15:08:12 +0000499
Chris Lattner2c78b872009-04-14 23:22:57 +0000500 if (ObjCExclusiveGC)
501 Options.setGCMode(LangOptions::GCOnly);
502 else if (ObjCEnableGC)
503 Options.setGCMode(LangOptions::HybridGC);
Mike Stump1eb44332009-09-09 15:08:12 +0000504
Fariborz Jahanianb123ea32009-09-16 21:37:16 +0000505 if (ObjCEnableNewGCAPI)
506 Options.ObjCNewGCAPI = 1;
507
Fariborz Jahanian448f5e62009-04-17 03:04:15 +0000508 if (ObjCEnableGCBitmapPrint)
509 Options.ObjCGCBitmapPrint = 1;
Mike Stump1eb44332009-09-09 15:08:12 +0000510
Nate Begeman2ef13e52009-08-10 23:49:36 +0000511 if (AltiVec)
512 Options.AltiVec = 1;
Daniel Dunbar5345c392009-09-03 04:54:28 +0000513
514 if (PThread)
515 Options.POSIXThreads = 1;
Mike Stump1eb44332009-09-09 15:08:12 +0000516
Chris Lattner2c78b872009-04-14 23:22:57 +0000517 Options.setVisibilityMode(SymbolVisibility);
518 Options.OverflowChecking = OverflowChecking;
Reid Spencer5f016e22007-07-11 17:01:13 +0000519}
520
521/// LangStds - Language standards we support.
522enum LangStds {
Mike Stump1eb44332009-09-09 15:08:12 +0000523 lang_unspecified,
Reid Spencer5f016e22007-07-11 17:01:13 +0000524 lang_c89, lang_c94, lang_c99,
Ted Kremenekea644d82008-09-03 21:22:16 +0000525 lang_gnu_START,
526 lang_gnu89 = lang_gnu_START, lang_gnu99,
Chris Lattnerd4b80f12007-07-16 04:18:29 +0000527 lang_cxx98, lang_gnucxx98,
528 lang_cxx0x, lang_gnucxx0x
Reid Spencer5f016e22007-07-11 17:01:13 +0000529};
530
531static llvm::cl::opt<LangStds>
532LangStd("std", llvm::cl::desc("Language standard to compile for"),
533 llvm::cl::init(lang_unspecified),
534 llvm::cl::values(clEnumValN(lang_c89, "c89", "ISO C 1990"),
535 clEnumValN(lang_c89, "c90", "ISO C 1990"),
536 clEnumValN(lang_c89, "iso9899:1990", "ISO C 1990"),
537 clEnumValN(lang_c94, "iso9899:199409",
538 "ISO C 1990 with amendment 1"),
539 clEnumValN(lang_c99, "c99", "ISO C 1999"),
Chris Lattner50748f42009-04-06 17:17:55 +0000540 clEnumValN(lang_c99, "c9x", "ISO C 1999"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000541 clEnumValN(lang_c99, "iso9899:1999", "ISO C 1999"),
Chris Lattner50748f42009-04-06 17:17:55 +0000542 clEnumValN(lang_c99, "iso9899:199x", "ISO C 1999"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000543 clEnumValN(lang_gnu89, "gnu89",
Gabor Greif10b26142009-02-28 09:22:15 +0000544 "ISO C 1990 with GNU extensions"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000545 clEnumValN(lang_gnu99, "gnu99",
Gabor Greif10b26142009-02-28 09:22:15 +0000546 "ISO C 1999 with GNU extensions (default for C)"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000547 clEnumValN(lang_gnu99, "gnu9x",
548 "ISO C 1999 with GNU extensions"),
549 clEnumValN(lang_cxx98, "c++98",
550 "ISO C++ 1998 with amendments"),
551 clEnumValN(lang_gnucxx98, "gnu++98",
552 "ISO C++ 1998 with amendments and GNU "
553 "extensions (default for C++)"),
Chris Lattnerd4b80f12007-07-16 04:18:29 +0000554 clEnumValN(lang_cxx0x, "c++0x",
555 "Upcoming ISO C++ 200x with amendments"),
556 clEnumValN(lang_gnucxx0x, "gnu++0x",
557 "Upcoming ISO C++ 200x with amendments and GNU "
Gabor Greif5f8d1db2009-03-11 23:07:18 +0000558 "extensions"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000559 clEnumValEnd));
560
561static llvm::cl::opt<bool>
562NoOperatorNames("fno-operator-names",
563 llvm::cl::desc("Do not treat C++ operator name keywords as "
564 "synonyms for operators"));
565
Anders Carlssonee98ac52007-10-15 02:50:23 +0000566static llvm::cl::opt<bool>
567PascalStrings("fpascal-strings",
568 llvm::cl::desc("Recognize and construct Pascal-style "
569 "string literals"));
Mike Stump1eb44332009-09-09 15:08:12 +0000570
Steve Naroffd62701b2008-02-07 03:50:06 +0000571static llvm::cl::opt<bool>
572MSExtensions("fms-extensions",
573 llvm::cl::desc("Accept some non-standard constructs used in "
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000574 "Microsoft header files "));
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000575
576static llvm::cl::opt<bool>
577WritableStrings("fwritable-strings",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000578 llvm::cl::desc("Store string literals as writable data"));
Anders Carlsson695dbb62007-11-30 04:21:22 +0000579
580static llvm::cl::opt<bool>
Anders Carlssonad53eff2009-01-30 23:26:40 +0000581NoLaxVectorConversions("fno-lax-vector-conversions",
Anders Carlssonb0f90cc2009-01-30 23:17:46 +0000582 llvm::cl::desc("Disallow implicit conversions between "
583 "vectors with a different number of "
584 "elements or different element types"));
Chris Lattnerae0ee032008-12-04 23:20:07 +0000585
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000586static llvm::cl::opt<bool>
Daniel Dunbar48d1ef72009-04-07 21:16:11 +0000587EnableBlocks("fblocks", llvm::cl::desc("enable the 'blocks' language feature"));
Mike Stumpa0f02aa2009-02-02 22:57:57 +0000588
589static llvm::cl::opt<bool>
Chris Lattner810f6d52009-03-13 17:38:01 +0000590EnableHeinousExtensions("fheinous-gnu-extensions",
591 llvm::cl::desc("enable GNU extensions that you really really shouldn't use"),
592 llvm::cl::ValueDisallowed, llvm::cl::Hidden);
593
594static llvm::cl::opt<bool>
Mike Stumpa0f02aa2009-02-02 22:57:57 +0000595ObjCNonFragileABI("fobjc-nonfragile-abi",
596 llvm::cl::desc("enable objective-c's nonfragile abi"));
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000597
Daniel Dunbard6884a02009-05-04 05:16:21 +0000598
599static llvm::cl::opt<bool>
Daniel Dunbard604c402009-02-04 21:19:06 +0000600EmitAllDecls("femit-all-decls",
601 llvm::cl::desc("Emit all declarations, even if unused"));
Ted Kremenek01d9dbf2008-04-29 04:37:03 +0000602
Daniel Dunbar6379a7a2008-08-11 17:36:14 +0000603static llvm::cl::opt<bool>
604Exceptions("fexceptions",
Chris Lattnerf5db8f82009-04-19 07:00:02 +0000605 llvm::cl::desc("Enable support for exception handling"));
Daniel Dunbar6379a7a2008-08-11 17:36:14 +0000606
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000607static llvm::cl::opt<bool>
Mike Stump738f8c22009-07-31 23:15:31 +0000608Rtti("frtti", llvm::cl::init(true),
609 llvm::cl::desc("Enable generation of rtti information"));
610
611static llvm::cl::opt<bool>
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000612GNURuntime("fgnu-runtime",
Ted Kremenek85888962008-10-21 00:54:44 +0000613 llvm::cl::desc("Generate output compatible with the standard GNU "
Chris Lattnerf5db8f82009-04-19 07:00:02 +0000614 "Objective-C runtime"));
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000615
616static llvm::cl::opt<bool>
617NeXTRuntime("fnext-runtime",
Ted Kremenek85888962008-10-21 00:54:44 +0000618 llvm::cl::desc("Generate output compatible with the NeXT "
Chris Lattnerf5db8f82009-04-19 07:00:02 +0000619 "runtime"));
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000620
Eli Friedmanc4757bd2009-06-05 07:12:17 +0000621static llvm::cl::opt<bool>
622CharIsSigned("fsigned-char",
623 llvm::cl::desc("Force char to be a signed/unsigned type"));
Ted Kremenekea644d82008-09-03 21:22:16 +0000624
625
626static llvm::cl::opt<bool>
Chris Lattnerf5db8f82009-04-19 07:00:02 +0000627Trigraphs("trigraphs", llvm::cl::desc("Process trigraph sequences"));
Ted Kremenekea644d82008-09-03 21:22:16 +0000628
Douglas Gregor26dce442009-03-10 00:06:19 +0000629static llvm::cl::opt<unsigned>
630TemplateDepth("ftemplate-depth", llvm::cl::init(99),
631 llvm::cl::desc("Maximum depth of recursive template "
632 "instantiation"));
Chris Lattnerf5db8f82009-04-19 07:00:02 +0000633static llvm::cl::opt<bool>
634DollarsInIdents("fdollars-in-identifiers",
635 llvm::cl::desc("Allow '$' in identifiers"));
Chris Lattner16167a62009-03-02 22:11:07 +0000636
Anders Carlsson4ca076f2009-04-06 17:37:10 +0000637
638static llvm::cl::opt<bool>
639OptSize("Os", llvm::cl::desc("Optimize for size"));
640
641static llvm::cl::opt<bool>
Mike Stump1eb44332009-09-09 15:08:12 +0000642DisableLLVMOptimizations("disable-llvm-optzns",
Daniel Dunbar877db382009-06-02 22:07:45 +0000643 llvm::cl::desc("Don't run LLVM optimization passes"));
644
645static llvm::cl::opt<bool>
Anders Carlsson4ca076f2009-04-06 17:37:10 +0000646NoCommon("fno-common",
647 llvm::cl::desc("Compile common globals like normal definitions"),
648 llvm::cl::ValueDisallowed);
649
Daniel Dunbarc9abc042009-04-08 05:11:16 +0000650static llvm::cl::opt<std::string>
651MainFileName("main-file-name",
652 llvm::cl::desc("Main file name to use for debug info"));
Anders Carlsson4ca076f2009-04-06 17:37:10 +0000653
Anders Carlssona33d9b42009-05-13 19:49:53 +0000654// FIXME: Also add an "-fno-access-control" option.
655static llvm::cl::opt<bool>
Mike Stump1eb44332009-09-09 15:08:12 +0000656AccessControl("faccess-control",
Anders Carlssona33d9b42009-05-13 19:49:53 +0000657 llvm::cl::desc("Enable C++ access control"));
658
Anders Carlsson92f58222009-08-22 22:30:33 +0000659static llvm::cl::opt<bool>
660NoElideConstructors("fno-elide-constructors",
661 llvm::cl::desc("Disable C++ copy constructor elision"));
662
Daniel Dunbar73b79592009-09-14 00:02:12 +0000663static llvm::cl::opt<std::string>
664TargetABI("target-abi",
665 llvm::cl::desc("Target a particular ABI type"));
666
Anders Carlsson92f58222009-08-22 22:30:33 +0000667
Anders Carlsson4ca076f2009-04-06 17:37:10 +0000668// It might be nice to add bounds to the CommandLine library directly.
669struct OptLevelParser : public llvm::cl::parser<unsigned> {
Chris Lattner59b21722009-09-20 00:39:15 +0000670 bool parse(llvm::cl::Option &O, llvm::StringRef ArgName,
671 llvm::StringRef Arg, unsigned &Val) {
Anders Carlsson4ca076f2009-04-06 17:37:10 +0000672 if (llvm::cl::parser<unsigned>::parse(O, ArgName, Arg, Val))
673 return true;
Anders Carlsson4ca076f2009-04-06 17:37:10 +0000674 if (Val > 3)
Benjamin Kramer21fde992009-08-02 12:12:11 +0000675 return O.error("'" + Arg + "' invalid optimization level!");
Anders Carlsson4ca076f2009-04-06 17:37:10 +0000676 return false;
677 }
678};
679static llvm::cl::opt<unsigned, false, OptLevelParser>
680OptLevel("O", llvm::cl::Prefix,
681 llvm::cl::desc("Optimization level"),
682 llvm::cl::init(0));
683
Daniel Dunbar9fd0b1f2009-04-08 03:03:23 +0000684static llvm::cl::opt<unsigned>
Daniel Dunbar3bbc7532009-04-08 18:03:55 +0000685PICLevel("pic-level", llvm::cl::desc("Value for __PIC__"));
686
687static llvm::cl::opt<bool>
688StaticDefine("static-define", llvm::cl::desc("Should __STATIC__ be defined"));
Daniel Dunbar9fd0b1f2009-04-08 03:03:23 +0000689
Bill Wendling45483f72009-06-28 07:36:13 +0000690static llvm::cl::opt<int>
691StackProtector("stack-protector",
692 llvm::cl::desc("Enable stack protectors"),
693 llvm::cl::init(-1));
694
Daniel Dunbardcb4a1a2008-08-23 08:43:39 +0000695static void InitializeLanguageStandard(LangOptions &Options, LangKind LK,
Daniel Dunbar868bd0a2009-05-06 03:16:41 +0000696 TargetInfo *Target,
697 const llvm::StringMap<bool> &Features) {
Chris Lattner8fc4dfb2008-12-04 22:54:33 +0000698 // Allow the target to set the default the langauge options as it sees fit.
699 Target->getDefaultLangOptions(Options);
Daniel Dunbar868bd0a2009-05-06 03:16:41 +0000700
701 // Pass the map of target features to the target for validation and
702 // processing.
703 Target->HandleTargetFeatures(Features);
Mike Stump1eb44332009-09-09 15:08:12 +0000704
Reid Spencer5f016e22007-07-11 17:01:13 +0000705 if (LangStd == lang_unspecified) {
706 // Based on the base language, pick one.
Ted Kremenek8904f152007-12-05 23:49:08 +0000707 switch (LK) {
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +0000708 case langkind_ast: assert(0 && "Invalid call for AST inputs");
Ted Kremenekf2a17b12009-03-19 19:02:20 +0000709 case lang_unspecified: assert(0 && "Unknown base language");
Nate Begeman4e3629e2009-06-25 22:43:10 +0000710 case langkind_ocl:
711 LangStd = lang_c99;
712 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000713 case langkind_c:
Chris Lattnera778d7d2008-10-22 17:29:21 +0000714 case langkind_asm_cpp:
Reid Spencer5f016e22007-07-11 17:01:13 +0000715 case langkind_c_cpp:
716 case langkind_objc:
717 case langkind_objc_cpp:
718 LangStd = lang_gnu99;
719 break;
720 case langkind_cxx:
721 case langkind_cxx_cpp:
722 case langkind_objcxx:
723 case langkind_objcxx_cpp:
724 LangStd = lang_gnucxx98;
725 break;
726 }
727 }
Mike Stump1eb44332009-09-09 15:08:12 +0000728
Reid Spencer5f016e22007-07-11 17:01:13 +0000729 switch (LangStd) {
730 default: assert(0 && "Unknown language standard!");
731
732 // Fall through from newer standards to older ones. This isn't really right.
733 // FIXME: Enable specifically the right features based on the language stds.
Chris Lattnerd4b80f12007-07-16 04:18:29 +0000734 case lang_gnucxx0x:
735 case lang_cxx0x:
736 Options.CPlusPlus0x = 1;
737 // FALL THROUGH
Reid Spencer5f016e22007-07-11 17:01:13 +0000738 case lang_gnucxx98:
739 case lang_cxx98:
740 Options.CPlusPlus = 1;
741 Options.CXXOperatorNames = !NoOperatorNames;
742 // FALL THROUGH.
743 case lang_gnu99:
744 case lang_c99:
Reid Spencer5f016e22007-07-11 17:01:13 +0000745 Options.C99 = 1;
746 Options.HexFloats = 1;
747 // FALL THROUGH.
748 case lang_gnu89:
749 Options.BCPLComment = 1; // Only for C99/C++.
750 // FALL THROUGH.
751 case lang_c94:
Chris Lattner3426b9b2008-02-25 04:01:39 +0000752 Options.Digraphs = 1; // C94, C99, C++.
753 // FALL THROUGH.
Reid Spencer5f016e22007-07-11 17:01:13 +0000754 case lang_c89:
755 break;
756 }
Argyrios Kyrtzidisd1465522008-09-11 04:21:06 +0000757
Chris Lattner7e9c90b2009-03-20 15:44:26 +0000758 // GNUMode - Set if we're in gnu99, gnu89, gnucxx98, etc.
759 Options.GNUMode = LangStd >= lang_gnu_START;
Mike Stump1eb44332009-09-09 15:08:12 +0000760
Argyrios Kyrtzidisd1465522008-09-11 04:21:06 +0000761 if (Options.CPlusPlus) {
762 Options.C99 = 0;
Eli Friedmanab24c8d2009-08-26 20:15:14 +0000763 Options.HexFloats = 0;
Argyrios Kyrtzidisd1465522008-09-11 04:21:06 +0000764 }
Mike Stump1eb44332009-09-09 15:08:12 +0000765
Chris Lattnerd658b562008-04-05 06:32:51 +0000766 if (LangStd == lang_c89 || LangStd == lang_c94 || LangStd == lang_gnu89)
767 Options.ImplicitInt = 1;
768 else
769 Options.ImplicitInt = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000770
Daniel Dunbard573d262009-04-07 22:13:21 +0000771 // Mimicing gcc's behavior, trigraphs are only enabled if -trigraphs
772 // is specified, or -std is set to a conforming mode.
Chris Lattner7e9c90b2009-03-20 15:44:26 +0000773 Options.Trigraphs = !Options.GNUMode;
Chris Lattner802db9b2008-12-05 00:10:44 +0000774 if (Trigraphs.getPosition())
Chris Lattner7e9c90b2009-03-20 15:44:26 +0000775 Options.Trigraphs = Trigraphs; // Command line option wins if specified.
Ted Kremenekea644d82008-09-03 21:22:16 +0000776
Chris Lattner802db9b2008-12-05 00:10:44 +0000777 // If in a conformant language mode (e.g. -std=c99) Blocks defaults to off
778 // even if they are normally on for the target. In GNU modes (e.g.
779 // -std=gnu99) the default for blocks depends on the target settings.
Anders Carlssone56f6ff2009-01-21 18:47:36 +0000780 // However, blocks are not turned off when compiling Obj-C or Obj-C++ code.
Chris Lattner7e9c90b2009-03-20 15:44:26 +0000781 if (!Options.ObjC1 && !Options.GNUMode)
Chris Lattner802db9b2008-12-05 00:10:44 +0000782 Options.Blocks = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000783
Chris Lattner01638a62009-04-19 07:06:52 +0000784 // Default to not accepting '$' in identifiers when preprocessing assembler,
785 // but do accept when preprocessing C. FIXME: these defaults are right for
786 // darwin, are they right everywhere?
787 Options.DollarIdents = LK != langkind_asm_cpp;
788 if (DollarsInIdents.getPosition()) // Explicit setting overrides default.
Chris Lattnerf5db8f82009-04-19 07:00:02 +0000789 Options.DollarIdents = DollarsInIdents;
Mike Stump1eb44332009-09-09 15:08:12 +0000790
Chris Lattnerae0ee032008-12-04 23:20:07 +0000791 if (PascalStrings.getPosition())
792 Options.PascalStrings = PascalStrings;
Eli Friedmanabc4e322009-06-08 06:11:14 +0000793 if (MSExtensions.getPosition())
794 Options.Microsoft = MSExtensions;
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000795 Options.WritableStrings = WritableStrings;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +0000796 if (NoLaxVectorConversions.getPosition())
797 Options.LaxVectorConversions = 0;
Daniel Dunbar6379a7a2008-08-11 17:36:14 +0000798 Options.Exceptions = Exceptions;
Mike Stump738f8c22009-07-31 23:15:31 +0000799 Options.Rtti = Rtti;
Mike Stumpa0f02aa2009-02-02 22:57:57 +0000800 if (EnableBlocks.getPosition())
Chris Lattnerae0ee032008-12-04 23:20:07 +0000801 Options.Blocks = EnableBlocks;
Eli Friedmanc4757bd2009-06-05 07:12:17 +0000802 if (CharIsSigned.getPosition())
803 Options.CharIsSigned = CharIsSigned;
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000804
Daniel Dunbar9f9768c2009-03-20 23:49:28 +0000805 if (!AllowBuiltins)
Chris Lattner7644f072009-03-13 22:38:49 +0000806 Options.NoBuiltin = 1;
Douglas Gregor3573c0c2009-02-14 20:49:29 +0000807 if (Freestanding)
Chris Lattner7644f072009-03-13 22:38:49 +0000808 Options.Freestanding = Options.NoBuiltin = 1;
Mike Stump1eb44332009-09-09 15:08:12 +0000809
Chris Lattner810f6d52009-03-13 17:38:01 +0000810 if (EnableHeinousExtensions)
811 Options.HeinousExtensions = 1;
Douglas Gregor3573c0c2009-02-14 20:49:29 +0000812
Anders Carlssona33d9b42009-05-13 19:49:53 +0000813 if (AccessControl)
814 Options.AccessControl = 1;
Mike Stump1eb44332009-09-09 15:08:12 +0000815
Anders Carlsson92f58222009-08-22 22:30:33 +0000816 Options.ElideConstructors = !NoElideConstructors;
Mike Stump1eb44332009-09-09 15:08:12 +0000817
Chris Lattnere4f21422009-06-30 01:26:17 +0000818 // OpenCL and C++ both have bool, true, false keywords.
819 Options.Bool = Options.OpenCL | Options.CPlusPlus;
Mike Stump1eb44332009-09-09 15:08:12 +0000820
Daniel Dunbaref2abfe2009-02-16 22:43:43 +0000821 Options.MathErrno = MathErrno;
822
Douglas Gregor26dce442009-03-10 00:06:19 +0000823 Options.InstantiationDepth = TemplateDepth;
824
Chris Lattner8fc4dfb2008-12-04 22:54:33 +0000825 // Override the default runtime if the user requested it.
826 if (NeXTRuntime)
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000827 Options.NeXTRuntime = 1;
Chris Lattner8fc4dfb2008-12-04 22:54:33 +0000828 else if (GNURuntime)
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000829 Options.NeXTRuntime = 0;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000830
David Chisnall8a5a9aa2009-08-31 16:41:57 +0000831 if (!ObjCConstantStringClass.empty())
832 Options.ObjCConstantStringClass = ObjCConstantStringClass.c_str();
833
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000834 if (ObjCNonFragileABI)
835 Options.ObjCNonFragileABI = 1;
Fariborz Jahanian34e65772009-05-22 20:17:16 +0000836
Daniel Dunbard604c402009-02-04 21:19:06 +0000837 if (EmitAllDecls)
838 Options.EmitAllDecls = 1;
Anders Carlsson4ca076f2009-04-06 17:37:10 +0000839
Daniel Dunbar3bbc7532009-04-08 18:03:55 +0000840 // The __OPTIMIZE_SIZE__ define is tied to -Oz, which we don't
841 // support.
842 Options.OptimizeSize = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000843
Anders Carlsson4ca076f2009-04-06 17:37:10 +0000844 // -Os implies -O2
Daniel Dunbar3bbc7532009-04-08 18:03:55 +0000845 if (OptSize || OptLevel)
Anders Carlsson4ca076f2009-04-06 17:37:10 +0000846 Options.Optimize = 1;
Daniel Dunbar9fd0b1f2009-04-08 03:03:23 +0000847
848 assert(PICLevel <= 2 && "Invalid value for -pic-level");
849 Options.PICLevel = PICLevel;
Daniel Dunbarc9abc042009-04-08 05:11:16 +0000850
Daniel Dunbar3bbc7532009-04-08 18:03:55 +0000851 Options.GNUInline = !Options.C99;
Mike Stump1eb44332009-09-09 15:08:12 +0000852 // FIXME: This is affected by other options (-fno-inline).
Daniel Dunbar3bbc7532009-04-08 18:03:55 +0000853 Options.NoInline = !OptSize && !OptLevel;
854
855 Options.Static = StaticDefine;
856
Bill Wendling4ebe3e42009-06-28 23:01:01 +0000857 switch (StackProtector) {
858 default:
859 assert(StackProtector <= 2 && "Invalid value for -stack-protector");
860 case -1: break;
861 case 0: Options.setStackProtectorMode(LangOptions::SSPOff); break;
862 case 1: Options.setStackProtectorMode(LangOptions::SSPOn); break;
863 case 2: Options.setStackProtectorMode(LangOptions::SSPReq); break;
864 }
Bill Wendling45483f72009-06-28 07:36:13 +0000865
Daniel Dunbarc9abc042009-04-08 05:11:16 +0000866 if (MainFileName.getPosition())
867 Options.setMainFileName(MainFileName.c_str());
Reid Spencer5f016e22007-07-11 17:01:13 +0000868}
869
870//===----------------------------------------------------------------------===//
Ted Kremenekae360762007-12-03 22:06:55 +0000871// Target Triple Processing.
872//===----------------------------------------------------------------------===//
873
874static llvm::cl::opt<std::string>
875TargetTriple("triple",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000876 llvm::cl::desc("Specify target triple (e.g. i686-apple-darwin9)"));
Ted Kremenekae360762007-12-03 22:06:55 +0000877
Chris Lattner42e67372008-03-05 01:18:20 +0000878static llvm::cl::opt<std::string>
Mike Stump1eb44332009-09-09 15:08:12 +0000879MacOSVersionMin("mmacosx-version-min",
Daniel Dunbar8d33cd72009-04-10 19:52:24 +0000880 llvm::cl::desc("Specify target Mac OS X version (e.g. 10.5)"));
Chris Lattner6a30c1f2008-09-30 01:13:12 +0000881
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000882// If -mmacosx-version-min=10.3.9 is specified, change the triple from being
883// something like powerpc-apple-darwin9 to powerpc-apple-darwin7
Daniel Dunbar64ffc142009-03-31 20:10:05 +0000884
885// FIXME: We should have the driver do this instead.
Chris Lattner2f60af72009-09-12 22:45:58 +0000886static void HandleMacOSVersionMin(llvm::Triple &Triple) {
887 if (Triple.getOS() != llvm::Triple::Darwin) {
Mike Stump1eb44332009-09-09 15:08:12 +0000888 fprintf(stderr,
Daniel Dunbar8d33cd72009-04-10 19:52:24 +0000889 "-mmacosx-version-min only valid for darwin (Mac OS X) targets\n");
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000890 exit(1);
891 }
Chris Lattner2f60af72009-09-12 22:45:58 +0000892
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000893 // Validate that MacOSVersionMin is a 'version number', starting with 10.[3-9]
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000894 if (MacOSVersionMin.size() < 4 ||
895 MacOSVersionMin.substr(0, 3) != "10." ||
896 !isdigit(MacOSVersionMin[3])) {
Mike Stump1eb44332009-09-09 15:08:12 +0000897 fprintf(stderr,
Daniel Dunbaraf07f932009-03-31 17:35:15 +0000898 "-mmacosx-version-min=%s is invalid, expected something like '10.4'.\n",
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000899 MacOSVersionMin.c_str());
900 exit(1);
901 }
Chris Lattner2f60af72009-09-12 22:45:58 +0000902
903 unsigned VersionNum = MacOSVersionMin[3]-'0';
904
905 if (VersionNum <= 4 && Triple.getArch() == llvm::Triple::x86_64) {
Mike Stump1eb44332009-09-09 15:08:12 +0000906 fprintf(stderr,
Chris Lattner2f60af72009-09-12 22:45:58 +0000907 "-mmacosx-version-min=%s is invalid with -arch x86_64.\n",
Fariborz Jahanian6a1284a2009-04-10 20:33:45 +0000908 MacOSVersionMin.c_str());
909 exit(1);
910 }
911
Chris Lattner2f60af72009-09-12 22:45:58 +0000912
913 llvm::SmallString<16> NewDarwinString;
914 NewDarwinString += "darwin";
915
916 // Turn MacOSVersionMin into a darwin number: e.g. 10.3.9 is 3 -> darwin7.
917 VersionNum += 4;
918 if (VersionNum > 9) {
919 NewDarwinString += '1';
920 VersionNum -= 10;
921 }
922 NewDarwinString += (VersionNum+'0');
923
924 if (MacOSVersionMin.size() == 4) {
925 // "10.4" is ok.
926 } else if (MacOSVersionMin.size() == 6 &&
927 MacOSVersionMin[4] == '.' &&
928 isdigit(MacOSVersionMin[5])) { // 10.4.7 is ok.
929 // Add the period piece (.7) to the end of the triple. This gives us
930 // something like ...-darwin8.7
931 NewDarwinString += '.';
932 NewDarwinString += MacOSVersionMin[5];
933 } else { // "10.4" is ok. 10.4x is not.
934 fprintf(stderr,
935 "-mmacosx-version-min=%s is invalid, expected something like '10.4'.\n",
936 MacOSVersionMin.c_str());
937 exit(1);
938 }
939
940 Triple.setOSName(NewDarwinString.str());
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000941}
942
Daniel Dunbar8d33cd72009-04-10 19:52:24 +0000943static llvm::cl::opt<std::string>
Mike Stump1eb44332009-09-09 15:08:12 +0000944IPhoneOSVersionMin("miphoneos-version-min",
Daniel Dunbar8d33cd72009-04-10 19:52:24 +0000945 llvm::cl::desc("Specify target iPhone OS version (e.g. 2.0)"));
946
947// If -miphoneos-version-min=2.2 is specified, change the triple from being
948// something like armv6-apple-darwin10 to armv6-apple-darwin9.2.2. We use
949// 9 as the default major Darwin number, and encode the iPhone OS version
950// number in the minor version and revision.
951
952// FIXME: We should have the driver do this instead.
Chris Lattner2f60af72009-09-12 22:45:58 +0000953static void HandleIPhoneOSVersionMin(llvm::Triple &Triple) {
954 if (Triple.getOS() != llvm::Triple::Darwin) {
Mike Stump1eb44332009-09-09 15:08:12 +0000955 fprintf(stderr,
Chris Lattner2f60af72009-09-12 22:45:58 +0000956 "-miphoneos-version-min only valid for darwin (Mac OS X) targets\n");
Daniel Dunbar8d33cd72009-04-10 19:52:24 +0000957 exit(1);
958 }
Mike Stump1eb44332009-09-09 15:08:12 +0000959
Chris Lattner2f60af72009-09-12 22:45:58 +0000960 // Validate that IPhoneOSVersionMin is a 'version number', starting with
961 // [2-9].[0-9]
962 if (IPhoneOSVersionMin.size() != 3 || !isdigit(IPhoneOSVersionMin[0]) ||
963 IPhoneOSVersionMin[1] != '.' || !isdigit(IPhoneOSVersionMin[2])) {
Mike Stump1eb44332009-09-09 15:08:12 +0000964 fprintf(stderr,
Chris Lattner2f60af72009-09-12 22:45:58 +0000965 "-miphoneos-version-min=%s is invalid, expected something like '2.0'.\n",
Daniel Dunbar8d33cd72009-04-10 19:52:24 +0000966 IPhoneOSVersionMin.c_str());
967 exit(1);
968 }
Chris Lattner2f60af72009-09-12 22:45:58 +0000969
970 // Turn IPhoneOSVersionMin into a darwin number: e.g. 2.0 is 2 -> 9.2.0
971 llvm::SmallString<16> NewDarwinString;
972 NewDarwinString += "darwin9.";
973 NewDarwinString += IPhoneOSVersionMin;
974 Triple.setOSName(NewDarwinString.str());
Daniel Dunbar8d33cd72009-04-10 19:52:24 +0000975}
976
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000977/// CreateTargetTriple - Process the various options that affect the target
978/// triple and build a final aggregate triple that we are compiling for.
Chris Lattner2f60af72009-09-12 22:45:58 +0000979static llvm::Triple CreateTargetTriple() {
Ted Kremenekae360762007-12-03 22:06:55 +0000980 // Initialize base triple. If a -triple option has been specified, use
981 // that triple. Otherwise, default to the host triple.
Chris Lattner2f60af72009-09-12 22:45:58 +0000982 llvm::Triple Triple(TargetTriple);
983 if (Triple.getTriple().empty())
984 Triple = llvm::Triple(llvm::sys::getHostTriple());
Chris Lattner6a30c1f2008-09-30 01:13:12 +0000985
986 // If -mmacosx-version-min=10.3.9 is specified, change the triple from being
987 // something like powerpc-apple-darwin9 to powerpc-apple-darwin7
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000988 if (!MacOSVersionMin.empty())
989 HandleMacOSVersionMin(Triple);
Daniel Dunbar8d33cd72009-04-10 19:52:24 +0000990 else if (!IPhoneOSVersionMin.empty())
Chris Lattner2f60af72009-09-12 22:45:58 +0000991 HandleIPhoneOSVersionMin(Triple);
Mike Stump1eb44332009-09-09 15:08:12 +0000992
Chris Lattner6a30c1f2008-09-30 01:13:12 +0000993 return Triple;
Ted Kremenekae360762007-12-03 22:06:55 +0000994}
995
996//===----------------------------------------------------------------------===//
Chris Lattnere116ccf2009-04-21 05:40:52 +0000997// SourceManager initialization.
Reid Spencer5f016e22007-07-11 17:01:13 +0000998//===----------------------------------------------------------------------===//
999
Douglas Gregore1d918e2009-04-10 23:10:45 +00001000static bool InitializeSourceManager(Preprocessor &PP,
1001 const std::string &InFile) {
1002 // Figure out where to get and map in the main file.
1003 SourceManager &SourceMgr = PP.getSourceManager();
1004 FileManager &FileMgr = PP.getFileManager();
Daniel Dunbar57cbfc02009-04-27 21:19:07 +00001005
1006 if (EmptyInputOnly) {
1007 const char *EmptyStr = "";
Mike Stump1eb44332009-09-09 15:08:12 +00001008 llvm::MemoryBuffer *SB =
Daniel Dunbar57cbfc02009-04-27 21:19:07 +00001009 llvm::MemoryBuffer::getMemBuffer(EmptyStr, EmptyStr, "<empty input>");
1010 SourceMgr.createMainFileIDForMemBuffer(SB);
1011 } else if (InFile != "-") {
Douglas Gregore1d918e2009-04-10 23:10:45 +00001012 const FileEntry *File = FileMgr.getFile(InFile);
1013 if (File) SourceMgr.createMainFileID(File, SourceLocation());
1014 if (SourceMgr.getMainFileID().isInvalid()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001015 PP.getDiagnostics().Report(FullSourceLoc(), diag::err_fe_error_reading)
Douglas Gregore1d918e2009-04-10 23:10:45 +00001016 << InFile.c_str();
1017 return true;
1018 }
1019 } else {
1020 llvm::MemoryBuffer *SB = llvm::MemoryBuffer::getSTDIN();
1021
1022 // If stdin was empty, SB is null. Cons up an empty memory
1023 // buffer now.
1024 if (!SB) {
1025 const char *EmptyStr = "";
1026 SB = llvm::MemoryBuffer::getMemBuffer(EmptyStr, EmptyStr, "<stdin>");
1027 }
1028
1029 SourceMgr.createMainFileIDForMemBuffer(SB);
1030 if (SourceMgr.getMainFileID().isInvalid()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001031 PP.getDiagnostics().Report(FullSourceLoc(),
Douglas Gregore1d918e2009-04-10 23:10:45 +00001032 diag::err_fe_error_reading_stdin);
1033 return true;
1034 }
1035 }
1036
1037 return false;
1038}
1039
Chris Lattneraa391972008-04-19 23:09:31 +00001040
Chris Lattnere116ccf2009-04-21 05:40:52 +00001041//===----------------------------------------------------------------------===//
1042// Preprocessor Initialization
1043//===----------------------------------------------------------------------===//
Sam Bishop1102d6b2008-04-14 14:41:57 +00001044
Chris Lattnere116ccf2009-04-21 05:40:52 +00001045// FIXME: Preprocessor builtins to support.
1046// -A... - Play with #assertions
1047// -undef - Undefine all predefined macros
Chris Lattnerb31ac222009-04-08 20:15:42 +00001048
Chris Lattnere116ccf2009-04-21 05:40:52 +00001049static llvm::cl::list<std::string>
1050D_macros("D", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
1051 llvm::cl::desc("Predefine the specified macro"));
1052static llvm::cl::list<std::string>
1053U_macros("U", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
1054 llvm::cl::desc("Undefine the specified macro"));
Chris Lattnerb8e240e2009-04-08 18:24:34 +00001055
Chris Lattnere116ccf2009-04-21 05:40:52 +00001056static llvm::cl::list<std::string>
1057ImplicitIncludes("include", llvm::cl::value_desc("file"),
1058 llvm::cl::desc("Include file before parsing"));
1059static llvm::cl::list<std::string>
1060ImplicitMacroIncludes("imacros", llvm::cl::value_desc("file"),
1061 llvm::cl::desc("Include macros from file before parsing"));
Chris Lattnerb8e240e2009-04-08 18:24:34 +00001062
Chris Lattnere116ccf2009-04-21 05:40:52 +00001063static llvm::cl::opt<std::string>
1064ImplicitIncludePCH("include-pch", llvm::cl::value_desc("file"),
1065 llvm::cl::desc("Include precompiled header file"));
1066
1067static llvm::cl::opt<std::string>
1068ImplicitIncludePTH("include-pth", llvm::cl::value_desc("file"),
1069 llvm::cl::desc("Include file before parsing"));
1070
Douglas Gregore650c8c2009-07-07 00:12:59 +00001071static llvm::cl::opt<bool>
Mike Stump1eb44332009-09-09 15:08:12 +00001072RelocatablePCH("relocatable-pch",
Douglas Gregore650c8c2009-07-07 00:12:59 +00001073 llvm::cl::desc("Whether to build a relocatable precompiled "
1074 "header"));
Reid Spencer5f016e22007-07-11 17:01:13 +00001075
1076//===----------------------------------------------------------------------===//
1077// Preprocessor include path information.
1078//===----------------------------------------------------------------------===//
1079
1080// This tool exports a large number of command line options to control how the
1081// preprocessor searches for header files. At root, however, the Preprocessor
1082// object takes a very simple interface: a list of directories to search for
Mike Stump1eb44332009-09-09 15:08:12 +00001083//
Daniel Dunbarfb4ac7b2009-05-06 03:48:17 +00001084// FIXME: -nostdinc++
Chris Lattner0c946412007-08-26 17:47:35 +00001085// FIXME: -imultilib
Reid Spencer5f016e22007-07-11 17:01:13 +00001086//
Reid Spencer5f016e22007-07-11 17:01:13 +00001087
1088static llvm::cl::opt<bool>
1089nostdinc("nostdinc", llvm::cl::desc("Disable standard #include directories"));
1090
1091// Various command line options. These four add directories to each chain.
1092static llvm::cl::list<std::string>
1093F_dirs("F", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1094 llvm::cl::desc("Add directory to framework include search path"));
1095static llvm::cl::list<std::string>
1096I_dirs("I", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1097 llvm::cl::desc("Add directory to include search path"));
1098static llvm::cl::list<std::string>
1099idirafter_dirs("idirafter", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1100 llvm::cl::desc("Add directory to AFTER include search path"));
1101static llvm::cl::list<std::string>
1102iquote_dirs("iquote", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1103 llvm::cl::desc("Add directory to QUOTE include search path"));
1104static llvm::cl::list<std::string>
1105isystem_dirs("isystem", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1106 llvm::cl::desc("Add directory to SYSTEM include search path"));
1107
1108// These handle -iprefix/-iwithprefix/-iwithprefixbefore.
1109static llvm::cl::list<std::string>
1110iprefix_vals("iprefix", llvm::cl::value_desc("prefix"), llvm::cl::Prefix,
1111 llvm::cl::desc("Set the -iwithprefix/-iwithprefixbefore prefix"));
1112static llvm::cl::list<std::string>
1113iwithprefix_vals("iwithprefix", llvm::cl::value_desc("dir"), llvm::cl::Prefix,
1114 llvm::cl::desc("Set directory to SYSTEM include search path with prefix"));
1115static llvm::cl::list<std::string>
1116iwithprefixbefore_vals("iwithprefixbefore", llvm::cl::value_desc("dir"),
1117 llvm::cl::Prefix,
1118 llvm::cl::desc("Set directory to include search path with prefix"));
1119
Chris Lattner0c946412007-08-26 17:47:35 +00001120static llvm::cl::opt<std::string>
1121isysroot("isysroot", llvm::cl::value_desc("dir"), llvm::cl::init("/"),
1122 llvm::cl::desc("Set the system root directory (usually /)"));
1123
Reid Spencer5f016e22007-07-11 17:01:13 +00001124// Finally, implement the code that groks the options above.
Chris Lattner5f9eae52008-03-01 08:07:28 +00001125
Reid Spencer5f016e22007-07-11 17:01:13 +00001126/// InitializeIncludePaths - Process the -I options and set them in the
1127/// HeaderSearch object.
Nico Weber0fca0222008-08-22 09:25:22 +00001128void InitializeIncludePaths(const char *Argv0, HeaderSearch &Headers,
1129 FileManager &FM, const LangOptions &Lang) {
1130 InitHeaderSearch Init(Headers, Verbose, isysroot);
1131
Ted Kremenekf3721112008-05-31 00:27:00 +00001132 // Handle -I... and -F... options, walking the lists in parallel.
1133 unsigned Iidx = 0, Fidx = 0;
1134 while (Iidx < I_dirs.size() && Fidx < F_dirs.size()) {
1135 if (I_dirs.getPosition(Iidx) < F_dirs.getPosition(Fidx)) {
Nico Weber0fca0222008-08-22 09:25:22 +00001136 Init.AddPath(I_dirs[Iidx], InitHeaderSearch::Angled, false, true, false);
Ted Kremenekf3721112008-05-31 00:27:00 +00001137 ++Iidx;
1138 } else {
Nico Weber0fca0222008-08-22 09:25:22 +00001139 Init.AddPath(F_dirs[Fidx], InitHeaderSearch::Angled, false, true, true);
Ted Kremenekf3721112008-05-31 00:27:00 +00001140 ++Fidx;
1141 }
1142 }
Mike Stump1eb44332009-09-09 15:08:12 +00001143
Ted Kremenekf3721112008-05-31 00:27:00 +00001144 // Consume what's left from whatever list was longer.
1145 for (; Iidx != I_dirs.size(); ++Iidx)
Nico Weber0fca0222008-08-22 09:25:22 +00001146 Init.AddPath(I_dirs[Iidx], InitHeaderSearch::Angled, false, true, false);
Ted Kremenekf3721112008-05-31 00:27:00 +00001147 for (; Fidx != F_dirs.size(); ++Fidx)
Nico Weber0fca0222008-08-22 09:25:22 +00001148 Init.AddPath(F_dirs[Fidx], InitHeaderSearch::Angled, false, true, true);
Mike Stump1eb44332009-09-09 15:08:12 +00001149
Reid Spencer5f016e22007-07-11 17:01:13 +00001150 // Handle -idirafter... options.
1151 for (unsigned i = 0, e = idirafter_dirs.size(); i != e; ++i)
Nico Weber0fca0222008-08-22 09:25:22 +00001152 Init.AddPath(idirafter_dirs[i], InitHeaderSearch::After,
1153 false, true, false);
Mike Stump1eb44332009-09-09 15:08:12 +00001154
Reid Spencer5f016e22007-07-11 17:01:13 +00001155 // Handle -iquote... options.
1156 for (unsigned i = 0, e = iquote_dirs.size(); i != e; ++i)
Nico Weber0fca0222008-08-22 09:25:22 +00001157 Init.AddPath(iquote_dirs[i], InitHeaderSearch::Quoted, false, true, false);
Mike Stump1eb44332009-09-09 15:08:12 +00001158
Reid Spencer5f016e22007-07-11 17:01:13 +00001159 // Handle -isystem... options.
1160 for (unsigned i = 0, e = isystem_dirs.size(); i != e; ++i)
Nico Weber0fca0222008-08-22 09:25:22 +00001161 Init.AddPath(isystem_dirs[i], InitHeaderSearch::System, false, true, false);
Reid Spencer5f016e22007-07-11 17:01:13 +00001162
1163 // Walk the -iprefix/-iwithprefix/-iwithprefixbefore argument lists in
1164 // parallel, processing the values in order of occurance to get the right
1165 // prefixes.
1166 {
1167 std::string Prefix = ""; // FIXME: this isn't the correct default prefix.
1168 unsigned iprefix_idx = 0;
1169 unsigned iwithprefix_idx = 0;
1170 unsigned iwithprefixbefore_idx = 0;
1171 bool iprefix_done = iprefix_vals.empty();
1172 bool iwithprefix_done = iwithprefix_vals.empty();
1173 bool iwithprefixbefore_done = iwithprefixbefore_vals.empty();
1174 while (!iprefix_done || !iwithprefix_done || !iwithprefixbefore_done) {
1175 if (!iprefix_done &&
Mike Stump1eb44332009-09-09 15:08:12 +00001176 (iwithprefix_done ||
1177 iprefix_vals.getPosition(iprefix_idx) <
Reid Spencer5f016e22007-07-11 17:01:13 +00001178 iwithprefix_vals.getPosition(iwithprefix_idx)) &&
Mike Stump1eb44332009-09-09 15:08:12 +00001179 (iwithprefixbefore_done ||
1180 iprefix_vals.getPosition(iprefix_idx) <
Reid Spencer5f016e22007-07-11 17:01:13 +00001181 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
1182 Prefix = iprefix_vals[iprefix_idx];
1183 ++iprefix_idx;
1184 iprefix_done = iprefix_idx == iprefix_vals.size();
1185 } else if (!iwithprefix_done &&
Mike Stump1eb44332009-09-09 15:08:12 +00001186 (iwithprefixbefore_done ||
1187 iwithprefix_vals.getPosition(iwithprefix_idx) <
Reid Spencer5f016e22007-07-11 17:01:13 +00001188 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
Mike Stump1eb44332009-09-09 15:08:12 +00001189 Init.AddPath(Prefix+iwithprefix_vals[iwithprefix_idx],
Nico Weber0fca0222008-08-22 09:25:22 +00001190 InitHeaderSearch::System, false, false, false);
Reid Spencer5f016e22007-07-11 17:01:13 +00001191 ++iwithprefix_idx;
1192 iwithprefix_done = iwithprefix_idx == iwithprefix_vals.size();
1193 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00001194 Init.AddPath(Prefix+iwithprefixbefore_vals[iwithprefixbefore_idx],
Nico Weber0fca0222008-08-22 09:25:22 +00001195 InitHeaderSearch::Angled, false, false, false);
Reid Spencer5f016e22007-07-11 17:01:13 +00001196 ++iwithprefixbefore_idx;
Mike Stump1eb44332009-09-09 15:08:12 +00001197 iwithprefixbefore_done =
Reid Spencer5f016e22007-07-11 17:01:13 +00001198 iwithprefixbefore_idx == iwithprefixbefore_vals.size();
1199 }
1200 }
1201 }
Chris Lattner5f9eae52008-03-01 08:07:28 +00001202
Nico Weber0fca0222008-08-22 09:25:22 +00001203 Init.AddDefaultEnvVarPaths(Lang);
Chris Lattner5f9eae52008-03-01 08:07:28 +00001204
Daniel Dunbaradcf5b32009-02-21 20:52:41 +00001205 // Add the clang headers, which are relative to the clang binary.
Mike Stump1eb44332009-09-09 15:08:12 +00001206 llvm::sys::Path MainExecutablePath =
Chris Lattner985e1822008-03-03 05:57:43 +00001207 llvm::sys::Path::GetMainExecutable(Argv0,
1208 (void*)(intptr_t)InitializeIncludePaths);
Chris Lattnerdcaa0962008-03-03 03:16:03 +00001209 if (!MainExecutablePath.isEmpty()) {
1210 MainExecutablePath.eraseComponent(); // Remove /clang from foo/bin/clang
1211 MainExecutablePath.eraseComponent(); // Remove /bin from foo/bin
Daniel Dunbaradcf5b32009-02-21 20:52:41 +00001212
Mike Stump1eb44332009-09-09 15:08:12 +00001213 // Get foo/lib/clang/<version>/include
Daniel Dunbaradcf5b32009-02-21 20:52:41 +00001214 MainExecutablePath.appendComponent("lib");
1215 MainExecutablePath.appendComponent("clang");
Daniel Dunbarfb4ac7b2009-05-06 03:48:17 +00001216 MainExecutablePath.appendComponent(CLANG_VERSION_STRING);
Daniel Dunbaradcf5b32009-02-21 20:52:41 +00001217 MainExecutablePath.appendComponent("include");
Mike Stump1eb44332009-09-09 15:08:12 +00001218
Chris Lattner6858dd32009-02-19 06:48:28 +00001219 // We pass true to ignore sysroot so that we *always* look for clang headers
1220 // relative to our executable, never relative to -isysroot.
1221 Init.AddPath(MainExecutablePath.c_str(), InitHeaderSearch::System,
1222 false, false, false, true /*ignore sysroot*/);
Chris Lattnerdcaa0962008-03-03 03:16:03 +00001223 }
Mike Stump1eb44332009-09-09 15:08:12 +00001224
1225 if (!nostdinc)
Nico Weber0fca0222008-08-22 09:25:22 +00001226 Init.AddDefaultSystemIncludePaths(Lang);
Reid Spencer5f016e22007-07-11 17:01:13 +00001227
1228 // Now that we have collected all of the include paths, merge them all
1229 // together and tell the preprocessor about them.
Mike Stump1eb44332009-09-09 15:08:12 +00001230
Nico Weber0fca0222008-08-22 09:25:22 +00001231 Init.Realize();
Reid Spencer5f016e22007-07-11 17:01:13 +00001232}
1233
Mike Stump1eb44332009-09-09 15:08:12 +00001234void InitializePreprocessorInitOptions(PreprocessorInitOptions &InitOpts) {
Chris Lattnere116ccf2009-04-21 05:40:52 +00001235 // Add macros from the command line.
1236 unsigned d = 0, D = D_macros.size();
1237 unsigned u = 0, U = U_macros.size();
1238 while (d < D || u < U) {
1239 if (u == U || (d < D && D_macros.getPosition(d) < U_macros.getPosition(u)))
1240 InitOpts.addMacroDef(D_macros[d++]);
1241 else
1242 InitOpts.addMacroUndef(U_macros[u++]);
1243 }
1244
1245 // If -imacros are specified, include them now. These are processed before
1246 // any -include directives.
1247 for (unsigned i = 0, e = ImplicitMacroIncludes.size(); i != e; ++i)
1248 InitOpts.addMacroInclude(ImplicitMacroIncludes[i]);
1249
Douglas Gregorb64c1932009-05-12 01:31:05 +00001250 if (!ImplicitIncludePTH.empty() || !ImplicitIncludes.empty() ||
1251 (!ImplicitIncludePCH.empty() && ProgAction == PrintPreprocessedInput)) {
Chris Lattnere116ccf2009-04-21 05:40:52 +00001252 // We want to add these paths to the predefines buffer in order, make a
1253 // temporary vector to sort by their occurrence.
1254 llvm::SmallVector<std::pair<unsigned, std::string*>, 8> OrderedPaths;
1255
1256 if (!ImplicitIncludePTH.empty())
1257 OrderedPaths.push_back(std::make_pair(ImplicitIncludePTH.getPosition(),
1258 &ImplicitIncludePTH));
Douglas Gregorb64c1932009-05-12 01:31:05 +00001259 if (!ImplicitIncludePCH.empty() && ProgAction == PrintPreprocessedInput)
1260 OrderedPaths.push_back(std::make_pair(ImplicitIncludePCH.getPosition(),
1261 &ImplicitIncludePCH));
Chris Lattnere116ccf2009-04-21 05:40:52 +00001262 for (unsigned i = 0, e = ImplicitIncludes.size(); i != e; ++i)
1263 OrderedPaths.push_back(std::make_pair(ImplicitIncludes.getPosition(i),
1264 &ImplicitIncludes[i]));
1265 llvm::array_pod_sort(OrderedPaths.begin(), OrderedPaths.end());
1266
1267
1268 // Now that they are ordered by position, add to the predefines buffer.
1269 for (unsigned i = 0, e = OrderedPaths.size(); i != e; ++i) {
1270 std::string *Ptr = OrderedPaths[i].second;
1271 if (!ImplicitIncludes.empty() &&
1272 Ptr >= &ImplicitIncludes[0] &&
1273 Ptr <= &ImplicitIncludes[ImplicitIncludes.size()-1]) {
1274 InitOpts.addInclude(*Ptr, false);
Douglas Gregorb64c1932009-05-12 01:31:05 +00001275 } else if (Ptr == &ImplicitIncludePTH) {
Chris Lattnere116ccf2009-04-21 05:40:52 +00001276 InitOpts.addInclude(*Ptr, true);
Douglas Gregorb64c1932009-05-12 01:31:05 +00001277 } else {
1278 // We end up here when we're producing preprocessed output and
1279 // we loaded a PCH file. In this case, just include the header
1280 // file that was used to build the precompiled header.
1281 assert(Ptr == &ImplicitIncludePCH);
1282 std::string OriginalFile = PCHReader::getOriginalSourceFile(*Ptr);
1283 if (!OriginalFile.empty()) {
1284 InitOpts.addInclude(OriginalFile, false);
1285 ImplicitIncludePCH.clear();
1286 }
Chris Lattnere116ccf2009-04-21 05:40:52 +00001287 }
1288 }
1289 }
1290}
1291
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001292//===----------------------------------------------------------------------===//
1293// Driver PreprocessorFactory - For lazily generating preprocessors ...
1294//===----------------------------------------------------------------------===//
1295
1296namespace {
1297class VISIBILITY_HIDDEN DriverPreprocessorFactory : public PreprocessorFactory {
1298 Diagnostic &Diags;
1299 const LangOptions &LangInfo;
1300 TargetInfo &Target;
1301 SourceManager &SourceMgr;
1302 HeaderSearch &HeaderInfo;
Mike Stump1eb44332009-09-09 15:08:12 +00001303
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001304public:
Eli Friedmanf086e3b2009-05-18 07:39:39 +00001305 DriverPreprocessorFactory(Diagnostic &diags, const LangOptions &opts,
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001306 TargetInfo &target, SourceManager &SM,
Mike Stump1eb44332009-09-09 15:08:12 +00001307 HeaderSearch &Headers)
Eli Friedmanf086e3b2009-05-18 07:39:39 +00001308 : Diags(diags), LangInfo(opts), Target(target),
Douglas Gregore1d918e2009-04-10 23:10:45 +00001309 SourceMgr(SM), HeaderInfo(Headers) {}
Mike Stump1eb44332009-09-09 15:08:12 +00001310
1311
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001312 virtual ~DriverPreprocessorFactory() {}
Mike Stump1eb44332009-09-09 15:08:12 +00001313
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001314 virtual Preprocessor* CreatePreprocessor() {
Ted Kremenek72b1b152009-01-15 18:47:46 +00001315 llvm::OwningPtr<PTHManager> PTHMgr;
1316
Ted Kremenek748d5d62009-03-20 00:26:38 +00001317 if (!TokenCache.empty() && !ImplicitIncludePTH.empty()) {
1318 fprintf(stderr, "error: cannot use both -token-cache and -include-pth "
1319 "options\n");
Ted Kremenek22f0d092009-03-22 06:42:39 +00001320 exit(1);
Ted Kremenek748d5d62009-03-20 00:26:38 +00001321 }
Mike Stump1eb44332009-09-09 15:08:12 +00001322
Ted Kremenek72b1b152009-01-15 18:47:46 +00001323 // Use PTH?
Ted Kremenek748d5d62009-03-20 00:26:38 +00001324 if (!TokenCache.empty() || !ImplicitIncludePTH.empty()) {
1325 const std::string& x = TokenCache.empty() ? ImplicitIncludePTH:TokenCache;
Mike Stump1eb44332009-09-09 15:08:12 +00001326 PTHMgr.reset(PTHManager::Create(x, &Diags,
Ted Kremenek22f0d092009-03-22 06:42:39 +00001327 TokenCache.empty() ? Diagnostic::Error
1328 : Diagnostic::Warning));
Ted Kremenek748d5d62009-03-20 00:26:38 +00001329 }
Mike Stump1eb44332009-09-09 15:08:12 +00001330
Ted Kremenek22f0d092009-03-22 06:42:39 +00001331 if (Diags.hasErrorOccurred())
1332 exit(1);
Mike Stump1eb44332009-09-09 15:08:12 +00001333
Ted Kremenek72b1b152009-01-15 18:47:46 +00001334 // Create the Preprocessor.
1335 llvm::OwningPtr<Preprocessor> PP(new Preprocessor(Diags, LangInfo, Target,
1336 SourceMgr, HeaderInfo,
1337 PTHMgr.get()));
Mike Stump1eb44332009-09-09 15:08:12 +00001338
Ted Kremenek72b1b152009-01-15 18:47:46 +00001339 // Note that this is different then passing PTHMgr to Preprocessor's ctor.
1340 // That argument is used as the IdentifierInfoLookup argument to
1341 // IdentifierTable's ctor.
1342 if (PTHMgr) {
1343 PTHMgr->setPreprocessor(PP.get());
1344 PP->setPTHManager(PTHMgr.take());
1345 }
Douglas Gregor14f79002009-04-10 03:52:48 +00001346
Chris Lattnere116ccf2009-04-21 05:40:52 +00001347 PreprocessorInitOptions InitOpts;
1348 InitializePreprocessorInitOptions(InitOpts);
Eli Friedmanf086e3b2009-05-18 07:39:39 +00001349 if (InitializePreprocessor(*PP, InitOpts))
Douglas Gregore1d918e2009-04-10 23:10:45 +00001350 return 0;
Chris Lattnere116ccf2009-04-21 05:40:52 +00001351
Douglas Gregore1d918e2009-04-10 23:10:45 +00001352 return PP.take();
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001353 }
1354};
1355}
Reid Spencer5f016e22007-07-11 17:01:13 +00001356
Reid Spencer5f016e22007-07-11 17:01:13 +00001357//===----------------------------------------------------------------------===//
1358// Basic Parser driver
1359//===----------------------------------------------------------------------===//
1360
Chris Lattner51574ea2008-04-19 23:25:44 +00001361static void ParseFile(Preprocessor &PP, MinimalAction *PA) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001362 Parser P(PP, *PA);
Ted Kremenek95041a22007-12-19 22:51:13 +00001363 PP.EnterMainSourceFile();
Mike Stump1eb44332009-09-09 15:08:12 +00001364
Reid Spencer5f016e22007-07-11 17:01:13 +00001365 // Parsing the specified input file.
1366 P.ParseTranslationUnit();
1367 delete PA;
1368}
1369
1370//===----------------------------------------------------------------------===//
Daniel Dunbar70f92432008-10-23 05:50:47 +00001371// Code generation options
1372//===----------------------------------------------------------------------===//
1373
1374static llvm::cl::opt<bool>
Chris Lattner15104882009-03-09 22:05:03 +00001375GenerateDebugInfo("g",
1376 llvm::cl::desc("Generate source level debug information"));
1377
Daniel Dunbara034ba82009-02-17 19:47:34 +00001378static llvm::cl::opt<std::string>
1379TargetCPU("mcpu",
1380 llvm::cl::desc("Target a specific cpu type (-mcpu=help for details)"));
1381
Daniel Dunbar868bd0a2009-05-06 03:16:41 +00001382static llvm::cl::list<std::string>
1383TargetFeatures("target-feature", llvm::cl::desc("Target specific attributes"));
1384
Devang Patel24095da2009-06-04 23:32:02 +00001385
1386static llvm::cl::opt<bool>
1387DisableRedZone("disable-red-zone",
1388 llvm::cl::desc("Do not emit code that uses the red zone."),
1389 llvm::cl::init(false));
1390
Devang Patelacebb392009-06-05 22:05:48 +00001391static llvm::cl::opt<bool>
1392NoImplicitFloat("no-implicit-float",
1393 llvm::cl::desc("Don't generate implicit floating point instructions (x86-only)"),
1394 llvm::cl::init(false));
1395
Daniel Dunbar868bd0a2009-05-06 03:16:41 +00001396/// ComputeTargetFeatures - Recompute the target feature list to only
1397/// be the list of things that are enabled, based on the target cpu
1398/// and feature list.
1399static void ComputeFeatureMap(TargetInfo *Target,
1400 llvm::StringMap<bool> &Features) {
Mike Stump1eb44332009-09-09 15:08:12 +00001401 assert(Features.empty() && "invalid map");
Daniel Dunbar868bd0a2009-05-06 03:16:41 +00001402
1403 // Initialize the feature map based on the target.
1404 Target->getDefaultFeatures(TargetCPU, Features);
1405
1406 // Apply the user specified deltas.
Mike Stump1eb44332009-09-09 15:08:12 +00001407 for (llvm::cl::list<std::string>::iterator it = TargetFeatures.begin(),
Daniel Dunbar868bd0a2009-05-06 03:16:41 +00001408 ie = TargetFeatures.end(); it != ie; ++it) {
1409 const char *Name = it->c_str();
Mike Stump1eb44332009-09-09 15:08:12 +00001410
Daniel Dunbar868bd0a2009-05-06 03:16:41 +00001411 // FIXME: Don't handle errors like this.
1412 if (Name[0] != '-' && Name[0] != '+') {
Mike Stump1eb44332009-09-09 15:08:12 +00001413 fprintf(stderr, "error: clang-cc: invalid target feature string: %s\n",
Daniel Dunbar868bd0a2009-05-06 03:16:41 +00001414 Name);
1415 exit(1);
1416 }
Daniel Dunbar17ca3632009-05-06 21:07:50 +00001417 if (!Target->setFeatureEnabled(Features, Name + 1, (Name[0] == '+'))) {
Mike Stump1eb44332009-09-09 15:08:12 +00001418 fprintf(stderr, "error: clang-cc: invalid target feature name: %s\n",
Daniel Dunbar17ca3632009-05-06 21:07:50 +00001419 Name + 1);
Daniel Dunbar868bd0a2009-05-06 03:16:41 +00001420 exit(1);
1421 }
Daniel Dunbar868bd0a2009-05-06 03:16:41 +00001422 }
1423}
1424
Chris Lattner7afae712009-03-16 18:41:18 +00001425static void InitializeCompileOptions(CompileOptions &Opts,
Daniel Dunbar868bd0a2009-05-06 03:16:41 +00001426 const LangOptions &LangOpts,
1427 const llvm::StringMap<bool> &Features) {
Daniel Dunbar70f92432008-10-23 05:50:47 +00001428 Opts.OptimizeSize = OptSize;
Chris Lattner20126042009-03-09 22:00:34 +00001429 Opts.DebugInfo = GenerateDebugInfo;
Daniel Dunbar877db382009-06-02 22:07:45 +00001430
1431 if (DisableLLVMOptimizations) {
1432 Opts.OptimizationLevel = 0;
1433 Opts.Inlining = CompileOptions::NoInlining;
Daniel Dunbarac7ffe02008-10-29 07:56:11 +00001434 } else {
Daniel Dunbar877db382009-06-02 22:07:45 +00001435 if (OptSize) {
1436 // -Os implies -O2
1437 Opts.OptimizationLevel = 2;
1438 } else {
1439 Opts.OptimizationLevel = OptLevel;
1440 }
1441
1442 // We must always run at least the always inlining pass.
1443 if (Opts.OptimizationLevel > 1)
1444 Opts.Inlining = CompileOptions::NormalInlining;
1445 else
1446 Opts.Inlining = CompileOptions::OnlyAlwaysInlining;
Daniel Dunbarac7ffe02008-10-29 07:56:11 +00001447 }
Daniel Dunbar8e8f3b72008-10-29 03:42:18 +00001448
1449 // FIXME: There are llvm-gcc options to control these selectively.
Daniel Dunbar8e8f3b72008-10-29 03:42:18 +00001450 Opts.UnrollLoops = (Opts.OptimizationLevel > 1 && !OptSize);
Chris Lattner7afae712009-03-16 18:41:18 +00001451 Opts.SimplifyLibCalls = !LangOpts.NoBuiltin;
Daniel Dunbardd913e52008-10-31 09:34:21 +00001452
1453#ifdef NDEBUG
1454 Opts.VerifyModule = 0;
1455#endif
Daniel Dunbara034ba82009-02-17 19:47:34 +00001456
1457 Opts.CPU = TargetCPU;
Daniel Dunbar868bd0a2009-05-06 03:16:41 +00001458 Opts.Features.clear();
Mike Stump1eb44332009-09-09 15:08:12 +00001459 for (llvm::StringMap<bool>::const_iterator it = Features.begin(),
Daniel Dunbar868bd0a2009-05-06 03:16:41 +00001460 ie = Features.end(); it != ie; ++it) {
1461 // FIXME: If we are completely confident that we have the right
1462 // set, we only need to pass the minuses.
1463 std::string Name(it->second ? "+" : "-");
1464 Name += it->first();
1465 Opts.Features.push_back(Name);
1466 }
Mike Stump1eb44332009-09-09 15:08:12 +00001467
Chris Lattnerbd360642009-03-26 05:00:52 +00001468 Opts.NoCommon = NoCommon | LangOpts.CPlusPlus;
Mike Stump1eb44332009-09-09 15:08:12 +00001469
Chris Lattner44502662009-02-18 01:23:44 +00001470 // Handle -ftime-report.
1471 Opts.TimePasses = TimeReport;
Devang Patel24095da2009-06-04 23:32:02 +00001472
1473 Opts.DisableRedZone = DisableRedZone;
Devang Patelacebb392009-06-05 22:05:48 +00001474 Opts.NoImplicitFloat = NoImplicitFloat;
Daniel Dunbar70f92432008-10-23 05:50:47 +00001475}
1476
1477//===----------------------------------------------------------------------===//
Douglas Gregor26df2f02009-04-02 19:05:20 +00001478// Fix-It Options
1479//===----------------------------------------------------------------------===//
1480static llvm::cl::list<ParsedSourceLocation>
1481FixItAtLocations("fixit-at", llvm::cl::value_desc("source-location"),
1482 llvm::cl::desc("Perform Fix-It modifications at the given source location"));
1483
1484//===----------------------------------------------------------------------===//
Eli Friedmanc6d656e2009-05-18 22:39:16 +00001485// ObjC Rewriter Options
1486//===----------------------------------------------------------------------===//
1487static llvm::cl::opt<bool>
1488SilenceRewriteMacroWarning("Wno-rewrite-macros", llvm::cl::init(false),
1489 llvm::cl::desc("Silence ObjC rewriting warnings"));
1490
1491//===----------------------------------------------------------------------===//
Eli Friedman0eeb86e2009-05-19 01:17:04 +00001492// Warning Options
1493//===----------------------------------------------------------------------===//
1494
1495// This gets all -W options, including -Werror, -W[no-]system-headers, etc. The
1496// driver has stripped off -Wa,foo etc. The driver has also translated -W to
1497// -Wextra, so we don't need to worry about it.
1498static llvm::cl::list<std::string>
1499OptWarnings("W", llvm::cl::Prefix, llvm::cl::ValueOptional);
1500
1501static llvm::cl::opt<bool> OptPedantic("pedantic");
1502static llvm::cl::opt<bool> OptPedanticErrors("pedantic-errors");
1503static llvm::cl::opt<bool> OptNoWarnings("w");
1504
1505//===----------------------------------------------------------------------===//
Eli Friedman12d3b1d2009-05-19 03:06:47 +00001506// Preprocessing (-E mode) Options
1507//===----------------------------------------------------------------------===//
1508static llvm::cl::opt<bool>
1509DisableLineMarkers("P", llvm::cl::desc("Disable linemarker output in -E mode"));
1510static llvm::cl::opt<bool>
1511EnableCommentOutput("C", llvm::cl::desc("Enable comment output in -E mode"));
1512static llvm::cl::opt<bool>
1513EnableMacroCommentOutput("CC",
1514 llvm::cl::desc("Enable comment output in -E mode, "
1515 "even from macro expansions"));
1516static llvm::cl::opt<bool>
1517DumpMacros("dM", llvm::cl::desc("Print macro definitions in -E mode instead of"
1518 " normal output"));
1519static llvm::cl::opt<bool>
1520DumpDefines("dD", llvm::cl::desc("Print macro definitions in -E mode in "
1521 "addition to normal output"));
Eli Friedmanb5c8f8b2009-05-19 03:35:57 +00001522
1523//===----------------------------------------------------------------------===//
1524// Dependency file options
1525//===----------------------------------------------------------------------===//
1526static llvm::cl::opt<std::string>
1527DependencyFile("dependency-file",
1528 llvm::cl::desc("Filename (or -) to write dependency output to"));
1529
1530static llvm::cl::opt<bool>
1531DependenciesIncludeSystemHeaders("sys-header-deps",
1532 llvm::cl::desc("Include system headers in dependency output"));
1533
1534static llvm::cl::list<std::string>
1535DependencyTargets("MT",
1536 llvm::cl::desc("Specify target for dependency"));
1537
1538// FIXME: Implement feature
1539static llvm::cl::opt<bool>
1540PhonyDependencyTarget("MP",
1541 llvm::cl::desc("Create phony target for each dependency "
1542 "(other than main file)"));
1543
Eli Friedman12d3b1d2009-05-19 03:06:47 +00001544//===----------------------------------------------------------------------===//
Eli Friedmane71b85f2009-05-19 10:18:02 +00001545// Analysis options
1546//===----------------------------------------------------------------------===//
1547
1548static llvm::cl::list<Analyses>
1549AnalysisList(llvm::cl::desc("Source Code Analysis - Checks and Analyses"),
1550llvm::cl::values(
1551#define ANALYSIS(NAME, CMDFLAG, DESC, SCOPE)\
1552clEnumValN(NAME, CMDFLAG, DESC),
Eli Friedman0ec78fa2009-05-19 21:10:40 +00001553#include "clang/Frontend/Analyses.def"
Eli Friedmane71b85f2009-05-19 10:18:02 +00001554clEnumValEnd));
1555
Mike Stump1eb44332009-09-09 15:08:12 +00001556static llvm::cl::opt<AnalysisStores>
Eli Friedmane71b85f2009-05-19 10:18:02 +00001557AnalysisStoreOpt("analyzer-store",
1558 llvm::cl::desc("Source Code Analysis - Abstract Memory Store Models"),
1559 llvm::cl::init(BasicStoreModel),
1560 llvm::cl::values(
1561#define ANALYSIS_STORE(NAME, CMDFLAG, DESC, CREATFN)\
1562clEnumValN(NAME##Model, CMDFLAG, DESC),
Eli Friedman0ec78fa2009-05-19 21:10:40 +00001563#include "clang/Frontend/Analyses.def"
Eli Friedmane71b85f2009-05-19 10:18:02 +00001564clEnumValEnd));
1565
Mike Stump1eb44332009-09-09 15:08:12 +00001566static llvm::cl::opt<AnalysisConstraints>
Eli Friedmane71b85f2009-05-19 10:18:02 +00001567AnalysisConstraintsOpt("analyzer-constraints",
1568 llvm::cl::desc("Source Code Analysis - Symbolic Constraint Engines"),
1569 llvm::cl::init(RangeConstraintsModel),
1570 llvm::cl::values(
1571#define ANALYSIS_CONSTRAINTS(NAME, CMDFLAG, DESC, CREATFN)\
1572clEnumValN(NAME##Model, CMDFLAG, DESC),
Eli Friedman0ec78fa2009-05-19 21:10:40 +00001573#include "clang/Frontend/Analyses.def"
Eli Friedmane71b85f2009-05-19 10:18:02 +00001574clEnumValEnd));
1575
1576static llvm::cl::opt<AnalysisDiagClients>
1577AnalysisDiagOpt("analyzer-output",
1578 llvm::cl::desc("Source Code Analysis - Output Options"),
1579 llvm::cl::init(PD_HTML),
1580 llvm::cl::values(
1581#define ANALYSIS_DIAGNOSTICS(NAME, CMDFLAG, DESC, CREATFN, AUTOCREATE)\
1582clEnumValN(PD_##NAME, CMDFLAG, DESC),
Eli Friedman0ec78fa2009-05-19 21:10:40 +00001583#include "clang/Frontend/Analyses.def"
Eli Friedmane71b85f2009-05-19 10:18:02 +00001584clEnumValEnd));
1585
1586static llvm::cl::opt<bool>
1587VisualizeEGDot("analyzer-viz-egraph-graphviz",
1588 llvm::cl::desc("Display exploded graph using GraphViz"));
1589
1590static llvm::cl::opt<bool>
1591VisualizeEGUbi("analyzer-viz-egraph-ubigraph",
1592 llvm::cl::desc("Display exploded graph using Ubigraph"));
1593
1594static llvm::cl::opt<bool>
1595AnalyzeAll("analyzer-opt-analyze-headers",
1596 llvm::cl::desc("Force the static analyzer to analyze "
1597 "functions defined in header files"));
1598
1599static llvm::cl::opt<bool>
1600AnalyzerDisplayProgress("analyzer-display-progress",
1601 llvm::cl::desc("Emit verbose output about the analyzer's progress."));
1602
1603static llvm::cl::opt<bool>
1604PurgeDead("analyzer-purge-dead",
1605 llvm::cl::init(true),
1606 llvm::cl::desc("Remove dead symbols, bindings, and constraints before"
1607 " processing a statement."));
1608
1609static llvm::cl::opt<bool>
1610EagerlyAssume("analyzer-eagerly-assume",
1611 llvm::cl::init(false),
1612 llvm::cl::desc("Eagerly assume the truth/falseness of some "
1613 "symbolic constraints."));
1614
1615static llvm::cl::opt<std::string>
1616AnalyzeSpecificFunction("analyze-function",
1617 llvm::cl::desc("Run analysis on specific function"));
1618
1619static llvm::cl::opt<bool>
1620TrimGraph("trim-egraph",
1621 llvm::cl::desc("Only show error-related paths in the analysis graph"));
1622
1623static AnalyzerOptions ReadAnalyzerOptions() {
1624 AnalyzerOptions Opts;
1625 Opts.AnalysisList = AnalysisList;
1626 Opts.AnalysisStoreOpt = AnalysisStoreOpt;
1627 Opts.AnalysisConstraintsOpt = AnalysisConstraintsOpt;
1628 Opts.AnalysisDiagOpt = AnalysisDiagOpt;
1629 Opts.VisualizeEGDot = VisualizeEGDot;
1630 Opts.VisualizeEGUbi = VisualizeEGUbi;
1631 Opts.AnalyzeAll = AnalyzeAll;
1632 Opts.AnalyzerDisplayProgress = AnalyzerDisplayProgress;
1633 Opts.PurgeDead = PurgeDead;
1634 Opts.EagerlyAssume = EagerlyAssume;
1635 Opts.AnalyzeSpecificFunction = AnalyzeSpecificFunction;
1636 Opts.TrimGraph = TrimGraph;
1637 return Opts;
1638}
1639
1640//===----------------------------------------------------------------------===//
Chris Lattner75a97cb2009-04-17 21:05:01 +00001641// -dump-build-information Stuff
1642//===----------------------------------------------------------------------===//
1643
1644static llvm::cl::opt<std::string>
1645DumpBuildInformation("dump-build-information",
1646 llvm::cl::value_desc("filename"),
1647 llvm::cl::desc("output a dump of some build information to a file"));
1648
1649static llvm::raw_ostream *BuildLogFile = 0;
1650
1651/// LoggingDiagnosticClient - This is a simple diagnostic client that forwards
1652/// all diagnostics to both BuildLogFile and a chained DiagnosticClient.
1653namespace {
1654class LoggingDiagnosticClient : public DiagnosticClient {
1655 llvm::OwningPtr<DiagnosticClient> Chain1;
1656 llvm::OwningPtr<DiagnosticClient> Chain2;
1657public:
Mike Stump1eb44332009-09-09 15:08:12 +00001658
Chris Lattner75a97cb2009-04-17 21:05:01 +00001659 LoggingDiagnosticClient(DiagnosticClient *Normal) {
1660 // Output diags both where requested...
1661 Chain1.reset(Normal);
1662 // .. and to our log file.
1663 Chain2.reset(new TextDiagnosticPrinter(*BuildLogFile,
1664 !NoShowColumn,
1665 !NoCaretDiagnostics,
1666 !NoShowLocation,
1667 PrintSourceRangeInfo,
Chris Lattneraa5bf2e2009-04-19 07:44:08 +00001668 PrintDiagnosticOption,
Douglas Gregorfffd93f2009-05-01 21:53:04 +00001669 !NoDiagnosticsFixIt,
Nate Begeman4e3629e2009-06-25 22:43:10 +00001670 MessageLength));
Chris Lattner75a97cb2009-04-17 21:05:01 +00001671 }
Mike Stump1eb44332009-09-09 15:08:12 +00001672
Chris Lattner75a97cb2009-04-17 21:05:01 +00001673 virtual void setLangOptions(const LangOptions *LO) {
1674 Chain1->setLangOptions(LO);
1675 Chain2->setLangOptions(LO);
1676 }
Mike Stump1eb44332009-09-09 15:08:12 +00001677
Chris Lattner75a97cb2009-04-17 21:05:01 +00001678 virtual bool IncludeInDiagnosticCounts() const {
1679 return Chain1->IncludeInDiagnosticCounts();
1680 }
1681
1682 virtual void HandleDiagnostic(Diagnostic::Level DiagLevel,
1683 const DiagnosticInfo &Info) {
1684 Chain1->HandleDiagnostic(DiagLevel, Info);
1685 Chain2->HandleDiagnostic(DiagLevel, Info);
1686 }
1687};
1688} // end anonymous namespace.
1689
1690static void SetUpBuildDumpLog(unsigned argc, char **argv,
1691 llvm::OwningPtr<DiagnosticClient> &DiagClient) {
Mike Stump1eb44332009-09-09 15:08:12 +00001692
Chris Lattner75a97cb2009-04-17 21:05:01 +00001693 std::string ErrorInfo;
Chris Lattner92bcc272009-08-23 02:59:41 +00001694 BuildLogFile = new llvm::raw_fd_ostream(DumpBuildInformation.c_str(),
Dan Gohmanb044c472009-08-25 15:36:09 +00001695 ErrorInfo);
Mike Stump1eb44332009-09-09 15:08:12 +00001696
Chris Lattner75a97cb2009-04-17 21:05:01 +00001697 if (!ErrorInfo.empty()) {
1698 llvm::errs() << "error opening -dump-build-information file '"
1699 << DumpBuildInformation << "', option ignored!\n";
1700 delete BuildLogFile;
1701 BuildLogFile = 0;
1702 DumpBuildInformation = "";
1703 return;
1704 }
1705
1706 (*BuildLogFile) << "clang-cc command line arguments: ";
1707 for (unsigned i = 0; i != argc; ++i)
1708 (*BuildLogFile) << argv[i] << ' ';
1709 (*BuildLogFile) << '\n';
Mike Stump1eb44332009-09-09 15:08:12 +00001710
Chris Lattner75a97cb2009-04-17 21:05:01 +00001711 // LoggingDiagnosticClient - Insert a new logging diagnostic client in between
1712 // the diagnostic producers and the normal receiver.
1713 DiagClient.reset(new LoggingDiagnosticClient(DiagClient.take()));
1714}
1715
1716
1717
1718//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +00001719// Main driver
1720//===----------------------------------------------------------------------===//
1721
Chris Lattner92bcc272009-08-23 02:59:41 +00001722static llvm::raw_ostream *ComputeOutFile(const std::string &InFile,
1723 const char *Extension,
Eli Friedman66d6f042009-05-18 22:20:00 +00001724 bool Binary,
1725 llvm::sys::Path& OutPath) {
Chris Lattner92bcc272009-08-23 02:59:41 +00001726 llvm::raw_ostream *Ret;
Eli Friedman66d6f042009-05-18 22:20:00 +00001727 std::string OutFile;
Chris Lattner92bcc272009-08-23 02:59:41 +00001728 if (!OutputFile.empty())
Eli Friedman66d6f042009-05-18 22:20:00 +00001729 OutFile = OutputFile;
Chris Lattner92bcc272009-08-23 02:59:41 +00001730 else if (InFile == "-") {
1731 OutFile = "-";
Eli Friedman66d6f042009-05-18 22:20:00 +00001732 } else if (Extension) {
1733 llvm::sys::Path Path(InFile);
1734 Path.eraseSuffix();
1735 Path.appendSuffix(Extension);
Chris Lattnerd57a7ef2009-08-23 22:45:33 +00001736 OutFile = Path.str();
Eli Friedman66d6f042009-05-18 22:20:00 +00001737 } else {
Chris Lattner92bcc272009-08-23 02:59:41 +00001738 OutFile = "-";
Chris Lattner8a5c8092009-02-18 01:20:05 +00001739 }
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +00001740
Chris Lattner92bcc272009-08-23 02:59:41 +00001741 std::string Error;
1742 Ret = new llvm::raw_fd_ostream(OutFile.c_str(), Error,
Dan Gohmanb044c472009-08-25 15:36:09 +00001743 (Binary ? llvm::raw_fd_ostream::F_Binary : 0));
Chris Lattner92bcc272009-08-23 02:59:41 +00001744 if (!Error.empty()) {
1745 // FIXME: Don't fail this way.
1746 llvm::errs() << "ERROR: " << Error << "\n";
1747 ::exit(1);
Ted Kremenekdb094a22007-12-05 18:27:04 +00001748 }
Mike Stump1eb44332009-09-09 15:08:12 +00001749
Chris Lattner92bcc272009-08-23 02:59:41 +00001750 if (OutFile != "-")
1751 OutPath = OutFile;
Eli Friedman66d6f042009-05-18 22:20:00 +00001752
1753 return Ret;
Ted Kremenekdb094a22007-12-05 18:27:04 +00001754}
1755
Daniel Dunbar0794d8d2009-09-17 00:48:00 +00001756static ASTConsumer *CreateConsumerAction(Preprocessor &PP,
1757 const std::string &InFile,
1758 ProgActions PA,
1759 llvm::OwningPtr<llvm::raw_ostream> &OS,
1760 llvm::sys::Path &OutPath,
1761 const llvm::StringMap<bool> &Features,
1762 llvm::LLVMContext& Context) {
Ted Kremenek85888962008-10-21 00:54:44 +00001763 switch (PA) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001764 default:
Daniel Dunbar0794d8d2009-09-17 00:48:00 +00001765 return 0;
Eli Friedman66d6f042009-05-18 22:20:00 +00001766
1767 case ASTPrint:
1768 OS.reset(ComputeOutFile(InFile, 0, false, OutPath));
Daniel Dunbar0794d8d2009-09-17 00:48:00 +00001769 return CreateASTPrinter(OS.get());
Mike Stump1eb44332009-09-09 15:08:12 +00001770
Douglas Gregoree75c052009-05-21 20:55:50 +00001771 case ASTPrintXML:
1772 OS.reset(ComputeOutFile(InFile, "xml", false, OutPath));
Daniel Dunbar0794d8d2009-09-17 00:48:00 +00001773 return CreateASTPrinterXML(OS.get());
Douglas Gregoree75c052009-05-21 20:55:50 +00001774
Eli Friedman66d6f042009-05-18 22:20:00 +00001775 case ASTDump:
Daniel Dunbar0794d8d2009-09-17 00:48:00 +00001776 return CreateASTDumper();
Eli Friedman66d6f042009-05-18 22:20:00 +00001777
Eli Friedman66d6f042009-05-18 22:20:00 +00001778 case ASTView:
Daniel Dunbar0794d8d2009-09-17 00:48:00 +00001779 return CreateASTViewer();
Eli Friedman66d6f042009-05-18 22:20:00 +00001780
1781 case PrintDeclContext:
Daniel Dunbar0794d8d2009-09-17 00:48:00 +00001782 return CreateDeclContextPrinter();
Eli Friedman66d6f042009-05-18 22:20:00 +00001783
1784 case InheritanceView:
Daniel Dunbar0794d8d2009-09-17 00:48:00 +00001785 return CreateInheritanceViewer(InheritanceViewCls);
Eli Friedman66d6f042009-05-18 22:20:00 +00001786
1787 case EmitAssembly:
1788 case EmitLLVM:
Mike Stump1eb44332009-09-09 15:08:12 +00001789 case EmitBC:
Eli Friedman66d6f042009-05-18 22:20:00 +00001790 case EmitLLVMOnly: {
1791 BackendAction Act;
1792 if (ProgAction == EmitAssembly) {
1793 Act = Backend_EmitAssembly;
1794 OS.reset(ComputeOutFile(InFile, "s", true, OutPath));
1795 } else if (ProgAction == EmitLLVM) {
1796 Act = Backend_EmitLL;
1797 OS.reset(ComputeOutFile(InFile, "ll", true, OutPath));
1798 } else if (ProgAction == EmitLLVMOnly) {
1799 Act = Backend_EmitNothing;
1800 } else {
1801 Act = Backend_EmitBC;
1802 OS.reset(ComputeOutFile(InFile, "bc", true, OutPath));
Ted Kremenekdb094a22007-12-05 18:27:04 +00001803 }
Ted Kremenekfdfc1982007-12-19 22:24:34 +00001804
Eli Friedman66d6f042009-05-18 22:20:00 +00001805 CompileOptions Opts;
1806 InitializeCompileOptions(Opts, PP.getLangOptions(), Features);
Daniel Dunbar0794d8d2009-09-17 00:48:00 +00001807 return CreateBackendConsumer(Act, PP.getDiagnostics(), PP.getLangOptions(),
1808 Opts, InFile, OS.get(), Context);
Eli Friedman66d6f042009-05-18 22:20:00 +00001809 }
1810
Daniel Dunbar0794d8d2009-09-17 00:48:00 +00001811 case RewriteObjC:
1812 OS.reset(ComputeOutFile(InFile, "cpp", true, OutPath));
1813 return CreateObjCRewriter(InFile, OS.get(), PP.getDiagnostics(),
1814 PP.getLangOptions(), SilenceRewriteMacroWarning);
1815
1816 case RewriteBlocks:
1817 return CreateBlockRewriter(InFile, PP.getDiagnostics(),
1818 PP.getLangOptions());
1819 }
1820}
1821
1822/// ProcessInputFile - Process a single input file with the specified state.
1823///
1824static void ProcessInputFile(Preprocessor &PP, PreprocessorFactory &PPF,
1825 const std::string &InFile, ProgActions PA,
1826 const llvm::StringMap<bool> &Features,
1827 llvm::LLVMContext& Context) {
1828 llvm::OwningPtr<llvm::raw_ostream> OS;
1829 llvm::OwningPtr<ASTConsumer> Consumer;
1830 bool ClearSourceMgr = false;
1831 FixItRewriter *FixItRewrite = 0;
1832 bool CompleteTranslationUnit = true;
1833 llvm::sys::Path OutPath;
1834
1835 switch (PA) {
1836 default:
1837 Consumer.reset(CreateConsumerAction(PP, InFile, PA, OS, OutPath,
1838 Features, Context));
1839
1840 if (!Consumer.get()) {
1841 fprintf(stderr, "Unexpected program action!\n");
1842 HadErrors = true;
1843 return;
1844 }
1845
1846 break;;
1847
1848 case EmitHTML:
1849 OS.reset(ComputeOutFile(InFile, 0, true, OutPath));
1850 Consumer.reset(CreateHTMLPrinter(OS.get(), PP.getDiagnostics(), &PP, &PPF));
1851 break;
1852
1853 case RunAnalysis:
1854 Consumer.reset(CreateAnalysisConsumer(PP.getDiagnostics(), &PP, &PPF,
1855 PP.getLangOptions(), OutputFile,
1856 ReadAnalyzerOptions()));
1857 break;
1858
Eli Friedman66d6f042009-05-18 22:20:00 +00001859 case GeneratePCH:
Douglas Gregore650c8c2009-07-07 00:12:59 +00001860 if (RelocatablePCH.getValue() && !isysroot.getNumOccurrences()) {
1861 PP.Diag(SourceLocation(), diag::err_relocatable_without_without_isysroot);
1862 RelocatablePCH.setValue(false);
1863 }
Mike Stump1eb44332009-09-09 15:08:12 +00001864
Eli Friedman66d6f042009-05-18 22:20:00 +00001865 OS.reset(ComputeOutFile(InFile, 0, true, OutPath));
Douglas Gregore650c8c2009-07-07 00:12:59 +00001866 if (RelocatablePCH.getValue())
1867 Consumer.reset(CreatePCHGenerator(PP, OS.get(), isysroot.c_str()));
1868 else
1869 Consumer.reset(CreatePCHGenerator(PP, OS.get()));
Eli Friedman66d6f042009-05-18 22:20:00 +00001870 CompleteTranslationUnit = false;
1871 break;
1872
Chris Lattnerc106c102008-10-12 05:03:36 +00001873 case DumpRawTokens: {
Chris Lattner47099742009-02-18 01:51:21 +00001874 llvm::TimeRegion Timer(ClangFrontendTimer);
Chris Lattnerc106c102008-10-12 05:03:36 +00001875 SourceManager &SM = PP.getSourceManager();
Chris Lattnerc106c102008-10-12 05:03:36 +00001876 // Start lexing the specified input file.
Chris Lattner025c3a62009-01-17 07:35:14 +00001877 Lexer RawLex(SM.getMainFileID(), SM, PP.getLangOptions());
Chris Lattnerc106c102008-10-12 05:03:36 +00001878 RawLex.SetKeepWhitespaceMode(true);
1879
1880 Token RawTok;
Chris Lattnerc106c102008-10-12 05:03:36 +00001881 RawLex.LexFromRawLexer(RawTok);
1882 while (RawTok.isNot(tok::eof)) {
1883 PP.DumpToken(RawTok, true);
1884 fprintf(stderr, "\n");
1885 RawLex.LexFromRawLexer(RawTok);
1886 }
1887 ClearSourceMgr = true;
1888 break;
1889 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001890 case DumpTokens: { // Token dump mode.
Chris Lattner47099742009-02-18 01:51:21 +00001891 llvm::TimeRegion Timer(ClangFrontendTimer);
Chris Lattnerd2177732007-07-20 16:59:19 +00001892 Token Tok;
Chris Lattnerc106c102008-10-12 05:03:36 +00001893 // Start preprocessing the specified input file.
Ted Kremenek95041a22007-12-19 22:51:13 +00001894 PP.EnterMainSourceFile();
Reid Spencer5f016e22007-07-11 17:01:13 +00001895 do {
1896 PP.Lex(Tok);
1897 PP.DumpToken(Tok, true);
1898 fprintf(stderr, "\n");
Chris Lattner057aaf62007-10-09 18:03:42 +00001899 } while (Tok.isNot(tok::eof));
Chris Lattnerbd247762007-07-22 06:05:44 +00001900 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001901 break;
1902 }
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001903 case RunPreprocessorOnly:
Reid Spencer5f016e22007-07-11 17:01:13 +00001904 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001905
Douglas Gregorbf1bd6e2009-04-02 23:43:50 +00001906 case GeneratePTH: {
Chris Lattner47099742009-02-18 01:51:21 +00001907 llvm::TimeRegion Timer(ClangFrontendTimer);
Eli Friedmanf54fce82009-05-19 01:02:07 +00001908 if (OutputFile.empty() || OutputFile == "-") {
1909 // FIXME: Don't fail this way.
1910 // FIXME: Verify that we can actually seek in the given file.
Chris Lattner92bcc272009-08-23 02:59:41 +00001911 llvm::errs() << "ERROR: PTH requires an seekable file for output!\n";
Eli Friedmanf54fce82009-05-19 01:02:07 +00001912 ::exit(1);
1913 }
1914 OS.reset(ComputeOutFile(InFile, 0, true, OutPath));
1915 CacheTokens(PP, static_cast<llvm::raw_fd_ostream*>(OS.get()));
Ted Kremenek85888962008-10-21 00:54:44 +00001916 ClearSourceMgr = true;
1917 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001918 }
Douglas Gregor6ab35242009-04-09 21:40:53 +00001919
Chris Lattnercc7dea82009-04-27 22:02:30 +00001920 case PrintPreprocessedInput:
Eli Friedmanf54fce82009-05-19 01:02:07 +00001921 OS.reset(ComputeOutFile(InFile, 0, true, OutPath));
Reid Spencer5f016e22007-07-11 17:01:13 +00001922 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001923
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001924 case ParseNoop:
Reid Spencer5f016e22007-07-11 17:01:13 +00001925 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001926
Chris Lattner47099742009-02-18 01:51:21 +00001927 case ParsePrintCallbacks: {
1928 llvm::TimeRegion Timer(ClangFrontendTimer);
Eli Friedmanf54fce82009-05-19 01:02:07 +00001929 OS.reset(ComputeOutFile(InFile, 0, true, OutPath));
1930 ParseFile(PP, CreatePrintParserActionsAction(PP, OS.get()));
Chris Lattnerbd247762007-07-22 06:05:44 +00001931 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001932 break;
Chris Lattner47099742009-02-18 01:51:21 +00001933 }
1934
1935 case ParseSyntaxOnly: { // -fsyntax-only
1936 llvm::TimeRegion Timer(ClangFrontendTimer);
Ted Kremenek7e7e6252008-08-08 02:46:37 +00001937 Consumer.reset(new ASTConsumer());
Ted Kremenek2bf55142007-09-17 20:49:30 +00001938 break;
Chris Lattner47099742009-02-18 01:51:21 +00001939 }
Mike Stump1eb44332009-09-09 15:08:12 +00001940
Chris Lattnerb57e3d42008-05-08 06:52:13 +00001941 case RewriteMacros:
Eli Friedmanf54fce82009-05-19 01:02:07 +00001942 OS.reset(ComputeOutFile(InFile, 0, true, OutPath));
1943 RewriteMacrosInInput(PP, OS.get());
Chris Lattnerb57e3d42008-05-08 06:52:13 +00001944 ClearSourceMgr = true;
1945 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001946
Eli Friedmanf54fce82009-05-19 01:02:07 +00001947 case RewriteTest:
1948 OS.reset(ComputeOutFile(InFile, 0, true, OutPath));
1949 DoRewriteTest(PP, OS.get());
Chris Lattnerb13c5ee2008-10-12 05:29:20 +00001950 ClearSourceMgr = true;
1951 break;
Douglas Gregor558cb562009-04-02 01:08:08 +00001952
1953 case FixIt:
1954 llvm::TimeRegion Timer(ClangFrontendTimer);
1955 Consumer.reset(new ASTConsumer());
Douglas Gregorde4bf6a2009-04-02 17:13:00 +00001956 FixItRewrite = new FixItRewriter(PP.getDiagnostics(),
Chris Lattner2c78b872009-04-14 23:22:57 +00001957 PP.getSourceManager(),
1958 PP.getLangOptions());
Douglas Gregor558cb562009-04-02 01:08:08 +00001959 break;
Chris Lattner47099742009-02-18 01:51:21 +00001960 }
Ted Kremenek46157b52009-01-28 04:29:29 +00001961
Chris Lattner1aee61a2009-04-27 21:25:27 +00001962 if (FixItAtLocations.size() > 0) {
1963 // Even without the "-fixit" flag, with may have some specific
1964 // locations where the user has requested fixes. Process those
1965 // locations now.
1966 if (!FixItRewrite)
1967 FixItRewrite = new FixItRewriter(PP.getDiagnostics(),
1968 PP.getSourceManager(),
1969 PP.getLangOptions());
Chris Lattner9ecd26a2009-03-28 01:37:17 +00001970
Chris Lattner1aee61a2009-04-27 21:25:27 +00001971 bool AddedFixitLocation = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001972 for (unsigned Idx = 0, Last = FixItAtLocations.size();
Chris Lattner1aee61a2009-04-27 21:25:27 +00001973 Idx != Last; ++Idx) {
1974 RequestedSourceLocation Requested;
Argyrios Kyrtzidis34d25d82009-06-23 22:01:39 +00001975 if (ResolveParsedLocation(FixItAtLocations[Idx],
1976 PP.getFileManager(), Requested)) {
Chris Lattner1aee61a2009-04-27 21:25:27 +00001977 fprintf(stderr, "FIX-IT could not find file \"%s\"\n",
1978 FixItAtLocations[Idx].FileName.c_str());
1979 } else {
1980 FixItRewrite->addFixItLocation(Requested);
1981 AddedFixitLocation = true;
Douglas Gregor26df2f02009-04-02 19:05:20 +00001982 }
1983 }
1984
Chris Lattner1aee61a2009-04-27 21:25:27 +00001985 if (!AddedFixitLocation) {
1986 // All of the fix-it locations were bad. Don't fix anything.
1987 delete FixItRewrite;
1988 FixItRewrite = 0;
1989 }
1990 }
1991
1992 llvm::OwningPtr<ASTContext> ContextOwner;
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001993 if (Consumer)
Chris Lattner9ecd26a2009-03-28 01:37:17 +00001994 ContextOwner.reset(new ASTContext(PP.getLangOptions(),
1995 PP.getSourceManager(),
1996 PP.getTargetInfo(),
1997 PP.getIdentifierTable(),
1998 PP.getSelectorTable(),
Chris Lattner1b63e4f2009-06-14 01:54:56 +00001999 PP.getBuiltinInfo(),
Douglas Gregor2deaea32009-04-22 18:49:13 +00002000 /* FreeMemory = */ !DisableFree,
Chris Lattner1b63e4f2009-06-14 01:54:56 +00002001 /* size_reserve = */0));
Mike Stump1eb44332009-09-09 15:08:12 +00002002
Chris Lattnercc7dea82009-04-27 22:02:30 +00002003 llvm::OwningPtr<PCHReader> Reader;
2004 llvm::OwningPtr<ExternalASTSource> Source;
Mike Stump1eb44332009-09-09 15:08:12 +00002005
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002006 if (!ImplicitIncludePCH.empty()) {
Douglas Gregore650c8c2009-07-07 00:12:59 +00002007 // If the user specified -isysroot, it will be used for relocatable PCH
2008 // files.
2009 const char *isysrootPCH = 0;
2010 if (isysroot.getNumOccurrences() != 0)
2011 isysrootPCH = isysroot.c_str();
Mike Stump1eb44332009-09-09 15:08:12 +00002012
Douglas Gregore650c8c2009-07-07 00:12:59 +00002013 Reader.reset(new PCHReader(PP, ContextOwner.get(), isysrootPCH));
Mike Stump1eb44332009-09-09 15:08:12 +00002014
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002015 // The user has asked us to include a precompiled header. Load
2016 // the precompiled header into the AST context.
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002017 switch (Reader->ReadPCH(ImplicitIncludePCH)) {
2018 case PCHReader::Success: {
Douglas Gregore721f952009-04-28 18:58:38 +00002019 // Set the predefines buffer as suggested by the PCH
2020 // reader. Typically, the predefines buffer will be empty.
2021 PP.setPredefines(Reader->getSuggestedPredefines());
2022
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002023 // Attach the PCH reader to the AST context as an external AST
2024 // source, so that declarations will be deserialized from the
2025 // PCH file as needed.
Chris Lattnercc7dea82009-04-27 22:02:30 +00002026 if (ContextOwner) {
2027 Source.reset(Reader.take());
Douglas Gregore1d918e2009-04-10 23:10:45 +00002028 ContextOwner->setExternalSource(Source);
Chris Lattnercc7dea82009-04-27 22:02:30 +00002029 }
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002030 break;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002031 }
2032
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002033 case PCHReader::Failure:
2034 // Unrecoverable failure: don't even try to process the input
2035 // file.
2036 return;
2037
2038 case PCHReader::IgnorePCH:
Douglas Gregor1ab86ac2009-04-28 22:01:16 +00002039 // No suitable PCH file could be found. Return an error.
2040 return;
2041
2042#if 0
2043 // FIXME: We can recover from failed attempts to load PCH
2044 // files. This code will do so, if we ever want to enable it.
2045
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002046 // We delayed the initialization of builtins in the hope of
2047 // loading the PCH file. Since the PCH file could not be
2048 // loaded, initialize builtins now.
2049 if (ContextOwner)
2050 ContextOwner->InitializeBuiltins(PP.getIdentifierTable());
Douglas Gregor1ab86ac2009-04-28 22:01:16 +00002051#endif
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002052 }
2053
2054 // Finish preprocessor initialization. We do this now (rather
2055 // than earlier) because this initialization creates new source
2056 // location entries in the source manager, which must come after
2057 // the source location entries for the PCH file.
2058 if (InitializeSourceManager(PP, InFile))
2059 return;
Ted Kremenek46157b52009-01-28 04:29:29 +00002060 }
Douglas Gregor81b747b2009-09-17 21:32:03 +00002061
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002062 // If we have an ASTConsumer, run the parser with it.
Douglas Gregor81b747b2009-09-17 21:32:03 +00002063 if (Consumer) {
2064 CodeCompleteConsumer *(*CreateCodeCompleter)(Sema &, void *) = 0;
2065 void *CreateCodeCompleterData = 0;
2066
2067 if (DumpCodeCompletion) {
2068 // To dump code-completion information, we chop off the file at the
2069 // location of the string $$N$$, where N is the value provided to
2070 // -code-completion-dump, and then tell the lexer to return a
2071 // code-completion token before it hits the end of the file.
2072 // FIXME: Find $$N$$ in the main file buffer
2073
2074 PP.SetMainFileEofCodeCompletion();
2075
2076 // Set up the creation routine for code-completion.
2077 CreateCodeCompleter = BuildPrintingCodeCompleter;
2078 }
2079
Mike Stump1eb44332009-09-09 15:08:12 +00002080 ParseAST(PP, Consumer.get(), *ContextOwner.get(), Stats,
Douglas Gregor81b747b2009-09-17 21:32:03 +00002081 CompleteTranslationUnit,
2082 CreateCodeCompleter, CreateCodeCompleterData);
2083 }
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002084
2085 if (PA == RunPreprocessorOnly) { // Just lex as fast as we can, no output.
2086 llvm::TimeRegion Timer(ClangFrontendTimer);
2087 Token Tok;
2088 // Start parsing the specified input file.
2089 PP.EnterMainSourceFile();
2090 do {
2091 PP.Lex(Tok);
2092 } while (Tok.isNot(tok::eof));
2093 ClearSourceMgr = true;
2094 } else if (PA == ParseNoop) { // -parse-noop
2095 llvm::TimeRegion Timer(ClangFrontendTimer);
2096 ParseFile(PP, new MinimalAction(PP));
2097 ClearSourceMgr = true;
Chris Lattnercc7dea82009-04-27 22:02:30 +00002098 } else if (PA == PrintPreprocessedInput){ // -E mode.
2099 llvm::TimeRegion Timer(ClangFrontendTimer);
Eli Friedman12d3b1d2009-05-19 03:06:47 +00002100 if (DumpMacros)
2101 DoPrintMacros(PP, OS.get());
2102 else
2103 DoPrintPreprocessedInput(PP, OS.get(), EnableCommentOutput,
2104 EnableMacroCommentOutput,
2105 DisableLineMarkers, DumpDefines);
Chris Lattnercc7dea82009-04-27 22:02:30 +00002106 ClearSourceMgr = true;
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002107 }
Mike Stump1eb44332009-09-09 15:08:12 +00002108
Chris Lattner1aee61a2009-04-27 21:25:27 +00002109 if (FixItRewrite)
2110 FixItRewrite->WriteFixedFile(InFile, OutputFile);
Daniel Dunbar70186ab2009-07-29 02:40:09 +00002111
2112 // Disable the consumer prior to the context, the consumer may perform actions
2113 // in its destructor which require the context.
2114 if (DisableFree)
2115 Consumer.take();
2116 else
2117 Consumer.reset();
Mike Stump1eb44332009-09-09 15:08:12 +00002118
Chris Lattner1aee61a2009-04-27 21:25:27 +00002119 // If in -disable-free mode, don't deallocate ASTContext.
2120 if (DisableFree)
2121 ContextOwner.take();
2122 else
2123 ContextOwner.reset(); // Delete ASTContext
Eli Friedman66d6f042009-05-18 22:20:00 +00002124
Daniel Dunbar879c3ea2008-10-27 22:03:52 +00002125 if (VerifyDiagnostics)
Daniel Dunbar276373d2008-10-27 22:10:13 +00002126 if (CheckDiagnostics(PP))
2127 exit(1);
Chris Lattnere66b65c2008-02-06 01:42:25 +00002128
Reid Spencer5f016e22007-07-11 17:01:13 +00002129 if (Stats) {
Ted Kremenekfdfc1982007-12-19 22:24:34 +00002130 fprintf(stderr, "\nSTATISTICS FOR '%s':\n", InFile.c_str());
Reid Spencer5f016e22007-07-11 17:01:13 +00002131 PP.PrintStats();
2132 PP.getIdentifierTable().PrintStats();
Chris Lattnerdee73592007-12-15 20:48:40 +00002133 PP.getHeaderSearchInfo().PrintStats();
Ted Kremenek1b95a652009-01-09 18:20:21 +00002134 PP.getSourceManager().PrintStats();
Reid Spencer5f016e22007-07-11 17:01:13 +00002135 fprintf(stderr, "\n");
2136 }
Chris Lattnerbd247762007-07-22 06:05:44 +00002137
Mike Stump1eb44332009-09-09 15:08:12 +00002138 // For a multi-file compilation, some things are ok with nuking the source
Chris Lattnerbd247762007-07-22 06:05:44 +00002139 // manager tables, other require stable fileid/macroid's across multiple
2140 // files.
Chris Lattnerdee73592007-12-15 20:48:40 +00002141 if (ClearSourceMgr)
2142 PP.getSourceManager().clearIDTables();
Daniel Dunbard68ba0e2008-11-11 06:35:39 +00002143
Eli Friedman66d6f042009-05-18 22:20:00 +00002144 // Always delete the output stream because we don't want to leak file
2145 // handles. Also, we don't want to try to erase an open file.
2146 OS.reset();
2147
2148 if ((HadErrors || (PP.getDiagnostics().getNumErrors() != 0)) &&
2149 !OutPath.isEmpty()) {
2150 // If we had errors, try to erase the output file.
2151 OutPath.eraseFromDisk();
2152 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002153}
2154
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +00002155/// ProcessInputFile - Process a single AST input file with the specified state.
2156///
2157static void ProcessASTInputFile(const std::string &InFile, ProgActions PA,
2158 const llvm::StringMap<bool> &Features,
2159 Diagnostic &Diags, FileManager &FileMgr,
2160 llvm::LLVMContext& Context) {
2161 // FIXME: This is manufactoring its own diags and source manager, we should
2162 // reuse ours.
2163 std::string Error;
Daniel Dunbar31b87d82009-09-21 03:03:39 +00002164 llvm::OwningPtr<ASTUnit> AST(ASTUnit::LoadFromPCHFile(InFile, Diags, FileMgr,
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +00002165 &Error));
2166 if (!AST) {
2167 Diags.Report(FullSourceLoc(), diag::err_fe_invalid_ast_file) << Error;
2168 return;
2169 }
2170
2171 Preprocessor &PP = AST->getPreprocessor();
2172
2173 llvm::OwningPtr<llvm::raw_ostream> OS;
2174 llvm::sys::Path OutPath;
2175 llvm::OwningPtr<ASTConsumer> Consumer(CreateConsumerAction(PP, InFile, PA, OS,
2176 OutPath, Features,
2177 Context));
2178
2179 if (!Consumer.get()) {
2180 Diags.Report(FullSourceLoc(), diag::err_fe_invalid_ast_action);
2181 return;
2182 }
2183
Daniel Dunbara674bf42009-09-21 03:03:56 +00002184 // Set the main file ID to an empty file.
2185 //
2186 // FIXME: We probably shouldn't need this, but for now this is the simplest
2187 // way to reuse the logic in ParseAST.
2188 const char *EmptyStr = "";
2189 llvm::MemoryBuffer *SB =
2190 llvm::MemoryBuffer::getMemBuffer(EmptyStr, EmptyStr, "<dummy input>");
2191 AST->getSourceManager().createMainFileIDForMemBuffer(SB);
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +00002192
Daniel Dunbara674bf42009-09-21 03:03:56 +00002193 // Stream the input AST to the consumer.
2194 ParseAST(PP, Consumer.get(), AST->getASTContext(), Stats);
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +00002195
2196 // Release the consumer and the AST, in that order since the consumer may
2197 // perform actions in its destructor which require the context.
2198 if (DisableFree) {
2199 Consumer.take();
2200 AST.take();
2201 } else {
2202 Consumer.reset();
2203 AST.reset();
2204 }
2205
2206 // Always delete the output stream because we don't want to leak file
2207 // handles. Also, we don't want to try to erase an open file.
2208 OS.reset();
2209
2210 if ((HadErrors || (PP.getDiagnostics().getNumErrors() != 0)) &&
2211 !OutPath.isEmpty()) {
2212 // If we had errors, try to erase the output file.
2213 OutPath.eraseFromDisk();
2214 }
2215}
2216
Reid Spencer5f016e22007-07-11 17:01:13 +00002217static llvm::cl::list<std::string>
2218InputFilenames(llvm::cl::Positional, llvm::cl::desc("<input files>"));
2219
Daniel Dunbar70121eb2009-08-10 03:40:28 +00002220static void LLVMErrorHandler(void *UserData, const std::string &Message) {
2221 Diagnostic &Diags = *static_cast<Diagnostic*>(UserData);
2222
2223 Diags.Report(FullSourceLoc(), diag::err_fe_error_backend) << Message;
2224
2225 // We cannot recover from llvm errors.
2226 exit(1);
2227}
2228
Reid Spencer5f016e22007-07-11 17:01:13 +00002229int main(int argc, char **argv) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002230 llvm::sys::PrintStackTraceOnErrorSignal();
Chris Lattner09e94a32009-03-04 21:41:39 +00002231 llvm::PrettyStackTraceProgram X(argc, argv);
Owen Andersond7200462009-07-16 00:14:12 +00002232 llvm::LLVMContext &Context = llvm::getGlobalContext();
Daniel Dunbard6970812009-09-02 23:20:15 +00002233
Daniel Dunbar4d861512009-09-03 04:54:12 +00002234 // Initialize targets first, so that --version shows registered targets.
Chris Lattner2fe11942009-06-17 17:25:50 +00002235 llvm::InitializeAllTargets();
2236 llvm::InitializeAllAsmPrinters();
Daniel Dunbard6970812009-09-02 23:20:15 +00002237
2238 llvm::cl::ParseCommandLineOptions(argc, argv,
2239 "LLVM 'Clang' Compiler: http://clang.llvm.org\n");
Mike Stump1eb44332009-09-09 15:08:12 +00002240
Chris Lattner47099742009-02-18 01:51:21 +00002241 if (TimeReport)
2242 ClangFrontendTimer = new llvm::Timer("Clang front-end time");
Mike Stump1eb44332009-09-09 15:08:12 +00002243
Daniel Dunbar08e6dc62009-05-28 16:37:33 +00002244 if (Verbose)
Mike Stump3cbf5a02009-09-15 21:49:22 +00002245 llvm::errs() << "clang-cc version " CLANG_VERSION_STRING
2246 << " based upon " << PACKAGE_STRING
Daniel Dunbar2e30e592009-09-04 17:43:10 +00002247 << " hosted on " << llvm::sys::getHostTriple() << "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00002248
Reid Spencer5f016e22007-07-11 17:01:13 +00002249 // If no input was specified, read from stdin.
2250 if (InputFilenames.empty())
2251 InputFilenames.push_back("-");
Douglas Gregor68a0d782009-05-02 00:03:46 +00002252
Ted Kremenek31e703b2007-12-11 23:28:38 +00002253 // Create the diagnostic client for reporting errors or for
2254 // implementing -verify.
Chris Lattner409d4e72009-04-17 20:40:01 +00002255 llvm::OwningPtr<DiagnosticClient> DiagClient;
2256 if (VerifyDiagnostics) {
2257 // When checking diagnostics, just buffer them up.
2258 DiagClient.reset(new TextDiagnosticBuffer());
2259 if (InputFilenames.size() != 1) {
2260 fprintf(stderr, "-verify only works on single input files for now.\n");
2261 return 1;
2262 }
2263 if (!HTMLDiag.empty()) {
2264 fprintf(stderr, "-verify and -html-diags don't work together\n");
2265 return 1;
2266 }
2267 } else if (HTMLDiag.empty()) {
Ted Kremenekb4398aa2008-08-07 17:49:57 +00002268 // Print diagnostics to stderr by default.
Douglas Gregor68a0d782009-05-02 00:03:46 +00002269
2270 // If -fmessage-length=N was not specified, determine whether this
2271 // is a terminal and, if so, implicitly define -fmessage-length
2272 // appropriately.
2273 if (MessageLength.getNumOccurrences() == 0)
Douglas Gregor67187ce2009-05-11 18:06:49 +00002274 MessageLength.setValue(llvm::sys::Process::StandardErrColumns());
Douglas Gregor68a0d782009-05-02 00:03:46 +00002275
Torok Edwin603fca72009-06-04 07:18:23 +00002276 if (!NoColorDiagnostic) {
2277 NoColorDiagnostic.setValue(!llvm::sys::Process::StandardErrHasColors());
2278 }
2279
Chris Lattner409d4e72009-04-17 20:40:01 +00002280 DiagClient.reset(new TextDiagnosticPrinter(llvm::errs(),
Chris Lattnera03a5b52008-11-19 06:56:25 +00002281 !NoShowColumn,
Chris Lattner65f5e642009-01-30 19:01:41 +00002282 !NoCaretDiagnostics,
Chris Lattner1fbee5d2009-03-13 01:08:23 +00002283 !NoShowLocation,
Chris Lattnerd51d74a2009-04-16 05:44:38 +00002284 PrintSourceRangeInfo,
Chris Lattneraa5bf2e2009-04-19 07:44:08 +00002285 PrintDiagnosticOption,
Douglas Gregorfffd93f2009-05-01 21:53:04 +00002286 !NoDiagnosticsFixIt,
Torok Edwin603fca72009-06-04 07:18:23 +00002287 MessageLength,
2288 !NoColorDiagnostic));
Ted Kremenekb4398aa2008-08-07 17:49:57 +00002289 } else {
Chris Lattner409d4e72009-04-17 20:40:01 +00002290 DiagClient.reset(CreateHTMLDiagnosticClient(HTMLDiag));
Reid Spencer5f016e22007-07-11 17:01:13 +00002291 }
Mike Stump1eb44332009-09-09 15:08:12 +00002292
Chris Lattner75a97cb2009-04-17 21:05:01 +00002293 if (!DumpBuildInformation.empty()) {
2294 if (!HTMLDiag.empty()) {
2295 fprintf(stderr,
2296 "-dump-build-information and -html-diags don't work together\n");
2297 return 1;
2298 }
Mike Stump1eb44332009-09-09 15:08:12 +00002299
Chris Lattner75a97cb2009-04-17 21:05:01 +00002300 SetUpBuildDumpLog(argc, argv, DiagClient);
2301 }
Mike Stump1eb44332009-09-09 15:08:12 +00002302
Ted Kremenekb4398aa2008-08-07 17:49:57 +00002303
Reid Spencer5f016e22007-07-11 17:01:13 +00002304 // Configure our handling of diagnostics.
Ted Kremenekb4398aa2008-08-07 17:49:57 +00002305 Diagnostic Diags(DiagClient.get());
Eli Friedman0eeb86e2009-05-19 01:17:04 +00002306 if (ProcessWarningOptions(Diags, OptWarnings, OptPedantic, OptPedanticErrors,
2307 OptNoWarnings))
Sebastian Redl63a9e0f2009-03-06 17:41:35 +00002308 return 1;
Ted Kremenek31e703b2007-12-11 23:28:38 +00002309
Daniel Dunbar70121eb2009-08-10 03:40:28 +00002310 // Set an error handler, so that any LLVM backend diagnostics go through our
2311 // error handler.
2312 llvm::llvm_install_error_handler(LLVMErrorHandler,
2313 static_cast<void*>(&Diags));
2314
Chris Lattner4f037832007-12-05 23:24:17 +00002315 // -I- is a deprecated GCC feature, scan for it and reject it.
2316 for (unsigned i = 0, e = I_dirs.size(); i != e; ++i) {
2317 if (I_dirs[i] == "-") {
Mike Stump1eb44332009-09-09 15:08:12 +00002318 Diags.Report(FullSourceLoc(), diag::err_pp_I_dash_not_supported);
Chris Lattner4f037832007-12-05 23:24:17 +00002319 I_dirs.erase(I_dirs.begin()+i);
2320 --i;
2321 }
2322 }
Chris Lattner11215192008-03-14 06:12:05 +00002323
2324 // Get information about the target being compiled for.
Chris Lattner2f60af72009-09-12 22:45:58 +00002325 llvm::Triple Triple = CreateTargetTriple();
2326 llvm::OwningPtr<TargetInfo>
2327 Target(TargetInfo::CreateTargetInfo(Triple.getTriple()));
Mike Stump1eb44332009-09-09 15:08:12 +00002328
Chris Lattner11215192008-03-14 06:12:05 +00002329 if (Target == 0) {
Mike Stump1eb44332009-09-09 15:08:12 +00002330 Diags.Report(FullSourceLoc(), diag::err_fe_unknown_triple)
Chris Lattner2f60af72009-09-12 22:45:58 +00002331 << Triple.getTriple().c_str();
Sebastian Redlc5613db2009-03-07 12:09:25 +00002332 return 1;
Chris Lattner11215192008-03-14 06:12:05 +00002333 }
Mike Stump1eb44332009-09-09 15:08:12 +00002334
Daniel Dunbar73b79592009-09-14 00:02:12 +00002335 // Set the target ABI if specified.
2336 if (!TargetABI.empty()) {
2337 if (!Target->setABI(TargetABI)) {
2338 Diags.Report(FullSourceLoc(), diag::err_fe_unknown_target_abi)
2339 << TargetABI;
2340 return 1;
2341 }
2342 }
2343
Daniel Dunbard4270232009-01-20 23:17:32 +00002344 if (!InheritanceViewCls.empty()) // C++ visualization?
Ted Kremenek7cae2f62008-10-23 23:36:29 +00002345 ProgAction = InheritanceView;
Mike Stump1eb44332009-09-09 15:08:12 +00002346
Ted Kremenekc0c03bc2008-06-06 22:42:39 +00002347 llvm::OwningPtr<SourceManager> SourceMgr;
Mike Stump1eb44332009-09-09 15:08:12 +00002348
Chris Lattner2c78b872009-04-14 23:22:57 +00002349 // Create a file manager object to provide access to and cache the filesystem.
2350 FileManager FileMgr;
Douglas Gregor4fed3f42009-04-27 18:38:38 +00002351
Daniel Dunbar868bd0a2009-05-06 03:16:41 +00002352 // Compute the feature set, unfortunately this effects the language!
2353 llvm::StringMap<bool> Features;
2354 ComputeFeatureMap(Target.get(), Features);
2355
Reid Spencer5f016e22007-07-11 17:01:13 +00002356 for (unsigned i = 0, e = InputFilenames.size(); i != e; ++i) {
Ted Kremenek31e703b2007-12-11 23:28:38 +00002357 const std::string &InFile = InputFilenames[i];
Mike Stump1eb44332009-09-09 15:08:12 +00002358
Daniel Dunbaraca2ebd2009-09-17 00:48:13 +00002359 LangKind LK = GetLanguage(InFile);
2360 // AST inputs are handled specially.
2361 if (LK == langkind_ast) {
2362 ProcessASTInputFile(InFile, ProgAction, Features,
2363 Diags, FileMgr, Context);
2364 continue;
2365 }
2366
Chris Lattnerf63aea32009-03-04 21:40:56 +00002367 /// Create a SourceManager object. This tracks and owns all the file
2368 /// buffers allocated to a translation unit.
2369 if (!SourceMgr)
2370 SourceMgr.reset(new SourceManager());
2371 else
2372 SourceMgr->clearIDTables();
Mike Stump1eb44332009-09-09 15:08:12 +00002373
Chris Lattnerf63aea32009-03-04 21:40:56 +00002374 // Initialize language options, inferring file types from input filenames.
2375 LangOptions LangInfo;
Chris Lattner409d4e72009-04-17 20:40:01 +00002376 DiagClient->setLangOptions(&LangInfo);
Mike Stump1eb44332009-09-09 15:08:12 +00002377
Daniel Dunbar0b5b0da2009-04-01 05:09:09 +00002378 InitializeLangOptions(LangInfo, LK);
Daniel Dunbar868bd0a2009-05-06 03:16:41 +00002379 InitializeLanguageStandard(LangInfo, LK, Target.get(), Features);
Mike Stump1eb44332009-09-09 15:08:12 +00002380
Chris Lattnerf63aea32009-03-04 21:40:56 +00002381 // Process the -I options and set them in the HeaderInfo.
2382 HeaderSearch HeaderInfo(FileMgr);
Mike Stump1eb44332009-09-09 15:08:12 +00002383
2384
Chris Lattnerf63aea32009-03-04 21:40:56 +00002385 InitializeIncludePaths(argv[0], HeaderInfo, FileMgr, LangInfo);
Mike Stump1eb44332009-09-09 15:08:12 +00002386
Chris Lattnerf63aea32009-03-04 21:40:56 +00002387 // Set up the preprocessor with these options.
Eli Friedmanf086e3b2009-05-18 07:39:39 +00002388 DriverPreprocessorFactory PPFactory(Diags, LangInfo, *Target,
Chris Lattnerf63aea32009-03-04 21:40:56 +00002389 *SourceMgr.get(), HeaderInfo);
Mike Stump1eb44332009-09-09 15:08:12 +00002390
Chris Lattnerf63aea32009-03-04 21:40:56 +00002391 llvm::OwningPtr<Preprocessor> PP(PPFactory.CreatePreprocessor());
Mike Stump1eb44332009-09-09 15:08:12 +00002392
Chris Lattnerf63aea32009-03-04 21:40:56 +00002393 if (!PP)
2394 continue;
Ted Kremenekb4398aa2008-08-07 17:49:57 +00002395
Eli Friedmanb5c8f8b2009-05-19 03:35:57 +00002396 // Handle generating dependencies, if requested
2397 if (!DependencyFile.empty()) {
2398 llvm::raw_ostream *DependencyOS;
2399 if (DependencyTargets.empty()) {
2400 // FIXME: Use a proper diagnostic
Chris Lattner92bcc272009-08-23 02:59:41 +00002401 llvm::errs() << "-dependency-file requires at least one -MT option\n";
Eli Friedmanb5c8f8b2009-05-19 03:35:57 +00002402 HadErrors = true;
2403 continue;
2404 }
2405 std::string ErrStr;
2406 DependencyOS =
Dan Gohmanb044c472009-08-25 15:36:09 +00002407 new llvm::raw_fd_ostream(DependencyFile.c_str(), ErrStr);
Eli Friedmanb5c8f8b2009-05-19 03:35:57 +00002408 if (!ErrStr.empty()) {
2409 // FIXME: Use a proper diagnostic
Chris Lattner92bcc272009-08-23 02:59:41 +00002410 llvm::errs() << "unable to open dependency file: " + ErrStr;
Eli Friedmanb5c8f8b2009-05-19 03:35:57 +00002411 HadErrors = true;
2412 continue;
2413 }
2414
2415 AttachDependencyFileGen(PP.get(), DependencyOS, DependencyTargets,
2416 DependenciesIncludeSystemHeaders,
2417 PhonyDependencyTarget);
2418 }
2419
Chris Lattner1b63e4f2009-06-14 01:54:56 +00002420 if (ImplicitIncludePCH.empty()) {
2421 if (InitializeSourceManager(*PP.get(), InFile))
2422 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00002423
Chris Lattner1b63e4f2009-06-14 01:54:56 +00002424 // Initialize builtin info.
2425 PP->getBuiltinInfo().InitializeBuiltins(PP->getIdentifierTable(),
Chris Lattner1b63e4f2009-06-14 01:54:56 +00002426 PP->getLangOptions().NoBuiltin);
2427 }
Douglas Gregor14f79002009-04-10 03:52:48 +00002428
Chris Lattner409d4e72009-04-17 20:40:01 +00002429 if (!HTMLDiag.empty())
2430 ((PathDiagnosticClient*)DiagClient.get())->SetPreprocessor(PP.get());
Chris Lattnerf63aea32009-03-04 21:40:56 +00002431
2432 // Process the source file.
Owen Andersonc93f4982009-07-01 21:23:16 +00002433 ProcessInputFile(*PP, PPFactory, InFile, ProgAction, Features, Context);
Mike Stump1eb44332009-09-09 15:08:12 +00002434
Chris Lattner40469652009-04-17 20:16:08 +00002435 HeaderInfo.ClearFileInfo();
Chris Lattner409d4e72009-04-17 20:40:01 +00002436 DiagClient->setLangOptions(0);
Reid Spencer5f016e22007-07-11 17:01:13 +00002437 }
Chris Lattner11215192008-03-14 06:12:05 +00002438
Mike Stumpfc0fed32009-04-28 01:19:10 +00002439 if (!NoCaretDiagnostics)
2440 if (unsigned NumDiagnostics = Diags.getNumDiagnostics())
2441 fprintf(stderr, "%d diagnostic%s generated.\n", NumDiagnostics,
2442 (NumDiagnostics == 1 ? "" : "s"));
Mike Stump1eb44332009-09-09 15:08:12 +00002443
Reid Spencer5f016e22007-07-11 17:01:13 +00002444 if (Stats) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002445 FileMgr.PrintStats();
2446 fprintf(stderr, "\n");
2447 }
Chris Lattner75a97cb2009-04-17 21:05:01 +00002448
2449 delete ClangFrontendTimer;
2450 delete BuildLogFile;
Mike Stump1eb44332009-09-09 15:08:12 +00002451
Daniel Dunbar276373d2008-10-27 22:10:13 +00002452 // If verifying diagnostics and we reached here, all is well.
2453 if (VerifyDiagnostics)
2454 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002455
Daniel Dunbar524b86f2008-10-28 00:38:08 +00002456 // Managed static deconstruction. Useful for making things like
2457 // -time-passes usable.
2458 llvm::llvm_shutdown();
2459
Daniel Dunbarb0adbba2008-10-04 23:42:49 +00002460 return HadErrors || (Diags.getNumErrors() != 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00002461}