blob: 3c451c8c0d2e32529808fe78204c0b8c2eb208b8 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- clang.cpp - C-Language Front-end ---------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This utility may be invoked in the following manner:
11// clang --help - Output help info.
12// clang [options] - Read from stdin.
13// clang [options] file - Read from "file".
14// clang [options] file1 file2 - Read these files.
15//
16//===----------------------------------------------------------------------===//
17//
18// TODO: Options to support:
19//
Chris Lattnerdddaa9c2009-02-18 01:17:01 +000020// -Wfatal-errors
Reid Spencer5f016e22007-07-11 17:01:13 +000021// -ftabstop=width
22//
23//===----------------------------------------------------------------------===//
24
Eli Friedman0ec78fa2009-05-19 21:10:40 +000025#include "clang/Frontend/AnalysisConsumer.h"
Eli Friedman8ceb0d92009-05-18 23:02:01 +000026#include "clang/Frontend/ASTConsumers.h"
Daniel Dunbare1bd4e62009-03-02 06:16:29 +000027#include "clang/Frontend/CompileOptions.h"
Douglas Gregor558cb562009-04-02 01:08:08 +000028#include "clang/Frontend/FixItRewriter.h"
Daniel Dunbar50f4f462009-03-12 10:14:16 +000029#include "clang/Frontend/FrontendDiagnostic.h"
Daniel Dunbare1bd4e62009-03-02 06:16:29 +000030#include "clang/Frontend/InitHeaderSearch.h"
Chris Lattnere116ccf2009-04-21 05:40:52 +000031#include "clang/Frontend/InitPreprocessor.h"
Daniel Dunbar50f4f462009-03-12 10:14:16 +000032#include "clang/Frontend/PathDiagnosticClients.h"
Douglas Gregor2cf26342009-04-09 22:27:44 +000033#include "clang/Frontend/PCHReader.h"
Daniel Dunbare1bd4e62009-03-02 06:16:29 +000034#include "clang/Frontend/TextDiagnosticBuffer.h"
35#include "clang/Frontend/TextDiagnosticPrinter.h"
Argyrios Kyrtzidis34d25d82009-06-23 22:01:39 +000036#include "clang/Frontend/CommandLineSourceLoc.h"
Eli Friedmanb09f6e12009-05-19 04:14:29 +000037#include "clang/Frontend/Utils.h"
Ted Kremenek88f5cde2008-03-27 06:17:42 +000038#include "clang/Analysis/PathDiagnostic.h"
Chris Lattner8ee3c032008-02-06 02:01:47 +000039#include "clang/CodeGen/ModuleBuilder.h"
Chris Lattnere91c1342008-02-06 00:23:21 +000040#include "clang/Sema/ParseAST.h"
Chris Lattner88eccaf2009-01-29 06:55:46 +000041#include "clang/Sema/SemaDiagnostic.h"
Chris Lattner556beb72007-09-15 22:56:56 +000042#include "clang/AST/ASTConsumer.h"
Chris Lattner1266eca2009-03-28 04:31:31 +000043#include "clang/AST/ASTContext.h"
44#include "clang/AST/Decl.h"
Chris Lattner682bf922009-03-29 16:50:03 +000045#include "clang/AST/DeclGroup.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000046#include "clang/Parse/Parser.h"
47#include "clang/Lex/HeaderSearch.h"
Chris Lattnerdb766842009-02-06 04:16:41 +000048#include "clang/Lex/LexDiagnostic.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000049#include "clang/Basic/FileManager.h"
50#include "clang/Basic/SourceManager.h"
51#include "clang/Basic/TargetInfo.h"
Daniel Dunbaraa338bc2009-05-06 04:07:06 +000052#include "clang/Basic/Version.h"
Owen Anderson42253cc2009-07-01 17:00:06 +000053#include "llvm/LLVMContext.h"
Chris Lattnerba0f25f2008-09-30 20:16:56 +000054#include "llvm/ADT/OwningPtr.h"
Chris Lattner8f3dab82007-12-15 23:20:07 +000055#include "llvm/ADT/SmallPtrSet.h"
Chris Lattnerba0f25f2008-09-30 20:16:56 +000056#include "llvm/ADT/StringExtras.h"
Daniel Dunbar868bd0a2009-05-06 03:16:41 +000057#include "llvm/ADT/StringMap.h"
Chris Lattnerb8e240e2009-04-08 18:24:34 +000058#include "llvm/ADT/STLExtras.h"
Chris Lattnerba0f25f2008-09-30 20:16:56 +000059#include "llvm/Config/config.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000060#include "llvm/Support/CommandLine.h"
Daniel Dunbar70121eb2009-08-10 03:40:28 +000061#include "llvm/Support/ErrorHandling.h"
Daniel Dunbar524b86f2008-10-28 00:38:08 +000062#include "llvm/Support/ManagedStatic.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000063#include "llvm/Support/MemoryBuffer.h"
Zhongxing Xu20922362008-11-26 05:23:17 +000064#include "llvm/Support/PluginLoader.h"
Chris Lattner09e94a32009-03-04 21:41:39 +000065#include "llvm/Support/PrettyStackTrace.h"
Chris Lattner47099742009-02-18 01:51:21 +000066#include "llvm/Support/Timer.h"
Chris Lattner0fa0daa2009-08-24 04:11:30 +000067#include "llvm/Support/raw_ostream.h"
Daniel Dunbare553a722008-10-02 01:21:33 +000068#include "llvm/System/Host.h"
Chris Lattnerdcaa0962008-03-03 03:16:03 +000069#include "llvm/System/Path.h"
Douglas Gregor44cf08e2009-05-03 03:52:38 +000070#include "llvm/System/Process.h"
Eli Friedman66d6f042009-05-18 22:20:00 +000071#include "llvm/System/Program.h"
Chris Lattnerba0f25f2008-09-30 20:16:56 +000072#include "llvm/System/Signals.h"
Chris Lattner2fe11942009-06-17 17:25:50 +000073#include "llvm/Target/TargetSelect.h"
Douglas Gregor26df2f02009-04-02 19:05:20 +000074#include <cstdlib>
Douglas Gregor44cf08e2009-05-03 03:52:38 +000075#if HAVE_SYS_TYPES_H
Douglas Gregor68a0d782009-05-02 00:03:46 +000076# include <sys/types.h>
77#endif
Douglas Gregor26df2f02009-04-02 19:05:20 +000078
Reid Spencer5f016e22007-07-11 17:01:13 +000079using namespace clang;
80
81//===----------------------------------------------------------------------===//
Douglas Gregor26df2f02009-04-02 19:05:20 +000082// Source Location Parser
83//===----------------------------------------------------------------------===//
84
Argyrios Kyrtzidis34d25d82009-06-23 22:01:39 +000085static bool ResolveParsedLocation(ParsedSourceLocation &ParsedLoc,
86 FileManager &FileMgr,
87 RequestedSourceLocation &Result) {
88 const FileEntry *File = FileMgr.getFile(ParsedLoc.FileName);
Douglas Gregor26df2f02009-04-02 19:05:20 +000089 if (!File)
90 return true;
91
92 Result.File = File;
Argyrios Kyrtzidis34d25d82009-06-23 22:01:39 +000093 Result.Line = ParsedLoc.Line;
94 Result.Column = ParsedLoc.Column;
Douglas Gregor26df2f02009-04-02 19:05:20 +000095 return false;
96}
97
Douglas Gregor26df2f02009-04-02 19:05:20 +000098//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +000099// Global options.
100//===----------------------------------------------------------------------===//
101
Chris Lattner47099742009-02-18 01:51:21 +0000102/// ClangFrontendTimer - The front-end activities should charge time to it with
103/// TimeRegion. The -ftime-report option controls whether this will do
104/// anything.
105llvm::Timer *ClangFrontendTimer = 0;
106
Daniel Dunbard3db4012008-10-16 16:54:18 +0000107static bool HadErrors = false;
Daniel Dunbarb0adbba2008-10-04 23:42:49 +0000108
Reid Spencer5f016e22007-07-11 17:01:13 +0000109static llvm::cl::opt<bool>
110Verbose("v", llvm::cl::desc("Enable verbose output"));
111static llvm::cl::opt<bool>
Mike Stump1eb44332009-09-09 15:08:12 +0000112Stats("print-stats",
Nate Begemanaabbb122007-12-30 01:38:50 +0000113 llvm::cl::desc("Print performance metrics and statistics"));
Daniel Dunbard3db4012008-10-16 16:54:18 +0000114static llvm::cl::opt<bool>
115DisableFree("disable-free",
116 llvm::cl::desc("Disable freeing of memory on exit"),
117 llvm::cl::init(false));
Daniel Dunbar57cbfc02009-04-27 21:19:07 +0000118static llvm::cl::opt<bool>
Mike Stump1eb44332009-09-09 15:08:12 +0000119EmptyInputOnly("empty-input-only",
Daniel Dunbar57cbfc02009-04-27 21:19:07 +0000120 llvm::cl::desc("Force running on an empty input file"));
Reid Spencer5f016e22007-07-11 17:01:13 +0000121
122enum ProgActions {
Steve Naroffb29b4272008-04-14 22:03:09 +0000123 RewriteObjC, // ObjC->C Rewriter.
Steve Naroff13188952008-09-18 14:10:13 +0000124 RewriteBlocks, // ObjC->C Rewriter for Blocks.
Chris Lattnerb57e3d42008-05-08 06:52:13 +0000125 RewriteMacros, // Expand macros but not #includes.
Chris Lattnerb13c5ee2008-10-12 05:29:20 +0000126 RewriteTest, // Rewriter playground
Douglas Gregor558cb562009-04-02 01:08:08 +0000127 FixIt, // Fix-It Rewriter
Ted Kremenek13e479b2008-03-19 07:53:42 +0000128 HTMLTest, // HTML displayer testing stuff.
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000129 EmitAssembly, // Emit a .s file.
Reid Spencer5f016e22007-07-11 17:01:13 +0000130 EmitLLVM, // Emit a .ll file.
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +0000131 EmitBC, // Emit a .bc file.
Mike Stump1eb44332009-09-09 15:08:12 +0000132 EmitLLVMOnly, // Generate LLVM IR, but do not
Ted Kremenek6a340832008-03-18 21:19:49 +0000133 EmitHTML, // Translate input source into HTML.
Chris Lattner3b427b32007-10-11 00:18:28 +0000134 ASTPrint, // Parse ASTs and print them.
Douglas Gregoree75c052009-05-21 20:55:50 +0000135 ASTPrintXML, // Parse ASTs and print them in XML.
Chris Lattner3b427b32007-10-11 00:18:28 +0000136 ASTDump, // Parse ASTs and dump them.
137 ASTView, // Parse ASTs and view them in Graphviz.
Zhongxing Xu2d75d6f2009-01-13 01:29:24 +0000138 PrintDeclContext, // Print DeclContext and their Decls.
Reid Spencer5f016e22007-07-11 17:01:13 +0000139 ParsePrintCallbacks, // Parse and print each callback.
140 ParseSyntaxOnly, // Parse and perform semantic analysis.
141 ParseNoop, // Parse with noop callbacks.
142 RunPreprocessorOnly, // Just lex, no output.
143 PrintPreprocessedInput, // -E mode.
Chris Lattnerc106c102008-10-12 05:03:36 +0000144 DumpTokens, // Dump out preprocessed tokens.
145 DumpRawTokens, // Dump out raw tokens.
Mike Stump1eb44332009-09-09 15:08:12 +0000146 RunAnalysis, // Run one or more source code analyses.
Douglas Gregorbf1bd6e2009-04-02 23:43:50 +0000147 GeneratePTH, // Generate pre-tokenized header.
Douglas Gregor2cf26342009-04-09 22:27:44 +0000148 GeneratePCH, // Generate pre-compiled header.
Ted Kremenek7cae2f62008-10-23 23:36:29 +0000149 InheritanceView // View C++ inheritance for a specified class.
Reid Spencer5f016e22007-07-11 17:01:13 +0000150};
151
Mike Stump1eb44332009-09-09 15:08:12 +0000152static llvm::cl::opt<ProgActions>
Reid Spencer5f016e22007-07-11 17:01:13 +0000153ProgAction(llvm::cl::desc("Choose output type:"), llvm::cl::ZeroOrMore,
154 llvm::cl::init(ParseSyntaxOnly),
155 llvm::cl::values(
156 clEnumValN(RunPreprocessorOnly, "Eonly",
157 "Just run preprocessor, no output (for timings)"),
158 clEnumValN(PrintPreprocessedInput, "E",
159 "Run preprocessor, emit preprocessed file"),
Chris Lattnerc106c102008-10-12 05:03:36 +0000160 clEnumValN(DumpRawTokens, "dump-raw-tokens",
161 "Lex file in raw mode and dump raw tokens"),
Daniel Dunbard4270232009-01-20 23:17:32 +0000162 clEnumValN(RunAnalysis, "analyze",
163 "Run static analysis engine"),
Chris Lattnerc106c102008-10-12 05:03:36 +0000164 clEnumValN(DumpTokens, "dump-tokens",
Reid Spencer5f016e22007-07-11 17:01:13 +0000165 "Run preprocessor, dump internal rep of tokens"),
166 clEnumValN(ParseNoop, "parse-noop",
167 "Run parser with noop callbacks (for timings)"),
168 clEnumValN(ParseSyntaxOnly, "fsyntax-only",
169 "Run parser and perform semantic analysis"),
170 clEnumValN(ParsePrintCallbacks, "parse-print-callbacks",
171 "Run parser and print each callback invoked"),
Ted Kremenek6a340832008-03-18 21:19:49 +0000172 clEnumValN(EmitHTML, "emit-html",
173 "Output input source as HTML"),
Chris Lattner3b427b32007-10-11 00:18:28 +0000174 clEnumValN(ASTPrint, "ast-print",
175 "Build ASTs and then pretty-print them"),
Douglas Gregoree75c052009-05-21 20:55:50 +0000176 clEnumValN(ASTPrintXML, "ast-print-xml",
177 "Build ASTs and then print them in XML format"),
Chris Lattner3b427b32007-10-11 00:18:28 +0000178 clEnumValN(ASTDump, "ast-dump",
179 "Build ASTs and then debug dump them"),
Chris Lattnerea254db2007-10-11 00:37:43 +0000180 clEnumValN(ASTView, "ast-view",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000181 "Build ASTs and view them with GraphViz"),
Zhongxing Xu2d75d6f2009-01-13 01:29:24 +0000182 clEnumValN(PrintDeclContext, "print-decl-contexts",
Ted Kremenek08478eb2009-04-01 00:23:28 +0000183 "Print DeclContexts and their Decls"),
Douglas Gregorbf1bd6e2009-04-02 23:43:50 +0000184 clEnumValN(GeneratePTH, "emit-pth",
Ted Kremenek08478eb2009-04-01 00:23:28 +0000185 "Generate pre-tokenized header file"),
Douglas Gregor2cf26342009-04-09 22:27:44 +0000186 clEnumValN(GeneratePCH, "emit-pch",
187 "Generate pre-compiled header file"),
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000188 clEnumValN(EmitAssembly, "S",
189 "Emit native assembly code"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000190 clEnumValN(EmitLLVM, "emit-llvm",
Ted Kremenek27b07c52007-09-06 21:26:58 +0000191 "Build ASTs then convert to LLVM, emit .ll file"),
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +0000192 clEnumValN(EmitBC, "emit-llvm-bc",
193 "Build ASTs then convert to LLVM, emit .bc file"),
Daniel Dunbare8e26002009-02-26 22:39:37 +0000194 clEnumValN(EmitLLVMOnly, "emit-llvm-only",
195 "Build ASTs and convert to LLVM, discarding output"),
Chris Lattnerb13c5ee2008-10-12 05:29:20 +0000196 clEnumValN(RewriteTest, "rewrite-test",
197 "Rewriter playground"),
Steve Naroffb29b4272008-04-14 22:03:09 +0000198 clEnumValN(RewriteObjC, "rewrite-objc",
Chris Lattnerb57e3d42008-05-08 06:52:13 +0000199 "Rewrite ObjC into C (code rewriter example)"),
200 clEnumValN(RewriteMacros, "rewrite-macros",
201 "Expand macros without full preprocessing"),
Steve Naroff13188952008-09-18 14:10:13 +0000202 clEnumValN(RewriteBlocks, "rewrite-blocks",
203 "Rewrite Blocks to C"),
Douglas Gregor558cb562009-04-02 01:08:08 +0000204 clEnumValN(FixIt, "fixit",
205 "Apply fix-it advice to the input source"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000206 clEnumValEnd));
207
Ted Kremenekccc76472007-12-19 19:47:59 +0000208
209static llvm::cl::opt<std::string>
210OutputFile("o",
Ted Kremenek50b56412007-12-19 19:50:41 +0000211 llvm::cl::value_desc("path"),
Douglas Gregor370187c2009-04-22 21:45:53 +0000212 llvm::cl::desc("Specify output file"));
Ted Kremenek55af98c2008-04-14 18:40:58 +0000213
Ted Kremenekc2e72992008-12-02 19:57:31 +0000214
215//===----------------------------------------------------------------------===//
216// PTH.
217//===----------------------------------------------------------------------===//
218
219static llvm::cl::opt<std::string>
220TokenCache("token-cache", llvm::cl::value_desc("path"),
221 llvm::cl::desc("Use specified token cache file"));
222
Sanjiv Guptae8b9f5b2008-05-08 08:54:20 +0000223//===----------------------------------------------------------------------===//
Ted Kremenek55af98c2008-04-14 18:40:58 +0000224// Diagnostic Options
225//===----------------------------------------------------------------------===//
226
Ted Kremenek41193e42007-09-26 19:42:19 +0000227static llvm::cl::opt<bool>
228VerifyDiagnostics("verify",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000229 llvm::cl::desc("Verify emitted diagnostics and warnings"));
Ted Kremenek41193e42007-09-26 19:42:19 +0000230
Ted Kremenek88f5cde2008-03-27 06:17:42 +0000231static llvm::cl::opt<std::string>
232HTMLDiag("html-diags",
233 llvm::cl::desc("Generate HTML to report diagnostics"),
234 llvm::cl::value_desc("HTML directory"));
235
Nico Weberfd54ebc2008-08-05 23:33:20 +0000236static llvm::cl::opt<bool>
237NoShowColumn("fno-show-column",
238 llvm::cl::desc("Do not include column number on diagnostics"));
239
240static llvm::cl::opt<bool>
Chris Lattner65f5e642009-01-30 19:01:41 +0000241NoShowLocation("fno-show-source-location",
242 llvm::cl::desc("Do not include source location information with"
243 " diagnostics"));
244
245static llvm::cl::opt<bool>
Nico Weberfd54ebc2008-08-05 23:33:20 +0000246NoCaretDiagnostics("fno-caret-diagnostics",
247 llvm::cl::desc("Do not include source line and caret with"
248 " diagnostics"));
249
Chris Lattner1fbee5d2009-03-13 01:08:23 +0000250static llvm::cl::opt<bool>
Chris Lattneraa5bf2e2009-04-19 07:44:08 +0000251NoDiagnosticsFixIt("fno-diagnostics-fixit-info",
252 llvm::cl::desc("Do not include fixit information in"
253 " diagnostics"));
254
255static llvm::cl::opt<bool>
Chris Lattner182e0922009-04-21 05:34:31 +0000256PrintSourceRangeInfo("fdiagnostics-print-source-range-info",
257 llvm::cl::desc("Print source range spans in numeric form"));
258
Chris Lattnerd51d74a2009-04-16 05:44:38 +0000259static llvm::cl::opt<bool>
260PrintDiagnosticOption("fdiagnostics-show-option",
261 llvm::cl::desc("Print diagnostic name with mappable diagnostics"));
Nico Weberfd54ebc2008-08-05 23:33:20 +0000262
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000263static llvm::cl::opt<unsigned>
264MessageLength("fmessage-length",
Mike Stump1eb44332009-09-09 15:08:12 +0000265 llvm::cl::desc("Format message diagnostics so that they fit "
266 "within N columns or fewer, when possible."),
267 llvm::cl::value_desc("N"));
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000268
Torok Edwin603fca72009-06-04 07:18:23 +0000269static llvm::cl::opt<bool>
Torok Edwina46c71a2009-06-04 07:27:53 +0000270NoColorDiagnostic("fno-color-diagnostics",
Mike Stump1eb44332009-09-09 15:08:12 +0000271 llvm::cl::desc("Don't use colors when showing diagnostics "
Torok Edwin603fca72009-06-04 07:18:23 +0000272 "(automatically turned off if output is not a "
273 "terminal)."));
Reid Spencer5f016e22007-07-11 17:01:13 +0000274//===----------------------------------------------------------------------===//
Ted Kremenek7cae2f62008-10-23 23:36:29 +0000275// C++ Visualization.
276//===----------------------------------------------------------------------===//
277
278static llvm::cl::opt<std::string>
279InheritanceViewCls("cxx-inheritance-view",
280 llvm::cl::value_desc("class name"),
Daniel Dunbard77b2512009-01-14 18:56:36 +0000281 llvm::cl::desc("View C++ inheritance for a specified class"));
Ted Kremenek7cae2f62008-10-23 23:36:29 +0000282
283//===----------------------------------------------------------------------===//
Douglas Gregor3573c0c2009-02-14 20:49:29 +0000284// Builtin Options
285//===----------------------------------------------------------------------===//
Chris Lattnerb2509e12009-02-18 01:12:43 +0000286
287static llvm::cl::opt<bool>
288TimeReport("ftime-report",
289 llvm::cl::desc("Print the amount of time each "
290 "phase of compilation takes"));
291
Douglas Gregor3573c0c2009-02-14 20:49:29 +0000292static llvm::cl::opt<bool>
293Freestanding("ffreestanding",
Daniel Dunbaref2abfe2009-02-16 22:43:43 +0000294 llvm::cl::desc("Assert that the compilation takes place in a "
Douglas Gregor3573c0c2009-02-14 20:49:29 +0000295 "freestanding environment"));
296
Daniel Dunbaref2abfe2009-02-16 22:43:43 +0000297static llvm::cl::opt<bool>
Daniel Dunbar48d1ef72009-04-07 21:16:11 +0000298AllowBuiltins("fbuiltin", llvm::cl::init(true),
299 llvm::cl::desc("Disable implicit builtin knowledge of functions"));
Chris Lattner7644f072009-03-13 22:38:49 +0000300
301
302static llvm::cl::opt<bool>
Daniel Dunbar48d1ef72009-04-07 21:16:11 +0000303MathErrno("fmath-errno", llvm::cl::init(true),
304 llvm::cl::desc("Require math functions to respect errno"));
Daniel Dunbaref2abfe2009-02-16 22:43:43 +0000305
Douglas Gregor3573c0c2009-02-14 20:49:29 +0000306//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +0000307// Language Options
308//===----------------------------------------------------------------------===//
309
310enum LangKind {
311 langkind_unspecified,
312 langkind_c,
313 langkind_c_cpp,
Chris Lattnera778d7d2008-10-22 17:29:21 +0000314 langkind_asm_cpp,
Reid Spencer5f016e22007-07-11 17:01:13 +0000315 langkind_cxx,
316 langkind_cxx_cpp,
317 langkind_objc,
318 langkind_objc_cpp,
319 langkind_objcxx,
Nate Begeman4e3629e2009-06-25 22:43:10 +0000320 langkind_objcxx_cpp,
321 langkind_ocl
Reid Spencer5f016e22007-07-11 17:01:13 +0000322};
323
Reid Spencer5f016e22007-07-11 17:01:13 +0000324static llvm::cl::opt<LangKind>
325BaseLang("x", llvm::cl::desc("Base language to compile"),
326 llvm::cl::init(langkind_unspecified),
327 llvm::cl::values(clEnumValN(langkind_c, "c", "C"),
Nate Begeman4e3629e2009-06-25 22:43:10 +0000328 clEnumValN(langkind_ocl, "cl", "OpenCL C"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000329 clEnumValN(langkind_cxx, "c++", "C++"),
330 clEnumValN(langkind_objc, "objective-c", "Objective C"),
331 clEnumValN(langkind_objcxx,"objective-c++","Objective C++"),
Daniel Dunbard2ea3862009-01-29 23:50:47 +0000332 clEnumValN(langkind_c_cpp, "cpp-output",
Reid Spencer5f016e22007-07-11 17:01:13 +0000333 "Preprocessed C"),
Chris Lattnera778d7d2008-10-22 17:29:21 +0000334 clEnumValN(langkind_asm_cpp, "assembler-with-cpp",
335 "Preprocessed asm"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000336 clEnumValN(langkind_cxx_cpp, "c++-cpp-output",
Chris Lattnerc76d8072009-02-06 06:19:20 +0000337 "Preprocessed C++"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000338 clEnumValN(langkind_objc_cpp, "objective-c-cpp-output",
339 "Preprocessed Objective C"),
Chris Lattnerc76d8072009-02-06 06:19:20 +0000340 clEnumValN(langkind_objcxx_cpp, "objective-c++-cpp-output",
Reid Spencer5f016e22007-07-11 17:01:13 +0000341 "Preprocessed Objective C++"),
Daniel Dunbar0b5b0da2009-04-01 05:09:09 +0000342 clEnumValN(langkind_c, "c-header",
343 "C header"),
344 clEnumValN(langkind_objc, "objective-c-header",
345 "Objective-C header"),
346 clEnumValN(langkind_cxx, "c++-header",
347 "C++ header"),
348 clEnumValN(langkind_objcxx, "objective-c++-header",
349 "Objective-C++ header"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000350 clEnumValEnd));
351
352static llvm::cl::opt<bool>
353LangObjC("ObjC", llvm::cl::desc("Set base language to Objective-C"),
354 llvm::cl::Hidden);
355static llvm::cl::opt<bool>
356LangObjCXX("ObjC++", llvm::cl::desc("Set base language to Objective-C++"),
357 llvm::cl::Hidden);
358
Chris Lattner2c78b872009-04-14 23:22:57 +0000359static llvm::cl::opt<bool>
360ObjCExclusiveGC("fobjc-gc-only",
361 llvm::cl::desc("Use GC exclusively for Objective-C related "
362 "memory management"));
363
David Chisnall8a5a9aa2009-08-31 16:41:57 +0000364static llvm::cl::opt<std::string>
365ObjCConstantStringClass("fconstant-string-class",
366 llvm::cl::value_desc("class name"),
367 llvm::cl::desc("Specify the class to use for constant "
368 "Objective-C string objects."));
369
Chris Lattner2c78b872009-04-14 23:22:57 +0000370static llvm::cl::opt<bool>
371ObjCEnableGC("fobjc-gc",
372 llvm::cl::desc("Enable Objective-C garbage collection"));
373
Fariborz Jahanian448f5e62009-04-17 03:04:15 +0000374static llvm::cl::opt<bool>
375ObjCEnableGCBitmapPrint("print-ivar-layout",
376 llvm::cl::desc("Enable Objective-C Ivar layout bitmap print trace"));
377
Chris Lattner2c78b872009-04-14 23:22:57 +0000378static llvm::cl::opt<LangOptions::VisibilityMode>
379SymbolVisibility("fvisibility",
380 llvm::cl::desc("Set the default symbol visibility:"),
381 llvm::cl::init(LangOptions::Default),
382 llvm::cl::values(clEnumValN(LangOptions::Default, "default",
383 "Use default symbol visibility"),
384 clEnumValN(LangOptions::Hidden, "hidden",
385 "Use hidden symbol visibility"),
386 clEnumValN(LangOptions::Protected,"protected",
387 "Use protected symbol visibility"),
388 clEnumValEnd));
389
390static llvm::cl::opt<bool>
391OverflowChecking("ftrapv",
392 llvm::cl::desc("Trap on integer overflow"),
393 llvm::cl::init(false));
394
Fariborz Jahanian34e65772009-05-22 20:17:16 +0000395static llvm::cl::opt<bool>
Nate Begeman2ef13e52009-08-10 23:49:36 +0000396AltiVec("faltivec", llvm::cl::desc("Enable AltiVec vector initializer syntax"),
397 llvm::cl::init(false));
398
399static llvm::cl::opt<bool>
Daniel Dunbar5345c392009-09-03 04:54:28 +0000400PThread("pthread", llvm::cl::desc("Support POSIX threads in generated code"),
401 llvm::cl::init(false));
402
Ted Kremenek8904f152007-12-05 23:49:08 +0000403/// InitializeBaseLanguage - Handle the -x foo options.
404static void InitializeBaseLanguage() {
405 if (LangObjC)
406 BaseLang = langkind_objc;
407 else if (LangObjCXX)
408 BaseLang = langkind_objcxx;
409}
410
411static LangKind GetLanguage(const std::string &Filename) {
412 if (BaseLang != langkind_unspecified)
413 return BaseLang;
Mike Stump1eb44332009-09-09 15:08:12 +0000414
Ted Kremenek8904f152007-12-05 23:49:08 +0000415 std::string::size_type DotPos = Filename.rfind('.');
416
417 if (DotPos == std::string::npos) {
418 BaseLang = langkind_c; // Default to C if no extension.
Chris Lattner9b2f6c42008-01-04 19:12:28 +0000419 return langkind_c;
Reid Spencer5f016e22007-07-11 17:01:13 +0000420 }
Mike Stump1eb44332009-09-09 15:08:12 +0000421
Ted Kremenek8904f152007-12-05 23:49:08 +0000422 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
423 // C header: .h
424 // C++ header: .hh or .H;
425 // assembler no preprocessing: .s
426 // assembler: .S
427 if (Ext == "c")
428 return langkind_c;
Chris Lattnerd9cd4c92009-03-23 16:24:37 +0000429 else if (Ext == "S" ||
430 // If the compiler is run on a .s file, preprocess it as .S
431 Ext == "s")
Chris Lattnera778d7d2008-10-22 17:29:21 +0000432 return langkind_asm_cpp;
Ted Kremenek8904f152007-12-05 23:49:08 +0000433 else if (Ext == "i")
434 return langkind_c_cpp;
435 else if (Ext == "ii")
436 return langkind_cxx_cpp;
437 else if (Ext == "m")
438 return langkind_objc;
439 else if (Ext == "mi")
440 return langkind_objc_cpp;
441 else if (Ext == "mm" || Ext == "M")
442 return langkind_objcxx;
443 else if (Ext == "mii")
444 return langkind_objcxx_cpp;
445 else if (Ext == "C" || Ext == "cc" || Ext == "cpp" || Ext == "CPP" ||
446 Ext == "c++" || Ext == "cp" || Ext == "cxx")
447 return langkind_cxx;
Nate Begeman4e3629e2009-06-25 22:43:10 +0000448 else if (Ext == "cl")
449 return langkind_ocl;
Ted Kremenek8904f152007-12-05 23:49:08 +0000450 else
451 return langkind_c;
452}
453
454
Ted Kremenek85888962008-10-21 00:54:44 +0000455static void InitializeCOptions(LangOptions &Options) {
456 // Do nothing.
457}
458
459static void InitializeObjCOptions(LangOptions &Options) {
460 Options.ObjC1 = Options.ObjC2 = 1;
461}
Mike Stump1eb44332009-09-09 15:08:12 +0000462
Ted Kremenek85888962008-10-21 00:54:44 +0000463
Daniel Dunbar0b5b0da2009-04-01 05:09:09 +0000464static void InitializeLangOptions(LangOptions &Options, LangKind LK){
Reid Spencer5f016e22007-07-11 17:01:13 +0000465 // FIXME: implement -fpreprocessed mode.
466 bool NoPreprocess = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000467
Ted Kremenek8904f152007-12-05 23:49:08 +0000468 switch (LK) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000469 default: assert(0 && "Unknown language kind!");
Chris Lattnera778d7d2008-10-22 17:29:21 +0000470 case langkind_asm_cpp:
Daniel Dunbarc1571452008-12-01 18:55:22 +0000471 Options.AsmPreprocessor = 1;
Chris Lattnera778d7d2008-10-22 17:29:21 +0000472 // FALLTHROUGH
Reid Spencer5f016e22007-07-11 17:01:13 +0000473 case langkind_c_cpp:
474 NoPreprocess = true;
475 // FALLTHROUGH
476 case langkind_c:
Ted Kremenek85888962008-10-21 00:54:44 +0000477 InitializeCOptions(Options);
Reid Spencer5f016e22007-07-11 17:01:13 +0000478 break;
479 case langkind_cxx_cpp:
480 NoPreprocess = true;
481 // FALLTHROUGH
482 case langkind_cxx:
483 Options.CPlusPlus = 1;
484 break;
485 case langkind_objc_cpp:
486 NoPreprocess = true;
487 // FALLTHROUGH
488 case langkind_objc:
Ted Kremenek85888962008-10-21 00:54:44 +0000489 InitializeObjCOptions(Options);
Reid Spencer5f016e22007-07-11 17:01:13 +0000490 break;
491 case langkind_objcxx_cpp:
492 NoPreprocess = true;
493 // FALLTHROUGH
494 case langkind_objcxx:
495 Options.ObjC1 = Options.ObjC2 = 1;
496 Options.CPlusPlus = 1;
497 break;
Nate Begeman4e3629e2009-06-25 22:43:10 +0000498 case langkind_ocl:
499 Options.OpenCL = 1;
500 Options.AltiVec = 1;
501 Options.CXXOperatorNames = 1;
502 Options.LaxVectorConversions = 1;
503 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000504 }
Mike Stump1eb44332009-09-09 15:08:12 +0000505
Chris Lattner2c78b872009-04-14 23:22:57 +0000506 if (ObjCExclusiveGC)
507 Options.setGCMode(LangOptions::GCOnly);
508 else if (ObjCEnableGC)
509 Options.setGCMode(LangOptions::HybridGC);
Mike Stump1eb44332009-09-09 15:08:12 +0000510
Fariborz Jahanian448f5e62009-04-17 03:04:15 +0000511 if (ObjCEnableGCBitmapPrint)
512 Options.ObjCGCBitmapPrint = 1;
Mike Stump1eb44332009-09-09 15:08:12 +0000513
Nate Begeman2ef13e52009-08-10 23:49:36 +0000514 if (AltiVec)
515 Options.AltiVec = 1;
Daniel Dunbar5345c392009-09-03 04:54:28 +0000516
517 if (PThread)
518 Options.POSIXThreads = 1;
Mike Stump1eb44332009-09-09 15:08:12 +0000519
Chris Lattner2c78b872009-04-14 23:22:57 +0000520 Options.setVisibilityMode(SymbolVisibility);
521 Options.OverflowChecking = OverflowChecking;
Reid Spencer5f016e22007-07-11 17:01:13 +0000522}
523
524/// LangStds - Language standards we support.
525enum LangStds {
Mike Stump1eb44332009-09-09 15:08:12 +0000526 lang_unspecified,
Reid Spencer5f016e22007-07-11 17:01:13 +0000527 lang_c89, lang_c94, lang_c99,
Ted Kremenekea644d82008-09-03 21:22:16 +0000528 lang_gnu_START,
529 lang_gnu89 = lang_gnu_START, lang_gnu99,
Chris Lattnerd4b80f12007-07-16 04:18:29 +0000530 lang_cxx98, lang_gnucxx98,
531 lang_cxx0x, lang_gnucxx0x
Reid Spencer5f016e22007-07-11 17:01:13 +0000532};
533
534static llvm::cl::opt<LangStds>
535LangStd("std", llvm::cl::desc("Language standard to compile for"),
536 llvm::cl::init(lang_unspecified),
537 llvm::cl::values(clEnumValN(lang_c89, "c89", "ISO C 1990"),
538 clEnumValN(lang_c89, "c90", "ISO C 1990"),
539 clEnumValN(lang_c89, "iso9899:1990", "ISO C 1990"),
540 clEnumValN(lang_c94, "iso9899:199409",
541 "ISO C 1990 with amendment 1"),
542 clEnumValN(lang_c99, "c99", "ISO C 1999"),
Chris Lattner50748f42009-04-06 17:17:55 +0000543 clEnumValN(lang_c99, "c9x", "ISO C 1999"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000544 clEnumValN(lang_c99, "iso9899:1999", "ISO C 1999"),
Chris Lattner50748f42009-04-06 17:17:55 +0000545 clEnumValN(lang_c99, "iso9899:199x", "ISO C 1999"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000546 clEnumValN(lang_gnu89, "gnu89",
Gabor Greif10b26142009-02-28 09:22:15 +0000547 "ISO C 1990 with GNU extensions"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000548 clEnumValN(lang_gnu99, "gnu99",
Gabor Greif10b26142009-02-28 09:22:15 +0000549 "ISO C 1999 with GNU extensions (default for C)"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000550 clEnumValN(lang_gnu99, "gnu9x",
551 "ISO C 1999 with GNU extensions"),
552 clEnumValN(lang_cxx98, "c++98",
553 "ISO C++ 1998 with amendments"),
554 clEnumValN(lang_gnucxx98, "gnu++98",
555 "ISO C++ 1998 with amendments and GNU "
556 "extensions (default for C++)"),
Chris Lattnerd4b80f12007-07-16 04:18:29 +0000557 clEnumValN(lang_cxx0x, "c++0x",
558 "Upcoming ISO C++ 200x with amendments"),
559 clEnumValN(lang_gnucxx0x, "gnu++0x",
560 "Upcoming ISO C++ 200x with amendments and GNU "
Gabor Greif5f8d1db2009-03-11 23:07:18 +0000561 "extensions"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000562 clEnumValEnd));
563
564static llvm::cl::opt<bool>
565NoOperatorNames("fno-operator-names",
566 llvm::cl::desc("Do not treat C++ operator name keywords as "
567 "synonyms for operators"));
568
Anders Carlssonee98ac52007-10-15 02:50:23 +0000569static llvm::cl::opt<bool>
570PascalStrings("fpascal-strings",
571 llvm::cl::desc("Recognize and construct Pascal-style "
572 "string literals"));
Mike Stump1eb44332009-09-09 15:08:12 +0000573
Steve Naroffd62701b2008-02-07 03:50:06 +0000574static llvm::cl::opt<bool>
575MSExtensions("fms-extensions",
576 llvm::cl::desc("Accept some non-standard constructs used in "
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000577 "Microsoft header files "));
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000578
579static llvm::cl::opt<bool>
580WritableStrings("fwritable-strings",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000581 llvm::cl::desc("Store string literals as writable data"));
Anders Carlsson695dbb62007-11-30 04:21:22 +0000582
583static llvm::cl::opt<bool>
Anders Carlssonad53eff2009-01-30 23:26:40 +0000584NoLaxVectorConversions("fno-lax-vector-conversions",
Anders Carlssonb0f90cc2009-01-30 23:17:46 +0000585 llvm::cl::desc("Disallow implicit conversions between "
586 "vectors with a different number of "
587 "elements or different element types"));
Chris Lattnerae0ee032008-12-04 23:20:07 +0000588
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000589static llvm::cl::opt<bool>
Daniel Dunbar48d1ef72009-04-07 21:16:11 +0000590EnableBlocks("fblocks", llvm::cl::desc("enable the 'blocks' language feature"));
Mike Stumpa0f02aa2009-02-02 22:57:57 +0000591
592static llvm::cl::opt<bool>
Chris Lattner810f6d52009-03-13 17:38:01 +0000593EnableHeinousExtensions("fheinous-gnu-extensions",
594 llvm::cl::desc("enable GNU extensions that you really really shouldn't use"),
595 llvm::cl::ValueDisallowed, llvm::cl::Hidden);
596
597static llvm::cl::opt<bool>
Mike Stumpa0f02aa2009-02-02 22:57:57 +0000598ObjCNonFragileABI("fobjc-nonfragile-abi",
599 llvm::cl::desc("enable objective-c's nonfragile abi"));
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000600
Daniel Dunbard6884a02009-05-04 05:16:21 +0000601
602static llvm::cl::opt<bool>
Daniel Dunbard604c402009-02-04 21:19:06 +0000603EmitAllDecls("femit-all-decls",
604 llvm::cl::desc("Emit all declarations, even if unused"));
Ted Kremenek01d9dbf2008-04-29 04:37:03 +0000605
Daniel Dunbar6379a7a2008-08-11 17:36:14 +0000606static llvm::cl::opt<bool>
607Exceptions("fexceptions",
Chris Lattnerf5db8f82009-04-19 07:00:02 +0000608 llvm::cl::desc("Enable support for exception handling"));
Daniel Dunbar6379a7a2008-08-11 17:36:14 +0000609
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000610static llvm::cl::opt<bool>
Mike Stump738f8c22009-07-31 23:15:31 +0000611Rtti("frtti", llvm::cl::init(true),
612 llvm::cl::desc("Enable generation of rtti information"));
613
614static llvm::cl::opt<bool>
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000615GNURuntime("fgnu-runtime",
Ted Kremenek85888962008-10-21 00:54:44 +0000616 llvm::cl::desc("Generate output compatible with the standard GNU "
Chris Lattnerf5db8f82009-04-19 07:00:02 +0000617 "Objective-C runtime"));
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000618
619static llvm::cl::opt<bool>
620NeXTRuntime("fnext-runtime",
Ted Kremenek85888962008-10-21 00:54:44 +0000621 llvm::cl::desc("Generate output compatible with the NeXT "
Chris Lattnerf5db8f82009-04-19 07:00:02 +0000622 "runtime"));
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000623
Eli Friedmanc4757bd2009-06-05 07:12:17 +0000624static llvm::cl::opt<bool>
625CharIsSigned("fsigned-char",
626 llvm::cl::desc("Force char to be a signed/unsigned type"));
Ted Kremenekea644d82008-09-03 21:22:16 +0000627
628
629static llvm::cl::opt<bool>
Chris Lattnerf5db8f82009-04-19 07:00:02 +0000630Trigraphs("trigraphs", llvm::cl::desc("Process trigraph sequences"));
Ted Kremenekea644d82008-09-03 21:22:16 +0000631
Douglas Gregor26dce442009-03-10 00:06:19 +0000632static llvm::cl::opt<unsigned>
633TemplateDepth("ftemplate-depth", llvm::cl::init(99),
634 llvm::cl::desc("Maximum depth of recursive template "
635 "instantiation"));
Chris Lattnerf5db8f82009-04-19 07:00:02 +0000636static llvm::cl::opt<bool>
637DollarsInIdents("fdollars-in-identifiers",
638 llvm::cl::desc("Allow '$' in identifiers"));
Chris Lattner16167a62009-03-02 22:11:07 +0000639
Anders Carlsson4ca076f2009-04-06 17:37:10 +0000640
641static llvm::cl::opt<bool>
642OptSize("Os", llvm::cl::desc("Optimize for size"));
643
644static llvm::cl::opt<bool>
Mike Stump1eb44332009-09-09 15:08:12 +0000645DisableLLVMOptimizations("disable-llvm-optzns",
Daniel Dunbar877db382009-06-02 22:07:45 +0000646 llvm::cl::desc("Don't run LLVM optimization passes"));
647
648static llvm::cl::opt<bool>
Anders Carlsson4ca076f2009-04-06 17:37:10 +0000649NoCommon("fno-common",
650 llvm::cl::desc("Compile common globals like normal definitions"),
651 llvm::cl::ValueDisallowed);
652
Daniel Dunbarc9abc042009-04-08 05:11:16 +0000653static llvm::cl::opt<std::string>
654MainFileName("main-file-name",
655 llvm::cl::desc("Main file name to use for debug info"));
Anders Carlsson4ca076f2009-04-06 17:37:10 +0000656
Anders Carlssona33d9b42009-05-13 19:49:53 +0000657// FIXME: Also add an "-fno-access-control" option.
658static llvm::cl::opt<bool>
Mike Stump1eb44332009-09-09 15:08:12 +0000659AccessControl("faccess-control",
Anders Carlssona33d9b42009-05-13 19:49:53 +0000660 llvm::cl::desc("Enable C++ access control"));
661
Anders Carlsson92f58222009-08-22 22:30:33 +0000662static llvm::cl::opt<bool>
663NoElideConstructors("fno-elide-constructors",
664 llvm::cl::desc("Disable C++ copy constructor elision"));
665
Daniel Dunbar73b79592009-09-14 00:02:12 +0000666static llvm::cl::opt<std::string>
667TargetABI("target-abi",
668 llvm::cl::desc("Target a particular ABI type"));
669
Anders Carlsson92f58222009-08-22 22:30:33 +0000670
Anders Carlsson4ca076f2009-04-06 17:37:10 +0000671// It might be nice to add bounds to the CommandLine library directly.
672struct OptLevelParser : public llvm::cl::parser<unsigned> {
673 bool parse(llvm::cl::Option &O, const char *ArgName,
674 const std::string &Arg, unsigned &Val) {
675 if (llvm::cl::parser<unsigned>::parse(O, ArgName, Arg, Val))
676 return true;
Anders Carlsson4ca076f2009-04-06 17:37:10 +0000677 if (Val > 3)
Benjamin Kramer21fde992009-08-02 12:12:11 +0000678 return O.error("'" + Arg + "' invalid optimization level!");
Anders Carlsson4ca076f2009-04-06 17:37:10 +0000679 return false;
680 }
681};
682static llvm::cl::opt<unsigned, false, OptLevelParser>
683OptLevel("O", llvm::cl::Prefix,
684 llvm::cl::desc("Optimization level"),
685 llvm::cl::init(0));
686
Daniel Dunbar9fd0b1f2009-04-08 03:03:23 +0000687static llvm::cl::opt<unsigned>
Daniel Dunbar3bbc7532009-04-08 18:03:55 +0000688PICLevel("pic-level", llvm::cl::desc("Value for __PIC__"));
689
690static llvm::cl::opt<bool>
691StaticDefine("static-define", llvm::cl::desc("Should __STATIC__ be defined"));
Daniel Dunbar9fd0b1f2009-04-08 03:03:23 +0000692
Bill Wendling45483f72009-06-28 07:36:13 +0000693static llvm::cl::opt<int>
694StackProtector("stack-protector",
695 llvm::cl::desc("Enable stack protectors"),
696 llvm::cl::init(-1));
697
Daniel Dunbardcb4a1a2008-08-23 08:43:39 +0000698static void InitializeLanguageStandard(LangOptions &Options, LangKind LK,
Daniel Dunbar868bd0a2009-05-06 03:16:41 +0000699 TargetInfo *Target,
700 const llvm::StringMap<bool> &Features) {
Chris Lattner8fc4dfb2008-12-04 22:54:33 +0000701 // Allow the target to set the default the langauge options as it sees fit.
702 Target->getDefaultLangOptions(Options);
Daniel Dunbar868bd0a2009-05-06 03:16:41 +0000703
704 // Pass the map of target features to the target for validation and
705 // processing.
706 Target->HandleTargetFeatures(Features);
Mike Stump1eb44332009-09-09 15:08:12 +0000707
Reid Spencer5f016e22007-07-11 17:01:13 +0000708 if (LangStd == lang_unspecified) {
709 // Based on the base language, pick one.
Ted Kremenek8904f152007-12-05 23:49:08 +0000710 switch (LK) {
Ted Kremenekf2a17b12009-03-19 19:02:20 +0000711 case lang_unspecified: assert(0 && "Unknown base language");
Nate Begeman4e3629e2009-06-25 22:43:10 +0000712 case langkind_ocl:
713 LangStd = lang_c99;
714 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000715 case langkind_c:
Chris Lattnera778d7d2008-10-22 17:29:21 +0000716 case langkind_asm_cpp:
Reid Spencer5f016e22007-07-11 17:01:13 +0000717 case langkind_c_cpp:
718 case langkind_objc:
719 case langkind_objc_cpp:
720 LangStd = lang_gnu99;
721 break;
722 case langkind_cxx:
723 case langkind_cxx_cpp:
724 case langkind_objcxx:
725 case langkind_objcxx_cpp:
726 LangStd = lang_gnucxx98;
727 break;
728 }
729 }
Mike Stump1eb44332009-09-09 15:08:12 +0000730
Reid Spencer5f016e22007-07-11 17:01:13 +0000731 switch (LangStd) {
732 default: assert(0 && "Unknown language standard!");
733
734 // Fall through from newer standards to older ones. This isn't really right.
735 // FIXME: Enable specifically the right features based on the language stds.
Chris Lattnerd4b80f12007-07-16 04:18:29 +0000736 case lang_gnucxx0x:
737 case lang_cxx0x:
738 Options.CPlusPlus0x = 1;
739 // FALL THROUGH
Reid Spencer5f016e22007-07-11 17:01:13 +0000740 case lang_gnucxx98:
741 case lang_cxx98:
742 Options.CPlusPlus = 1;
743 Options.CXXOperatorNames = !NoOperatorNames;
744 // FALL THROUGH.
745 case lang_gnu99:
746 case lang_c99:
Reid Spencer5f016e22007-07-11 17:01:13 +0000747 Options.C99 = 1;
748 Options.HexFloats = 1;
749 // FALL THROUGH.
750 case lang_gnu89:
751 Options.BCPLComment = 1; // Only for C99/C++.
752 // FALL THROUGH.
753 case lang_c94:
Chris Lattner3426b9b2008-02-25 04:01:39 +0000754 Options.Digraphs = 1; // C94, C99, C++.
755 // FALL THROUGH.
Reid Spencer5f016e22007-07-11 17:01:13 +0000756 case lang_c89:
757 break;
758 }
Argyrios Kyrtzidisd1465522008-09-11 04:21:06 +0000759
Chris Lattner7e9c90b2009-03-20 15:44:26 +0000760 // GNUMode - Set if we're in gnu99, gnu89, gnucxx98, etc.
761 Options.GNUMode = LangStd >= lang_gnu_START;
Mike Stump1eb44332009-09-09 15:08:12 +0000762
Argyrios Kyrtzidisd1465522008-09-11 04:21:06 +0000763 if (Options.CPlusPlus) {
764 Options.C99 = 0;
Eli Friedmanab24c8d2009-08-26 20:15:14 +0000765 Options.HexFloats = 0;
Argyrios Kyrtzidisd1465522008-09-11 04:21:06 +0000766 }
Mike Stump1eb44332009-09-09 15:08:12 +0000767
Chris Lattnerd658b562008-04-05 06:32:51 +0000768 if (LangStd == lang_c89 || LangStd == lang_c94 || LangStd == lang_gnu89)
769 Options.ImplicitInt = 1;
770 else
771 Options.ImplicitInt = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000772
Daniel Dunbard573d262009-04-07 22:13:21 +0000773 // Mimicing gcc's behavior, trigraphs are only enabled if -trigraphs
774 // is specified, or -std is set to a conforming mode.
Chris Lattner7e9c90b2009-03-20 15:44:26 +0000775 Options.Trigraphs = !Options.GNUMode;
Chris Lattner802db9b2008-12-05 00:10:44 +0000776 if (Trigraphs.getPosition())
Chris Lattner7e9c90b2009-03-20 15:44:26 +0000777 Options.Trigraphs = Trigraphs; // Command line option wins if specified.
Ted Kremenekea644d82008-09-03 21:22:16 +0000778
Chris Lattner802db9b2008-12-05 00:10:44 +0000779 // If in a conformant language mode (e.g. -std=c99) Blocks defaults to off
780 // even if they are normally on for the target. In GNU modes (e.g.
781 // -std=gnu99) the default for blocks depends on the target settings.
Anders Carlssone56f6ff2009-01-21 18:47:36 +0000782 // However, blocks are not turned off when compiling Obj-C or Obj-C++ code.
Chris Lattner7e9c90b2009-03-20 15:44:26 +0000783 if (!Options.ObjC1 && !Options.GNUMode)
Chris Lattner802db9b2008-12-05 00:10:44 +0000784 Options.Blocks = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000785
Chris Lattner01638a62009-04-19 07:06:52 +0000786 // Default to not accepting '$' in identifiers when preprocessing assembler,
787 // but do accept when preprocessing C. FIXME: these defaults are right for
788 // darwin, are they right everywhere?
789 Options.DollarIdents = LK != langkind_asm_cpp;
790 if (DollarsInIdents.getPosition()) // Explicit setting overrides default.
Chris Lattnerf5db8f82009-04-19 07:00:02 +0000791 Options.DollarIdents = DollarsInIdents;
Mike Stump1eb44332009-09-09 15:08:12 +0000792
Chris Lattnerae0ee032008-12-04 23:20:07 +0000793 if (PascalStrings.getPosition())
794 Options.PascalStrings = PascalStrings;
Eli Friedmanabc4e322009-06-08 06:11:14 +0000795 if (MSExtensions.getPosition())
796 Options.Microsoft = MSExtensions;
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000797 Options.WritableStrings = WritableStrings;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +0000798 if (NoLaxVectorConversions.getPosition())
799 Options.LaxVectorConversions = 0;
Daniel Dunbar6379a7a2008-08-11 17:36:14 +0000800 Options.Exceptions = Exceptions;
Mike Stump738f8c22009-07-31 23:15:31 +0000801 Options.Rtti = Rtti;
Mike Stumpa0f02aa2009-02-02 22:57:57 +0000802 if (EnableBlocks.getPosition())
Chris Lattnerae0ee032008-12-04 23:20:07 +0000803 Options.Blocks = EnableBlocks;
Eli Friedmanc4757bd2009-06-05 07:12:17 +0000804 if (CharIsSigned.getPosition())
805 Options.CharIsSigned = CharIsSigned;
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000806
Daniel Dunbar9f9768c2009-03-20 23:49:28 +0000807 if (!AllowBuiltins)
Chris Lattner7644f072009-03-13 22:38:49 +0000808 Options.NoBuiltin = 1;
Douglas Gregor3573c0c2009-02-14 20:49:29 +0000809 if (Freestanding)
Chris Lattner7644f072009-03-13 22:38:49 +0000810 Options.Freestanding = Options.NoBuiltin = 1;
Mike Stump1eb44332009-09-09 15:08:12 +0000811
Chris Lattner810f6d52009-03-13 17:38:01 +0000812 if (EnableHeinousExtensions)
813 Options.HeinousExtensions = 1;
Douglas Gregor3573c0c2009-02-14 20:49:29 +0000814
Anders Carlssona33d9b42009-05-13 19:49:53 +0000815 if (AccessControl)
816 Options.AccessControl = 1;
Mike Stump1eb44332009-09-09 15:08:12 +0000817
Anders Carlsson92f58222009-08-22 22:30:33 +0000818 Options.ElideConstructors = !NoElideConstructors;
Mike Stump1eb44332009-09-09 15:08:12 +0000819
Chris Lattnere4f21422009-06-30 01:26:17 +0000820 // OpenCL and C++ both have bool, true, false keywords.
821 Options.Bool = Options.OpenCL | Options.CPlusPlus;
Mike Stump1eb44332009-09-09 15:08:12 +0000822
Daniel Dunbaref2abfe2009-02-16 22:43:43 +0000823 Options.MathErrno = MathErrno;
824
Douglas Gregor26dce442009-03-10 00:06:19 +0000825 Options.InstantiationDepth = TemplateDepth;
826
Chris Lattner8fc4dfb2008-12-04 22:54:33 +0000827 // Override the default runtime if the user requested it.
828 if (NeXTRuntime)
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000829 Options.NeXTRuntime = 1;
Chris Lattner8fc4dfb2008-12-04 22:54:33 +0000830 else if (GNURuntime)
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000831 Options.NeXTRuntime = 0;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000832
David Chisnall8a5a9aa2009-08-31 16:41:57 +0000833 if (!ObjCConstantStringClass.empty())
834 Options.ObjCConstantStringClass = ObjCConstantStringClass.c_str();
835
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000836 if (ObjCNonFragileABI)
837 Options.ObjCNonFragileABI = 1;
Fariborz Jahanian34e65772009-05-22 20:17:16 +0000838
Daniel Dunbard604c402009-02-04 21:19:06 +0000839 if (EmitAllDecls)
840 Options.EmitAllDecls = 1;
Anders Carlsson4ca076f2009-04-06 17:37:10 +0000841
Daniel Dunbar3bbc7532009-04-08 18:03:55 +0000842 // The __OPTIMIZE_SIZE__ define is tied to -Oz, which we don't
843 // support.
844 Options.OptimizeSize = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000845
Anders Carlsson4ca076f2009-04-06 17:37:10 +0000846 // -Os implies -O2
Daniel Dunbar3bbc7532009-04-08 18:03:55 +0000847 if (OptSize || OptLevel)
Anders Carlsson4ca076f2009-04-06 17:37:10 +0000848 Options.Optimize = 1;
Daniel Dunbar9fd0b1f2009-04-08 03:03:23 +0000849
850 assert(PICLevel <= 2 && "Invalid value for -pic-level");
851 Options.PICLevel = PICLevel;
Daniel Dunbarc9abc042009-04-08 05:11:16 +0000852
Daniel Dunbar3bbc7532009-04-08 18:03:55 +0000853 Options.GNUInline = !Options.C99;
Mike Stump1eb44332009-09-09 15:08:12 +0000854 // FIXME: This is affected by other options (-fno-inline).
Daniel Dunbar3bbc7532009-04-08 18:03:55 +0000855 Options.NoInline = !OptSize && !OptLevel;
856
857 Options.Static = StaticDefine;
858
Bill Wendling4ebe3e42009-06-28 23:01:01 +0000859 switch (StackProtector) {
860 default:
861 assert(StackProtector <= 2 && "Invalid value for -stack-protector");
862 case -1: break;
863 case 0: Options.setStackProtectorMode(LangOptions::SSPOff); break;
864 case 1: Options.setStackProtectorMode(LangOptions::SSPOn); break;
865 case 2: Options.setStackProtectorMode(LangOptions::SSPReq); break;
866 }
Bill Wendling45483f72009-06-28 07:36:13 +0000867
Daniel Dunbarc9abc042009-04-08 05:11:16 +0000868 if (MainFileName.getPosition())
869 Options.setMainFileName(MainFileName.c_str());
Reid Spencer5f016e22007-07-11 17:01:13 +0000870}
871
872//===----------------------------------------------------------------------===//
Ted Kremenekae360762007-12-03 22:06:55 +0000873// Target Triple Processing.
874//===----------------------------------------------------------------------===//
875
876static llvm::cl::opt<std::string>
877TargetTriple("triple",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000878 llvm::cl::desc("Specify target triple (e.g. i686-apple-darwin9)"));
Ted Kremenekae360762007-12-03 22:06:55 +0000879
Chris Lattner42e67372008-03-05 01:18:20 +0000880static llvm::cl::opt<std::string>
Mike Stump1eb44332009-09-09 15:08:12 +0000881MacOSVersionMin("mmacosx-version-min",
Daniel Dunbar8d33cd72009-04-10 19:52:24 +0000882 llvm::cl::desc("Specify target Mac OS X version (e.g. 10.5)"));
Chris Lattner6a30c1f2008-09-30 01:13:12 +0000883
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000884// If -mmacosx-version-min=10.3.9 is specified, change the triple from being
885// something like powerpc-apple-darwin9 to powerpc-apple-darwin7
Daniel Dunbar64ffc142009-03-31 20:10:05 +0000886
887// FIXME: We should have the driver do this instead.
Chris Lattner2f60af72009-09-12 22:45:58 +0000888static void HandleMacOSVersionMin(llvm::Triple &Triple) {
889 if (Triple.getOS() != llvm::Triple::Darwin) {
Mike Stump1eb44332009-09-09 15:08:12 +0000890 fprintf(stderr,
Daniel Dunbar8d33cd72009-04-10 19:52:24 +0000891 "-mmacosx-version-min only valid for darwin (Mac OS X) targets\n");
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000892 exit(1);
893 }
Chris Lattner2f60af72009-09-12 22:45:58 +0000894
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000895 // Validate that MacOSVersionMin is a 'version number', starting with 10.[3-9]
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000896 if (MacOSVersionMin.size() < 4 ||
897 MacOSVersionMin.substr(0, 3) != "10." ||
898 !isdigit(MacOSVersionMin[3])) {
Mike Stump1eb44332009-09-09 15:08:12 +0000899 fprintf(stderr,
Daniel Dunbaraf07f932009-03-31 17:35:15 +0000900 "-mmacosx-version-min=%s is invalid, expected something like '10.4'.\n",
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000901 MacOSVersionMin.c_str());
902 exit(1);
903 }
Chris Lattner2f60af72009-09-12 22:45:58 +0000904
905 unsigned VersionNum = MacOSVersionMin[3]-'0';
906
907 if (VersionNum <= 4 && Triple.getArch() == llvm::Triple::x86_64) {
Mike Stump1eb44332009-09-09 15:08:12 +0000908 fprintf(stderr,
Chris Lattner2f60af72009-09-12 22:45:58 +0000909 "-mmacosx-version-min=%s is invalid with -arch x86_64.\n",
Fariborz Jahanian6a1284a2009-04-10 20:33:45 +0000910 MacOSVersionMin.c_str());
911 exit(1);
912 }
913
Chris Lattner2f60af72009-09-12 22:45:58 +0000914
915 llvm::SmallString<16> NewDarwinString;
916 NewDarwinString += "darwin";
917
918 // Turn MacOSVersionMin into a darwin number: e.g. 10.3.9 is 3 -> darwin7.
919 VersionNum += 4;
920 if (VersionNum > 9) {
921 NewDarwinString += '1';
922 VersionNum -= 10;
923 }
924 NewDarwinString += (VersionNum+'0');
925
926 if (MacOSVersionMin.size() == 4) {
927 // "10.4" is ok.
928 } else if (MacOSVersionMin.size() == 6 &&
929 MacOSVersionMin[4] == '.' &&
930 isdigit(MacOSVersionMin[5])) { // 10.4.7 is ok.
931 // Add the period piece (.7) to the end of the triple. This gives us
932 // something like ...-darwin8.7
933 NewDarwinString += '.';
934 NewDarwinString += MacOSVersionMin[5];
935 } else { // "10.4" is ok. 10.4x is not.
936 fprintf(stderr,
937 "-mmacosx-version-min=%s is invalid, expected something like '10.4'.\n",
938 MacOSVersionMin.c_str());
939 exit(1);
940 }
941
942 Triple.setOSName(NewDarwinString.str());
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000943}
944
Daniel Dunbar8d33cd72009-04-10 19:52:24 +0000945static llvm::cl::opt<std::string>
Mike Stump1eb44332009-09-09 15:08:12 +0000946IPhoneOSVersionMin("miphoneos-version-min",
Daniel Dunbar8d33cd72009-04-10 19:52:24 +0000947 llvm::cl::desc("Specify target iPhone OS version (e.g. 2.0)"));
948
949// If -miphoneos-version-min=2.2 is specified, change the triple from being
950// something like armv6-apple-darwin10 to armv6-apple-darwin9.2.2. We use
951// 9 as the default major Darwin number, and encode the iPhone OS version
952// number in the minor version and revision.
953
954// FIXME: We should have the driver do this instead.
Chris Lattner2f60af72009-09-12 22:45:58 +0000955static void HandleIPhoneOSVersionMin(llvm::Triple &Triple) {
956 if (Triple.getOS() != llvm::Triple::Darwin) {
Mike Stump1eb44332009-09-09 15:08:12 +0000957 fprintf(stderr,
Chris Lattner2f60af72009-09-12 22:45:58 +0000958 "-miphoneos-version-min only valid for darwin (Mac OS X) targets\n");
Daniel Dunbar8d33cd72009-04-10 19:52:24 +0000959 exit(1);
960 }
Mike Stump1eb44332009-09-09 15:08:12 +0000961
Chris Lattner2f60af72009-09-12 22:45:58 +0000962 // Validate that IPhoneOSVersionMin is a 'version number', starting with
963 // [2-9].[0-9]
964 if (IPhoneOSVersionMin.size() != 3 || !isdigit(IPhoneOSVersionMin[0]) ||
965 IPhoneOSVersionMin[1] != '.' || !isdigit(IPhoneOSVersionMin[2])) {
Mike Stump1eb44332009-09-09 15:08:12 +0000966 fprintf(stderr,
Chris Lattner2f60af72009-09-12 22:45:58 +0000967 "-miphoneos-version-min=%s is invalid, expected something like '2.0'.\n",
Daniel Dunbar8d33cd72009-04-10 19:52:24 +0000968 IPhoneOSVersionMin.c_str());
969 exit(1);
970 }
Chris Lattner2f60af72009-09-12 22:45:58 +0000971
972 // Turn IPhoneOSVersionMin into a darwin number: e.g. 2.0 is 2 -> 9.2.0
973 llvm::SmallString<16> NewDarwinString;
974 NewDarwinString += "darwin9.";
975 NewDarwinString += IPhoneOSVersionMin;
976 Triple.setOSName(NewDarwinString.str());
Daniel Dunbar8d33cd72009-04-10 19:52:24 +0000977}
978
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000979/// CreateTargetTriple - Process the various options that affect the target
980/// triple and build a final aggregate triple that we are compiling for.
Chris Lattner2f60af72009-09-12 22:45:58 +0000981static llvm::Triple CreateTargetTriple() {
Ted Kremenekae360762007-12-03 22:06:55 +0000982 // Initialize base triple. If a -triple option has been specified, use
983 // that triple. Otherwise, default to the host triple.
Chris Lattner2f60af72009-09-12 22:45:58 +0000984 llvm::Triple Triple(TargetTriple);
985 if (Triple.getTriple().empty())
986 Triple = llvm::Triple(llvm::sys::getHostTriple());
Chris Lattner6a30c1f2008-09-30 01:13:12 +0000987
988 // If -mmacosx-version-min=10.3.9 is specified, change the triple from being
989 // something like powerpc-apple-darwin9 to powerpc-apple-darwin7
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000990 if (!MacOSVersionMin.empty())
991 HandleMacOSVersionMin(Triple);
Daniel Dunbar8d33cd72009-04-10 19:52:24 +0000992 else if (!IPhoneOSVersionMin.empty())
Chris Lattner2f60af72009-09-12 22:45:58 +0000993 HandleIPhoneOSVersionMin(Triple);
Mike Stump1eb44332009-09-09 15:08:12 +0000994
Chris Lattner6a30c1f2008-09-30 01:13:12 +0000995 return Triple;
Ted Kremenekae360762007-12-03 22:06:55 +0000996}
997
998//===----------------------------------------------------------------------===//
Chris Lattnere116ccf2009-04-21 05:40:52 +0000999// SourceManager initialization.
Reid Spencer5f016e22007-07-11 17:01:13 +00001000//===----------------------------------------------------------------------===//
1001
Douglas Gregore1d918e2009-04-10 23:10:45 +00001002static bool InitializeSourceManager(Preprocessor &PP,
1003 const std::string &InFile) {
1004 // Figure out where to get and map in the main file.
1005 SourceManager &SourceMgr = PP.getSourceManager();
1006 FileManager &FileMgr = PP.getFileManager();
Daniel Dunbar57cbfc02009-04-27 21:19:07 +00001007
1008 if (EmptyInputOnly) {
1009 const char *EmptyStr = "";
Mike Stump1eb44332009-09-09 15:08:12 +00001010 llvm::MemoryBuffer *SB =
Daniel Dunbar57cbfc02009-04-27 21:19:07 +00001011 llvm::MemoryBuffer::getMemBuffer(EmptyStr, EmptyStr, "<empty input>");
1012 SourceMgr.createMainFileIDForMemBuffer(SB);
1013 } else if (InFile != "-") {
Douglas Gregore1d918e2009-04-10 23:10:45 +00001014 const FileEntry *File = FileMgr.getFile(InFile);
1015 if (File) SourceMgr.createMainFileID(File, SourceLocation());
1016 if (SourceMgr.getMainFileID().isInvalid()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001017 PP.getDiagnostics().Report(FullSourceLoc(), diag::err_fe_error_reading)
Douglas Gregore1d918e2009-04-10 23:10:45 +00001018 << InFile.c_str();
1019 return true;
1020 }
1021 } else {
1022 llvm::MemoryBuffer *SB = llvm::MemoryBuffer::getSTDIN();
1023
1024 // If stdin was empty, SB is null. Cons up an empty memory
1025 // buffer now.
1026 if (!SB) {
1027 const char *EmptyStr = "";
1028 SB = llvm::MemoryBuffer::getMemBuffer(EmptyStr, EmptyStr, "<stdin>");
1029 }
1030
1031 SourceMgr.createMainFileIDForMemBuffer(SB);
1032 if (SourceMgr.getMainFileID().isInvalid()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001033 PP.getDiagnostics().Report(FullSourceLoc(),
Douglas Gregore1d918e2009-04-10 23:10:45 +00001034 diag::err_fe_error_reading_stdin);
1035 return true;
1036 }
1037 }
1038
1039 return false;
1040}
1041
Chris Lattneraa391972008-04-19 23:09:31 +00001042
Chris Lattnere116ccf2009-04-21 05:40:52 +00001043//===----------------------------------------------------------------------===//
1044// Preprocessor Initialization
1045//===----------------------------------------------------------------------===//
Sam Bishop1102d6b2008-04-14 14:41:57 +00001046
Chris Lattnere116ccf2009-04-21 05:40:52 +00001047// FIXME: Preprocessor builtins to support.
1048// -A... - Play with #assertions
1049// -undef - Undefine all predefined macros
Chris Lattnerb31ac222009-04-08 20:15:42 +00001050
Chris Lattnere116ccf2009-04-21 05:40:52 +00001051static llvm::cl::list<std::string>
1052D_macros("D", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
1053 llvm::cl::desc("Predefine the specified macro"));
1054static llvm::cl::list<std::string>
1055U_macros("U", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
1056 llvm::cl::desc("Undefine the specified macro"));
Chris Lattnerb8e240e2009-04-08 18:24:34 +00001057
Chris Lattnere116ccf2009-04-21 05:40:52 +00001058static llvm::cl::list<std::string>
1059ImplicitIncludes("include", llvm::cl::value_desc("file"),
1060 llvm::cl::desc("Include file before parsing"));
1061static llvm::cl::list<std::string>
1062ImplicitMacroIncludes("imacros", llvm::cl::value_desc("file"),
1063 llvm::cl::desc("Include macros from file before parsing"));
Chris Lattnerb8e240e2009-04-08 18:24:34 +00001064
Chris Lattnere116ccf2009-04-21 05:40:52 +00001065static llvm::cl::opt<std::string>
1066ImplicitIncludePCH("include-pch", llvm::cl::value_desc("file"),
1067 llvm::cl::desc("Include precompiled header file"));
1068
1069static llvm::cl::opt<std::string>
1070ImplicitIncludePTH("include-pth", llvm::cl::value_desc("file"),
1071 llvm::cl::desc("Include file before parsing"));
1072
Douglas Gregore650c8c2009-07-07 00:12:59 +00001073static llvm::cl::opt<bool>
Mike Stump1eb44332009-09-09 15:08:12 +00001074RelocatablePCH("relocatable-pch",
Douglas Gregore650c8c2009-07-07 00:12:59 +00001075 llvm::cl::desc("Whether to build a relocatable precompiled "
1076 "header"));
Reid Spencer5f016e22007-07-11 17:01:13 +00001077
1078//===----------------------------------------------------------------------===//
1079// Preprocessor include path information.
1080//===----------------------------------------------------------------------===//
1081
1082// This tool exports a large number of command line options to control how the
1083// preprocessor searches for header files. At root, however, the Preprocessor
1084// object takes a very simple interface: a list of directories to search for
Mike Stump1eb44332009-09-09 15:08:12 +00001085//
Daniel Dunbarfb4ac7b2009-05-06 03:48:17 +00001086// FIXME: -nostdinc++
Chris Lattner0c946412007-08-26 17:47:35 +00001087// FIXME: -imultilib
Reid Spencer5f016e22007-07-11 17:01:13 +00001088//
Reid Spencer5f016e22007-07-11 17:01:13 +00001089
1090static llvm::cl::opt<bool>
1091nostdinc("nostdinc", llvm::cl::desc("Disable standard #include directories"));
1092
1093// Various command line options. These four add directories to each chain.
1094static llvm::cl::list<std::string>
1095F_dirs("F", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1096 llvm::cl::desc("Add directory to framework include search path"));
1097static llvm::cl::list<std::string>
1098I_dirs("I", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1099 llvm::cl::desc("Add directory to include search path"));
1100static llvm::cl::list<std::string>
1101idirafter_dirs("idirafter", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1102 llvm::cl::desc("Add directory to AFTER include search path"));
1103static llvm::cl::list<std::string>
1104iquote_dirs("iquote", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1105 llvm::cl::desc("Add directory to QUOTE include search path"));
1106static llvm::cl::list<std::string>
1107isystem_dirs("isystem", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1108 llvm::cl::desc("Add directory to SYSTEM include search path"));
1109
1110// These handle -iprefix/-iwithprefix/-iwithprefixbefore.
1111static llvm::cl::list<std::string>
1112iprefix_vals("iprefix", llvm::cl::value_desc("prefix"), llvm::cl::Prefix,
1113 llvm::cl::desc("Set the -iwithprefix/-iwithprefixbefore prefix"));
1114static llvm::cl::list<std::string>
1115iwithprefix_vals("iwithprefix", llvm::cl::value_desc("dir"), llvm::cl::Prefix,
1116 llvm::cl::desc("Set directory to SYSTEM include search path with prefix"));
1117static llvm::cl::list<std::string>
1118iwithprefixbefore_vals("iwithprefixbefore", llvm::cl::value_desc("dir"),
1119 llvm::cl::Prefix,
1120 llvm::cl::desc("Set directory to include search path with prefix"));
1121
Chris Lattner0c946412007-08-26 17:47:35 +00001122static llvm::cl::opt<std::string>
1123isysroot("isysroot", llvm::cl::value_desc("dir"), llvm::cl::init("/"),
1124 llvm::cl::desc("Set the system root directory (usually /)"));
1125
Reid Spencer5f016e22007-07-11 17:01:13 +00001126// Finally, implement the code that groks the options above.
Chris Lattner5f9eae52008-03-01 08:07:28 +00001127
Reid Spencer5f016e22007-07-11 17:01:13 +00001128/// InitializeIncludePaths - Process the -I options and set them in the
1129/// HeaderSearch object.
Nico Weber0fca0222008-08-22 09:25:22 +00001130void InitializeIncludePaths(const char *Argv0, HeaderSearch &Headers,
1131 FileManager &FM, const LangOptions &Lang) {
1132 InitHeaderSearch Init(Headers, Verbose, isysroot);
1133
Ted Kremenekf3721112008-05-31 00:27:00 +00001134 // Handle -I... and -F... options, walking the lists in parallel.
1135 unsigned Iidx = 0, Fidx = 0;
1136 while (Iidx < I_dirs.size() && Fidx < F_dirs.size()) {
1137 if (I_dirs.getPosition(Iidx) < F_dirs.getPosition(Fidx)) {
Nico Weber0fca0222008-08-22 09:25:22 +00001138 Init.AddPath(I_dirs[Iidx], InitHeaderSearch::Angled, false, true, false);
Ted Kremenekf3721112008-05-31 00:27:00 +00001139 ++Iidx;
1140 } else {
Nico Weber0fca0222008-08-22 09:25:22 +00001141 Init.AddPath(F_dirs[Fidx], InitHeaderSearch::Angled, false, true, true);
Ted Kremenekf3721112008-05-31 00:27:00 +00001142 ++Fidx;
1143 }
1144 }
Mike Stump1eb44332009-09-09 15:08:12 +00001145
Ted Kremenekf3721112008-05-31 00:27:00 +00001146 // Consume what's left from whatever list was longer.
1147 for (; Iidx != I_dirs.size(); ++Iidx)
Nico Weber0fca0222008-08-22 09:25:22 +00001148 Init.AddPath(I_dirs[Iidx], InitHeaderSearch::Angled, false, true, false);
Ted Kremenekf3721112008-05-31 00:27:00 +00001149 for (; Fidx != F_dirs.size(); ++Fidx)
Nico Weber0fca0222008-08-22 09:25:22 +00001150 Init.AddPath(F_dirs[Fidx], InitHeaderSearch::Angled, false, true, true);
Mike Stump1eb44332009-09-09 15:08:12 +00001151
Reid Spencer5f016e22007-07-11 17:01:13 +00001152 // Handle -idirafter... options.
1153 for (unsigned i = 0, e = idirafter_dirs.size(); i != e; ++i)
Nico Weber0fca0222008-08-22 09:25:22 +00001154 Init.AddPath(idirafter_dirs[i], InitHeaderSearch::After,
1155 false, true, false);
Mike Stump1eb44332009-09-09 15:08:12 +00001156
Reid Spencer5f016e22007-07-11 17:01:13 +00001157 // Handle -iquote... options.
1158 for (unsigned i = 0, e = iquote_dirs.size(); i != e; ++i)
Nico Weber0fca0222008-08-22 09:25:22 +00001159 Init.AddPath(iquote_dirs[i], InitHeaderSearch::Quoted, false, true, false);
Mike Stump1eb44332009-09-09 15:08:12 +00001160
Reid Spencer5f016e22007-07-11 17:01:13 +00001161 // Handle -isystem... options.
1162 for (unsigned i = 0, e = isystem_dirs.size(); i != e; ++i)
Nico Weber0fca0222008-08-22 09:25:22 +00001163 Init.AddPath(isystem_dirs[i], InitHeaderSearch::System, false, true, false);
Reid Spencer5f016e22007-07-11 17:01:13 +00001164
1165 // Walk the -iprefix/-iwithprefix/-iwithprefixbefore argument lists in
1166 // parallel, processing the values in order of occurance to get the right
1167 // prefixes.
1168 {
1169 std::string Prefix = ""; // FIXME: this isn't the correct default prefix.
1170 unsigned iprefix_idx = 0;
1171 unsigned iwithprefix_idx = 0;
1172 unsigned iwithprefixbefore_idx = 0;
1173 bool iprefix_done = iprefix_vals.empty();
1174 bool iwithprefix_done = iwithprefix_vals.empty();
1175 bool iwithprefixbefore_done = iwithprefixbefore_vals.empty();
1176 while (!iprefix_done || !iwithprefix_done || !iwithprefixbefore_done) {
1177 if (!iprefix_done &&
Mike Stump1eb44332009-09-09 15:08:12 +00001178 (iwithprefix_done ||
1179 iprefix_vals.getPosition(iprefix_idx) <
Reid Spencer5f016e22007-07-11 17:01:13 +00001180 iwithprefix_vals.getPosition(iwithprefix_idx)) &&
Mike Stump1eb44332009-09-09 15:08:12 +00001181 (iwithprefixbefore_done ||
1182 iprefix_vals.getPosition(iprefix_idx) <
Reid Spencer5f016e22007-07-11 17:01:13 +00001183 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
1184 Prefix = iprefix_vals[iprefix_idx];
1185 ++iprefix_idx;
1186 iprefix_done = iprefix_idx == iprefix_vals.size();
1187 } else if (!iwithprefix_done &&
Mike Stump1eb44332009-09-09 15:08:12 +00001188 (iwithprefixbefore_done ||
1189 iwithprefix_vals.getPosition(iwithprefix_idx) <
Reid Spencer5f016e22007-07-11 17:01:13 +00001190 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
Mike Stump1eb44332009-09-09 15:08:12 +00001191 Init.AddPath(Prefix+iwithprefix_vals[iwithprefix_idx],
Nico Weber0fca0222008-08-22 09:25:22 +00001192 InitHeaderSearch::System, false, false, false);
Reid Spencer5f016e22007-07-11 17:01:13 +00001193 ++iwithprefix_idx;
1194 iwithprefix_done = iwithprefix_idx == iwithprefix_vals.size();
1195 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00001196 Init.AddPath(Prefix+iwithprefixbefore_vals[iwithprefixbefore_idx],
Nico Weber0fca0222008-08-22 09:25:22 +00001197 InitHeaderSearch::Angled, false, false, false);
Reid Spencer5f016e22007-07-11 17:01:13 +00001198 ++iwithprefixbefore_idx;
Mike Stump1eb44332009-09-09 15:08:12 +00001199 iwithprefixbefore_done =
Reid Spencer5f016e22007-07-11 17:01:13 +00001200 iwithprefixbefore_idx == iwithprefixbefore_vals.size();
1201 }
1202 }
1203 }
Chris Lattner5f9eae52008-03-01 08:07:28 +00001204
Nico Weber0fca0222008-08-22 09:25:22 +00001205 Init.AddDefaultEnvVarPaths(Lang);
Chris Lattner5f9eae52008-03-01 08:07:28 +00001206
Daniel Dunbaradcf5b32009-02-21 20:52:41 +00001207 // Add the clang headers, which are relative to the clang binary.
Mike Stump1eb44332009-09-09 15:08:12 +00001208 llvm::sys::Path MainExecutablePath =
Chris Lattner985e1822008-03-03 05:57:43 +00001209 llvm::sys::Path::GetMainExecutable(Argv0,
1210 (void*)(intptr_t)InitializeIncludePaths);
Chris Lattnerdcaa0962008-03-03 03:16:03 +00001211 if (!MainExecutablePath.isEmpty()) {
1212 MainExecutablePath.eraseComponent(); // Remove /clang from foo/bin/clang
1213 MainExecutablePath.eraseComponent(); // Remove /bin from foo/bin
Daniel Dunbaradcf5b32009-02-21 20:52:41 +00001214
Mike Stump1eb44332009-09-09 15:08:12 +00001215 // Get foo/lib/clang/<version>/include
Daniel Dunbaradcf5b32009-02-21 20:52:41 +00001216 MainExecutablePath.appendComponent("lib");
1217 MainExecutablePath.appendComponent("clang");
Daniel Dunbarfb4ac7b2009-05-06 03:48:17 +00001218 MainExecutablePath.appendComponent(CLANG_VERSION_STRING);
Daniel Dunbaradcf5b32009-02-21 20:52:41 +00001219 MainExecutablePath.appendComponent("include");
Mike Stump1eb44332009-09-09 15:08:12 +00001220
Chris Lattner6858dd32009-02-19 06:48:28 +00001221 // We pass true to ignore sysroot so that we *always* look for clang headers
1222 // relative to our executable, never relative to -isysroot.
1223 Init.AddPath(MainExecutablePath.c_str(), InitHeaderSearch::System,
1224 false, false, false, true /*ignore sysroot*/);
Chris Lattnerdcaa0962008-03-03 03:16:03 +00001225 }
Mike Stump1eb44332009-09-09 15:08:12 +00001226
1227 if (!nostdinc)
Nico Weber0fca0222008-08-22 09:25:22 +00001228 Init.AddDefaultSystemIncludePaths(Lang);
Reid Spencer5f016e22007-07-11 17:01:13 +00001229
1230 // Now that we have collected all of the include paths, merge them all
1231 // together and tell the preprocessor about them.
Mike Stump1eb44332009-09-09 15:08:12 +00001232
Nico Weber0fca0222008-08-22 09:25:22 +00001233 Init.Realize();
Reid Spencer5f016e22007-07-11 17:01:13 +00001234}
1235
Mike Stump1eb44332009-09-09 15:08:12 +00001236void InitializePreprocessorInitOptions(PreprocessorInitOptions &InitOpts) {
Chris Lattnere116ccf2009-04-21 05:40:52 +00001237 // Add macros from the command line.
1238 unsigned d = 0, D = D_macros.size();
1239 unsigned u = 0, U = U_macros.size();
1240 while (d < D || u < U) {
1241 if (u == U || (d < D && D_macros.getPosition(d) < U_macros.getPosition(u)))
1242 InitOpts.addMacroDef(D_macros[d++]);
1243 else
1244 InitOpts.addMacroUndef(U_macros[u++]);
1245 }
1246
1247 // If -imacros are specified, include them now. These are processed before
1248 // any -include directives.
1249 for (unsigned i = 0, e = ImplicitMacroIncludes.size(); i != e; ++i)
1250 InitOpts.addMacroInclude(ImplicitMacroIncludes[i]);
1251
Douglas Gregorb64c1932009-05-12 01:31:05 +00001252 if (!ImplicitIncludePTH.empty() || !ImplicitIncludes.empty() ||
1253 (!ImplicitIncludePCH.empty() && ProgAction == PrintPreprocessedInput)) {
Chris Lattnere116ccf2009-04-21 05:40:52 +00001254 // We want to add these paths to the predefines buffer in order, make a
1255 // temporary vector to sort by their occurrence.
1256 llvm::SmallVector<std::pair<unsigned, std::string*>, 8> OrderedPaths;
1257
1258 if (!ImplicitIncludePTH.empty())
1259 OrderedPaths.push_back(std::make_pair(ImplicitIncludePTH.getPosition(),
1260 &ImplicitIncludePTH));
Douglas Gregorb64c1932009-05-12 01:31:05 +00001261 if (!ImplicitIncludePCH.empty() && ProgAction == PrintPreprocessedInput)
1262 OrderedPaths.push_back(std::make_pair(ImplicitIncludePCH.getPosition(),
1263 &ImplicitIncludePCH));
Chris Lattnere116ccf2009-04-21 05:40:52 +00001264 for (unsigned i = 0, e = ImplicitIncludes.size(); i != e; ++i)
1265 OrderedPaths.push_back(std::make_pair(ImplicitIncludes.getPosition(i),
1266 &ImplicitIncludes[i]));
1267 llvm::array_pod_sort(OrderedPaths.begin(), OrderedPaths.end());
1268
1269
1270 // Now that they are ordered by position, add to the predefines buffer.
1271 for (unsigned i = 0, e = OrderedPaths.size(); i != e; ++i) {
1272 std::string *Ptr = OrderedPaths[i].second;
1273 if (!ImplicitIncludes.empty() &&
1274 Ptr >= &ImplicitIncludes[0] &&
1275 Ptr <= &ImplicitIncludes[ImplicitIncludes.size()-1]) {
1276 InitOpts.addInclude(*Ptr, false);
Douglas Gregorb64c1932009-05-12 01:31:05 +00001277 } else if (Ptr == &ImplicitIncludePTH) {
Chris Lattnere116ccf2009-04-21 05:40:52 +00001278 InitOpts.addInclude(*Ptr, true);
Douglas Gregorb64c1932009-05-12 01:31:05 +00001279 } else {
1280 // We end up here when we're producing preprocessed output and
1281 // we loaded a PCH file. In this case, just include the header
1282 // file that was used to build the precompiled header.
1283 assert(Ptr == &ImplicitIncludePCH);
1284 std::string OriginalFile = PCHReader::getOriginalSourceFile(*Ptr);
1285 if (!OriginalFile.empty()) {
1286 InitOpts.addInclude(OriginalFile, false);
1287 ImplicitIncludePCH.clear();
1288 }
Chris Lattnere116ccf2009-04-21 05:40:52 +00001289 }
1290 }
1291 }
1292}
1293
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001294//===----------------------------------------------------------------------===//
1295// Driver PreprocessorFactory - For lazily generating preprocessors ...
1296//===----------------------------------------------------------------------===//
1297
1298namespace {
1299class VISIBILITY_HIDDEN DriverPreprocessorFactory : public PreprocessorFactory {
1300 Diagnostic &Diags;
1301 const LangOptions &LangInfo;
1302 TargetInfo &Target;
1303 SourceManager &SourceMgr;
1304 HeaderSearch &HeaderInfo;
Mike Stump1eb44332009-09-09 15:08:12 +00001305
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001306public:
Eli Friedmanf086e3b2009-05-18 07:39:39 +00001307 DriverPreprocessorFactory(Diagnostic &diags, const LangOptions &opts,
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001308 TargetInfo &target, SourceManager &SM,
Mike Stump1eb44332009-09-09 15:08:12 +00001309 HeaderSearch &Headers)
Eli Friedmanf086e3b2009-05-18 07:39:39 +00001310 : Diags(diags), LangInfo(opts), Target(target),
Douglas Gregore1d918e2009-04-10 23:10:45 +00001311 SourceMgr(SM), HeaderInfo(Headers) {}
Mike Stump1eb44332009-09-09 15:08:12 +00001312
1313
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001314 virtual ~DriverPreprocessorFactory() {}
Mike Stump1eb44332009-09-09 15:08:12 +00001315
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001316 virtual Preprocessor* CreatePreprocessor() {
Ted Kremenek72b1b152009-01-15 18:47:46 +00001317 llvm::OwningPtr<PTHManager> PTHMgr;
1318
Ted Kremenek748d5d62009-03-20 00:26:38 +00001319 if (!TokenCache.empty() && !ImplicitIncludePTH.empty()) {
1320 fprintf(stderr, "error: cannot use both -token-cache and -include-pth "
1321 "options\n");
Ted Kremenek22f0d092009-03-22 06:42:39 +00001322 exit(1);
Ted Kremenek748d5d62009-03-20 00:26:38 +00001323 }
Mike Stump1eb44332009-09-09 15:08:12 +00001324
Ted Kremenek72b1b152009-01-15 18:47:46 +00001325 // Use PTH?
Ted Kremenek748d5d62009-03-20 00:26:38 +00001326 if (!TokenCache.empty() || !ImplicitIncludePTH.empty()) {
1327 const std::string& x = TokenCache.empty() ? ImplicitIncludePTH:TokenCache;
Mike Stump1eb44332009-09-09 15:08:12 +00001328 PTHMgr.reset(PTHManager::Create(x, &Diags,
Ted Kremenek22f0d092009-03-22 06:42:39 +00001329 TokenCache.empty() ? Diagnostic::Error
1330 : Diagnostic::Warning));
Ted Kremenek748d5d62009-03-20 00:26:38 +00001331 }
Mike Stump1eb44332009-09-09 15:08:12 +00001332
Ted Kremenek22f0d092009-03-22 06:42:39 +00001333 if (Diags.hasErrorOccurred())
1334 exit(1);
Mike Stump1eb44332009-09-09 15:08:12 +00001335
Ted Kremenek72b1b152009-01-15 18:47:46 +00001336 // Create the Preprocessor.
1337 llvm::OwningPtr<Preprocessor> PP(new Preprocessor(Diags, LangInfo, Target,
1338 SourceMgr, HeaderInfo,
1339 PTHMgr.get()));
Mike Stump1eb44332009-09-09 15:08:12 +00001340
Ted Kremenek72b1b152009-01-15 18:47:46 +00001341 // Note that this is different then passing PTHMgr to Preprocessor's ctor.
1342 // That argument is used as the IdentifierInfoLookup argument to
1343 // IdentifierTable's ctor.
1344 if (PTHMgr) {
1345 PTHMgr->setPreprocessor(PP.get());
1346 PP->setPTHManager(PTHMgr.take());
1347 }
Douglas Gregor14f79002009-04-10 03:52:48 +00001348
Chris Lattnere116ccf2009-04-21 05:40:52 +00001349 PreprocessorInitOptions InitOpts;
1350 InitializePreprocessorInitOptions(InitOpts);
Eli Friedmanf086e3b2009-05-18 07:39:39 +00001351 if (InitializePreprocessor(*PP, InitOpts))
Douglas Gregore1d918e2009-04-10 23:10:45 +00001352 return 0;
Chris Lattnere116ccf2009-04-21 05:40:52 +00001353
Douglas Gregore1d918e2009-04-10 23:10:45 +00001354 return PP.take();
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001355 }
1356};
1357}
Reid Spencer5f016e22007-07-11 17:01:13 +00001358
Reid Spencer5f016e22007-07-11 17:01:13 +00001359//===----------------------------------------------------------------------===//
1360// Basic Parser driver
1361//===----------------------------------------------------------------------===//
1362
Chris Lattner51574ea2008-04-19 23:25:44 +00001363static void ParseFile(Preprocessor &PP, MinimalAction *PA) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001364 Parser P(PP, *PA);
Ted Kremenek95041a22007-12-19 22:51:13 +00001365 PP.EnterMainSourceFile();
Mike Stump1eb44332009-09-09 15:08:12 +00001366
Reid Spencer5f016e22007-07-11 17:01:13 +00001367 // Parsing the specified input file.
1368 P.ParseTranslationUnit();
1369 delete PA;
1370}
1371
1372//===----------------------------------------------------------------------===//
Daniel Dunbar70f92432008-10-23 05:50:47 +00001373// Code generation options
1374//===----------------------------------------------------------------------===//
1375
1376static llvm::cl::opt<bool>
Chris Lattner15104882009-03-09 22:05:03 +00001377GenerateDebugInfo("g",
1378 llvm::cl::desc("Generate source level debug information"));
1379
Daniel Dunbara034ba82009-02-17 19:47:34 +00001380static llvm::cl::opt<std::string>
1381TargetCPU("mcpu",
1382 llvm::cl::desc("Target a specific cpu type (-mcpu=help for details)"));
1383
Daniel Dunbar868bd0a2009-05-06 03:16:41 +00001384static llvm::cl::list<std::string>
1385TargetFeatures("target-feature", llvm::cl::desc("Target specific attributes"));
1386
Devang Patel24095da2009-06-04 23:32:02 +00001387
1388static llvm::cl::opt<bool>
1389DisableRedZone("disable-red-zone",
1390 llvm::cl::desc("Do not emit code that uses the red zone."),
1391 llvm::cl::init(false));
1392
Devang Patelacebb392009-06-05 22:05:48 +00001393static llvm::cl::opt<bool>
1394NoImplicitFloat("no-implicit-float",
1395 llvm::cl::desc("Don't generate implicit floating point instructions (x86-only)"),
1396 llvm::cl::init(false));
1397
Daniel Dunbar868bd0a2009-05-06 03:16:41 +00001398/// ComputeTargetFeatures - Recompute the target feature list to only
1399/// be the list of things that are enabled, based on the target cpu
1400/// and feature list.
1401static void ComputeFeatureMap(TargetInfo *Target,
1402 llvm::StringMap<bool> &Features) {
Mike Stump1eb44332009-09-09 15:08:12 +00001403 assert(Features.empty() && "invalid map");
Daniel Dunbar868bd0a2009-05-06 03:16:41 +00001404
1405 // Initialize the feature map based on the target.
1406 Target->getDefaultFeatures(TargetCPU, Features);
1407
1408 // Apply the user specified deltas.
Mike Stump1eb44332009-09-09 15:08:12 +00001409 for (llvm::cl::list<std::string>::iterator it = TargetFeatures.begin(),
Daniel Dunbar868bd0a2009-05-06 03:16:41 +00001410 ie = TargetFeatures.end(); it != ie; ++it) {
1411 const char *Name = it->c_str();
Mike Stump1eb44332009-09-09 15:08:12 +00001412
Daniel Dunbar868bd0a2009-05-06 03:16:41 +00001413 // FIXME: Don't handle errors like this.
1414 if (Name[0] != '-' && Name[0] != '+') {
Mike Stump1eb44332009-09-09 15:08:12 +00001415 fprintf(stderr, "error: clang-cc: invalid target feature string: %s\n",
Daniel Dunbar868bd0a2009-05-06 03:16:41 +00001416 Name);
1417 exit(1);
1418 }
Daniel Dunbar17ca3632009-05-06 21:07:50 +00001419 if (!Target->setFeatureEnabled(Features, Name + 1, (Name[0] == '+'))) {
Mike Stump1eb44332009-09-09 15:08:12 +00001420 fprintf(stderr, "error: clang-cc: invalid target feature name: %s\n",
Daniel Dunbar17ca3632009-05-06 21:07:50 +00001421 Name + 1);
Daniel Dunbar868bd0a2009-05-06 03:16:41 +00001422 exit(1);
1423 }
Daniel Dunbar868bd0a2009-05-06 03:16:41 +00001424 }
1425}
1426
Chris Lattner7afae712009-03-16 18:41:18 +00001427static void InitializeCompileOptions(CompileOptions &Opts,
Daniel Dunbar868bd0a2009-05-06 03:16:41 +00001428 const LangOptions &LangOpts,
1429 const llvm::StringMap<bool> &Features) {
Daniel Dunbar70f92432008-10-23 05:50:47 +00001430 Opts.OptimizeSize = OptSize;
Chris Lattner20126042009-03-09 22:00:34 +00001431 Opts.DebugInfo = GenerateDebugInfo;
Daniel Dunbar877db382009-06-02 22:07:45 +00001432
1433 if (DisableLLVMOptimizations) {
1434 Opts.OptimizationLevel = 0;
1435 Opts.Inlining = CompileOptions::NoInlining;
Daniel Dunbarac7ffe02008-10-29 07:56:11 +00001436 } else {
Daniel Dunbar877db382009-06-02 22:07:45 +00001437 if (OptSize) {
1438 // -Os implies -O2
1439 Opts.OptimizationLevel = 2;
1440 } else {
1441 Opts.OptimizationLevel = OptLevel;
1442 }
1443
1444 // We must always run at least the always inlining pass.
1445 if (Opts.OptimizationLevel > 1)
1446 Opts.Inlining = CompileOptions::NormalInlining;
1447 else
1448 Opts.Inlining = CompileOptions::OnlyAlwaysInlining;
Daniel Dunbarac7ffe02008-10-29 07:56:11 +00001449 }
Daniel Dunbar8e8f3b72008-10-29 03:42:18 +00001450
1451 // FIXME: There are llvm-gcc options to control these selectively.
Daniel Dunbar8e8f3b72008-10-29 03:42:18 +00001452 Opts.UnrollLoops = (Opts.OptimizationLevel > 1 && !OptSize);
Chris Lattner7afae712009-03-16 18:41:18 +00001453 Opts.SimplifyLibCalls = !LangOpts.NoBuiltin;
Daniel Dunbardd913e52008-10-31 09:34:21 +00001454
1455#ifdef NDEBUG
1456 Opts.VerifyModule = 0;
1457#endif
Daniel Dunbara034ba82009-02-17 19:47:34 +00001458
1459 Opts.CPU = TargetCPU;
Daniel Dunbar868bd0a2009-05-06 03:16:41 +00001460 Opts.Features.clear();
Mike Stump1eb44332009-09-09 15:08:12 +00001461 for (llvm::StringMap<bool>::const_iterator it = Features.begin(),
Daniel Dunbar868bd0a2009-05-06 03:16:41 +00001462 ie = Features.end(); it != ie; ++it) {
1463 // FIXME: If we are completely confident that we have the right
1464 // set, we only need to pass the minuses.
1465 std::string Name(it->second ? "+" : "-");
1466 Name += it->first();
1467 Opts.Features.push_back(Name);
1468 }
Mike Stump1eb44332009-09-09 15:08:12 +00001469
Chris Lattnerbd360642009-03-26 05:00:52 +00001470 Opts.NoCommon = NoCommon | LangOpts.CPlusPlus;
Mike Stump1eb44332009-09-09 15:08:12 +00001471
Chris Lattner44502662009-02-18 01:23:44 +00001472 // Handle -ftime-report.
1473 Opts.TimePasses = TimeReport;
Devang Patel24095da2009-06-04 23:32:02 +00001474
1475 Opts.DisableRedZone = DisableRedZone;
Devang Patelacebb392009-06-05 22:05:48 +00001476 Opts.NoImplicitFloat = NoImplicitFloat;
Daniel Dunbar70f92432008-10-23 05:50:47 +00001477}
1478
1479//===----------------------------------------------------------------------===//
Douglas Gregor26df2f02009-04-02 19:05:20 +00001480// Fix-It Options
1481//===----------------------------------------------------------------------===//
1482static llvm::cl::list<ParsedSourceLocation>
1483FixItAtLocations("fixit-at", llvm::cl::value_desc("source-location"),
1484 llvm::cl::desc("Perform Fix-It modifications at the given source location"));
1485
1486//===----------------------------------------------------------------------===//
Eli Friedmanc6d656e2009-05-18 22:39:16 +00001487// ObjC Rewriter Options
1488//===----------------------------------------------------------------------===//
1489static llvm::cl::opt<bool>
1490SilenceRewriteMacroWarning("Wno-rewrite-macros", llvm::cl::init(false),
1491 llvm::cl::desc("Silence ObjC rewriting warnings"));
1492
1493//===----------------------------------------------------------------------===//
Eli Friedman0eeb86e2009-05-19 01:17:04 +00001494// Warning Options
1495//===----------------------------------------------------------------------===//
1496
1497// This gets all -W options, including -Werror, -W[no-]system-headers, etc. The
1498// driver has stripped off -Wa,foo etc. The driver has also translated -W to
1499// -Wextra, so we don't need to worry about it.
1500static llvm::cl::list<std::string>
1501OptWarnings("W", llvm::cl::Prefix, llvm::cl::ValueOptional);
1502
1503static llvm::cl::opt<bool> OptPedantic("pedantic");
1504static llvm::cl::opt<bool> OptPedanticErrors("pedantic-errors");
1505static llvm::cl::opt<bool> OptNoWarnings("w");
1506
1507//===----------------------------------------------------------------------===//
Eli Friedman12d3b1d2009-05-19 03:06:47 +00001508// Preprocessing (-E mode) Options
1509//===----------------------------------------------------------------------===//
1510static llvm::cl::opt<bool>
1511DisableLineMarkers("P", llvm::cl::desc("Disable linemarker output in -E mode"));
1512static llvm::cl::opt<bool>
1513EnableCommentOutput("C", llvm::cl::desc("Enable comment output in -E mode"));
1514static llvm::cl::opt<bool>
1515EnableMacroCommentOutput("CC",
1516 llvm::cl::desc("Enable comment output in -E mode, "
1517 "even from macro expansions"));
1518static llvm::cl::opt<bool>
1519DumpMacros("dM", llvm::cl::desc("Print macro definitions in -E mode instead of"
1520 " normal output"));
1521static llvm::cl::opt<bool>
1522DumpDefines("dD", llvm::cl::desc("Print macro definitions in -E mode in "
1523 "addition to normal output"));
Eli Friedmanb5c8f8b2009-05-19 03:35:57 +00001524
1525//===----------------------------------------------------------------------===//
1526// Dependency file options
1527//===----------------------------------------------------------------------===//
1528static llvm::cl::opt<std::string>
1529DependencyFile("dependency-file",
1530 llvm::cl::desc("Filename (or -) to write dependency output to"));
1531
1532static llvm::cl::opt<bool>
1533DependenciesIncludeSystemHeaders("sys-header-deps",
1534 llvm::cl::desc("Include system headers in dependency output"));
1535
1536static llvm::cl::list<std::string>
1537DependencyTargets("MT",
1538 llvm::cl::desc("Specify target for dependency"));
1539
1540// FIXME: Implement feature
1541static llvm::cl::opt<bool>
1542PhonyDependencyTarget("MP",
1543 llvm::cl::desc("Create phony target for each dependency "
1544 "(other than main file)"));
1545
Eli Friedman12d3b1d2009-05-19 03:06:47 +00001546//===----------------------------------------------------------------------===//
Eli Friedmane71b85f2009-05-19 10:18:02 +00001547// Analysis options
1548//===----------------------------------------------------------------------===//
1549
1550static llvm::cl::list<Analyses>
1551AnalysisList(llvm::cl::desc("Source Code Analysis - Checks and Analyses"),
1552llvm::cl::values(
1553#define ANALYSIS(NAME, CMDFLAG, DESC, SCOPE)\
1554clEnumValN(NAME, CMDFLAG, DESC),
Eli Friedman0ec78fa2009-05-19 21:10:40 +00001555#include "clang/Frontend/Analyses.def"
Eli Friedmane71b85f2009-05-19 10:18:02 +00001556clEnumValEnd));
1557
Mike Stump1eb44332009-09-09 15:08:12 +00001558static llvm::cl::opt<AnalysisStores>
Eli Friedmane71b85f2009-05-19 10:18:02 +00001559AnalysisStoreOpt("analyzer-store",
1560 llvm::cl::desc("Source Code Analysis - Abstract Memory Store Models"),
1561 llvm::cl::init(BasicStoreModel),
1562 llvm::cl::values(
1563#define ANALYSIS_STORE(NAME, CMDFLAG, DESC, CREATFN)\
1564clEnumValN(NAME##Model, CMDFLAG, DESC),
Eli Friedman0ec78fa2009-05-19 21:10:40 +00001565#include "clang/Frontend/Analyses.def"
Eli Friedmane71b85f2009-05-19 10:18:02 +00001566clEnumValEnd));
1567
Mike Stump1eb44332009-09-09 15:08:12 +00001568static llvm::cl::opt<AnalysisConstraints>
Eli Friedmane71b85f2009-05-19 10:18:02 +00001569AnalysisConstraintsOpt("analyzer-constraints",
1570 llvm::cl::desc("Source Code Analysis - Symbolic Constraint Engines"),
1571 llvm::cl::init(RangeConstraintsModel),
1572 llvm::cl::values(
1573#define ANALYSIS_CONSTRAINTS(NAME, CMDFLAG, DESC, CREATFN)\
1574clEnumValN(NAME##Model, CMDFLAG, DESC),
Eli Friedman0ec78fa2009-05-19 21:10:40 +00001575#include "clang/Frontend/Analyses.def"
Eli Friedmane71b85f2009-05-19 10:18:02 +00001576clEnumValEnd));
1577
1578static llvm::cl::opt<AnalysisDiagClients>
1579AnalysisDiagOpt("analyzer-output",
1580 llvm::cl::desc("Source Code Analysis - Output Options"),
1581 llvm::cl::init(PD_HTML),
1582 llvm::cl::values(
1583#define ANALYSIS_DIAGNOSTICS(NAME, CMDFLAG, DESC, CREATFN, AUTOCREATE)\
1584clEnumValN(PD_##NAME, CMDFLAG, DESC),
Eli Friedman0ec78fa2009-05-19 21:10:40 +00001585#include "clang/Frontend/Analyses.def"
Eli Friedmane71b85f2009-05-19 10:18:02 +00001586clEnumValEnd));
1587
1588static llvm::cl::opt<bool>
1589VisualizeEGDot("analyzer-viz-egraph-graphviz",
1590 llvm::cl::desc("Display exploded graph using GraphViz"));
1591
1592static llvm::cl::opt<bool>
1593VisualizeEGUbi("analyzer-viz-egraph-ubigraph",
1594 llvm::cl::desc("Display exploded graph using Ubigraph"));
1595
1596static llvm::cl::opt<bool>
1597AnalyzeAll("analyzer-opt-analyze-headers",
1598 llvm::cl::desc("Force the static analyzer to analyze "
1599 "functions defined in header files"));
1600
1601static llvm::cl::opt<bool>
1602AnalyzerDisplayProgress("analyzer-display-progress",
1603 llvm::cl::desc("Emit verbose output about the analyzer's progress."));
1604
1605static llvm::cl::opt<bool>
1606PurgeDead("analyzer-purge-dead",
1607 llvm::cl::init(true),
1608 llvm::cl::desc("Remove dead symbols, bindings, and constraints before"
1609 " processing a statement."));
1610
1611static llvm::cl::opt<bool>
1612EagerlyAssume("analyzer-eagerly-assume",
1613 llvm::cl::init(false),
1614 llvm::cl::desc("Eagerly assume the truth/falseness of some "
1615 "symbolic constraints."));
1616
1617static llvm::cl::opt<std::string>
1618AnalyzeSpecificFunction("analyze-function",
1619 llvm::cl::desc("Run analysis on specific function"));
1620
1621static llvm::cl::opt<bool>
1622TrimGraph("trim-egraph",
1623 llvm::cl::desc("Only show error-related paths in the analysis graph"));
1624
1625static AnalyzerOptions ReadAnalyzerOptions() {
1626 AnalyzerOptions Opts;
1627 Opts.AnalysisList = AnalysisList;
1628 Opts.AnalysisStoreOpt = AnalysisStoreOpt;
1629 Opts.AnalysisConstraintsOpt = AnalysisConstraintsOpt;
1630 Opts.AnalysisDiagOpt = AnalysisDiagOpt;
1631 Opts.VisualizeEGDot = VisualizeEGDot;
1632 Opts.VisualizeEGUbi = VisualizeEGUbi;
1633 Opts.AnalyzeAll = AnalyzeAll;
1634 Opts.AnalyzerDisplayProgress = AnalyzerDisplayProgress;
1635 Opts.PurgeDead = PurgeDead;
1636 Opts.EagerlyAssume = EagerlyAssume;
1637 Opts.AnalyzeSpecificFunction = AnalyzeSpecificFunction;
1638 Opts.TrimGraph = TrimGraph;
1639 return Opts;
1640}
1641
1642//===----------------------------------------------------------------------===//
Chris Lattner75a97cb2009-04-17 21:05:01 +00001643// -dump-build-information Stuff
1644//===----------------------------------------------------------------------===//
1645
1646static llvm::cl::opt<std::string>
1647DumpBuildInformation("dump-build-information",
1648 llvm::cl::value_desc("filename"),
1649 llvm::cl::desc("output a dump of some build information to a file"));
1650
1651static llvm::raw_ostream *BuildLogFile = 0;
1652
1653/// LoggingDiagnosticClient - This is a simple diagnostic client that forwards
1654/// all diagnostics to both BuildLogFile and a chained DiagnosticClient.
1655namespace {
1656class LoggingDiagnosticClient : public DiagnosticClient {
1657 llvm::OwningPtr<DiagnosticClient> Chain1;
1658 llvm::OwningPtr<DiagnosticClient> Chain2;
1659public:
Mike Stump1eb44332009-09-09 15:08:12 +00001660
Chris Lattner75a97cb2009-04-17 21:05:01 +00001661 LoggingDiagnosticClient(DiagnosticClient *Normal) {
1662 // Output diags both where requested...
1663 Chain1.reset(Normal);
1664 // .. and to our log file.
1665 Chain2.reset(new TextDiagnosticPrinter(*BuildLogFile,
1666 !NoShowColumn,
1667 !NoCaretDiagnostics,
1668 !NoShowLocation,
1669 PrintSourceRangeInfo,
Chris Lattneraa5bf2e2009-04-19 07:44:08 +00001670 PrintDiagnosticOption,
Douglas Gregorfffd93f2009-05-01 21:53:04 +00001671 !NoDiagnosticsFixIt,
Nate Begeman4e3629e2009-06-25 22:43:10 +00001672 MessageLength));
Chris Lattner75a97cb2009-04-17 21:05:01 +00001673 }
Mike Stump1eb44332009-09-09 15:08:12 +00001674
Chris Lattner75a97cb2009-04-17 21:05:01 +00001675 virtual void setLangOptions(const LangOptions *LO) {
1676 Chain1->setLangOptions(LO);
1677 Chain2->setLangOptions(LO);
1678 }
Mike Stump1eb44332009-09-09 15:08:12 +00001679
Chris Lattner75a97cb2009-04-17 21:05:01 +00001680 virtual bool IncludeInDiagnosticCounts() const {
1681 return Chain1->IncludeInDiagnosticCounts();
1682 }
1683
1684 virtual void HandleDiagnostic(Diagnostic::Level DiagLevel,
1685 const DiagnosticInfo &Info) {
1686 Chain1->HandleDiagnostic(DiagLevel, Info);
1687 Chain2->HandleDiagnostic(DiagLevel, Info);
1688 }
1689};
1690} // end anonymous namespace.
1691
1692static void SetUpBuildDumpLog(unsigned argc, char **argv,
1693 llvm::OwningPtr<DiagnosticClient> &DiagClient) {
Mike Stump1eb44332009-09-09 15:08:12 +00001694
Chris Lattner75a97cb2009-04-17 21:05:01 +00001695 std::string ErrorInfo;
Chris Lattner92bcc272009-08-23 02:59:41 +00001696 BuildLogFile = new llvm::raw_fd_ostream(DumpBuildInformation.c_str(),
Dan Gohmanb044c472009-08-25 15:36:09 +00001697 ErrorInfo);
Mike Stump1eb44332009-09-09 15:08:12 +00001698
Chris Lattner75a97cb2009-04-17 21:05:01 +00001699 if (!ErrorInfo.empty()) {
1700 llvm::errs() << "error opening -dump-build-information file '"
1701 << DumpBuildInformation << "', option ignored!\n";
1702 delete BuildLogFile;
1703 BuildLogFile = 0;
1704 DumpBuildInformation = "";
1705 return;
1706 }
1707
1708 (*BuildLogFile) << "clang-cc command line arguments: ";
1709 for (unsigned i = 0; i != argc; ++i)
1710 (*BuildLogFile) << argv[i] << ' ';
1711 (*BuildLogFile) << '\n';
Mike Stump1eb44332009-09-09 15:08:12 +00001712
Chris Lattner75a97cb2009-04-17 21:05:01 +00001713 // LoggingDiagnosticClient - Insert a new logging diagnostic client in between
1714 // the diagnostic producers and the normal receiver.
1715 DiagClient.reset(new LoggingDiagnosticClient(DiagClient.take()));
1716}
1717
1718
1719
1720//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +00001721// Main driver
1722//===----------------------------------------------------------------------===//
1723
Chris Lattner92bcc272009-08-23 02:59:41 +00001724static llvm::raw_ostream *ComputeOutFile(const std::string &InFile,
1725 const char *Extension,
Eli Friedman66d6f042009-05-18 22:20:00 +00001726 bool Binary,
1727 llvm::sys::Path& OutPath) {
Chris Lattner92bcc272009-08-23 02:59:41 +00001728 llvm::raw_ostream *Ret;
Eli Friedman66d6f042009-05-18 22:20:00 +00001729 std::string OutFile;
Chris Lattner92bcc272009-08-23 02:59:41 +00001730 if (!OutputFile.empty())
Eli Friedman66d6f042009-05-18 22:20:00 +00001731 OutFile = OutputFile;
Chris Lattner92bcc272009-08-23 02:59:41 +00001732 else if (InFile == "-") {
1733 OutFile = "-";
Eli Friedman66d6f042009-05-18 22:20:00 +00001734 } else if (Extension) {
1735 llvm::sys::Path Path(InFile);
1736 Path.eraseSuffix();
1737 Path.appendSuffix(Extension);
Chris Lattnerd57a7ef2009-08-23 22:45:33 +00001738 OutFile = Path.str();
Eli Friedman66d6f042009-05-18 22:20:00 +00001739 } else {
Chris Lattner92bcc272009-08-23 02:59:41 +00001740 OutFile = "-";
Chris Lattner8a5c8092009-02-18 01:20:05 +00001741 }
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +00001742
Chris Lattner92bcc272009-08-23 02:59:41 +00001743 std::string Error;
1744 Ret = new llvm::raw_fd_ostream(OutFile.c_str(), Error,
Dan Gohmanb044c472009-08-25 15:36:09 +00001745 (Binary ? llvm::raw_fd_ostream::F_Binary : 0));
Chris Lattner92bcc272009-08-23 02:59:41 +00001746 if (!Error.empty()) {
1747 // FIXME: Don't fail this way.
1748 llvm::errs() << "ERROR: " << Error << "\n";
1749 ::exit(1);
Ted Kremenekdb094a22007-12-05 18:27:04 +00001750 }
Mike Stump1eb44332009-09-09 15:08:12 +00001751
Chris Lattner92bcc272009-08-23 02:59:41 +00001752 if (OutFile != "-")
1753 OutPath = OutFile;
Eli Friedman66d6f042009-05-18 22:20:00 +00001754
1755 return Ret;
Ted Kremenekdb094a22007-12-05 18:27:04 +00001756}
1757
Reid Spencer5f016e22007-07-11 17:01:13 +00001758/// ProcessInputFile - Process a single input file with the specified state.
1759///
Ted Kremenek339b9c22008-04-17 22:31:54 +00001760static void ProcessInputFile(Preprocessor &PP, PreprocessorFactory &PPF,
Daniel Dunbar868bd0a2009-05-06 03:16:41 +00001761 const std::string &InFile, ProgActions PA,
Owen Anderson42253cc2009-07-01 17:00:06 +00001762 const llvm::StringMap<bool> &Features,
Owen Anderson8f1ca782009-07-01 23:14:14 +00001763 llvm::LLVMContext& Context) {
Eli Friedman66d6f042009-05-18 22:20:00 +00001764 llvm::OwningPtr<llvm::raw_ostream> OS;
Ted Kremenek7e7e6252008-08-08 02:46:37 +00001765 llvm::OwningPtr<ASTConsumer> Consumer;
Chris Lattnerbd247762007-07-22 06:05:44 +00001766 bool ClearSourceMgr = false;
Douglas Gregor558cb562009-04-02 01:08:08 +00001767 FixItRewriter *FixItRewrite = 0;
Douglas Gregorf807fe02009-04-14 16:27:31 +00001768 bool CompleteTranslationUnit = true;
Eli Friedman66d6f042009-05-18 22:20:00 +00001769 llvm::sys::Path OutPath;
Douglas Gregor558cb562009-04-02 01:08:08 +00001770
Ted Kremenek85888962008-10-21 00:54:44 +00001771 switch (PA) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001772 default:
Eli Friedman66d6f042009-05-18 22:20:00 +00001773 fprintf(stderr, "Unexpected program action!\n");
1774 HadErrors = true;
1775 return;
1776
1777 case ASTPrint:
1778 OS.reset(ComputeOutFile(InFile, 0, false, OutPath));
1779 Consumer.reset(CreateASTPrinter(OS.get()));
1780 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001781
Douglas Gregoree75c052009-05-21 20:55:50 +00001782 case ASTPrintXML:
1783 OS.reset(ComputeOutFile(InFile, "xml", false, OutPath));
1784 Consumer.reset(CreateASTPrinterXML(OS.get()));
1785 break;
1786
Eli Friedman66d6f042009-05-18 22:20:00 +00001787 case ASTDump:
Douglas Gregor4fe0c8e2009-05-30 00:08:05 +00001788 Consumer.reset(CreateASTDumper());
Eli Friedman66d6f042009-05-18 22:20:00 +00001789 break;
1790
Eli Friedman66d6f042009-05-18 22:20:00 +00001791 case ASTView:
Douglas Gregor4fe0c8e2009-05-30 00:08:05 +00001792 Consumer.reset(CreateASTViewer());
Eli Friedman66d6f042009-05-18 22:20:00 +00001793 break;
1794
1795 case PrintDeclContext:
1796 Consumer.reset(CreateDeclContextPrinter());
1797 break;
1798
1799 case EmitHTML:
1800 OS.reset(ComputeOutFile(InFile, 0, true, OutPath));
1801 Consumer.reset(CreateHTMLPrinter(OS.get(), PP.getDiagnostics(), &PP, &PPF));
1802 break;
1803
1804 case InheritanceView:
1805 Consumer.reset(CreateInheritanceViewer(InheritanceViewCls));
1806 break;
1807
1808 case EmitAssembly:
1809 case EmitLLVM:
Mike Stump1eb44332009-09-09 15:08:12 +00001810 case EmitBC:
Eli Friedman66d6f042009-05-18 22:20:00 +00001811 case EmitLLVMOnly: {
1812 BackendAction Act;
1813 if (ProgAction == EmitAssembly) {
1814 Act = Backend_EmitAssembly;
1815 OS.reset(ComputeOutFile(InFile, "s", true, OutPath));
1816 } else if (ProgAction == EmitLLVM) {
1817 Act = Backend_EmitLL;
1818 OS.reset(ComputeOutFile(InFile, "ll", true, OutPath));
1819 } else if (ProgAction == EmitLLVMOnly) {
1820 Act = Backend_EmitNothing;
1821 } else {
1822 Act = Backend_EmitBC;
1823 OS.reset(ComputeOutFile(InFile, "bc", true, OutPath));
Ted Kremenekdb094a22007-12-05 18:27:04 +00001824 }
Ted Kremenekfdfc1982007-12-19 22:24:34 +00001825
Eli Friedman66d6f042009-05-18 22:20:00 +00001826 CompileOptions Opts;
1827 InitializeCompileOptions(Opts, PP.getLangOptions(), Features);
1828 Consumer.reset(CreateBackendConsumer(Act, PP.getDiagnostics(),
1829 PP.getLangOptions(), Opts, InFile,
Owen Anderson42253cc2009-07-01 17:00:06 +00001830 OS.get(), Context));
Ted Kremenekdb094a22007-12-05 18:27:04 +00001831 break;
Eli Friedman66d6f042009-05-18 22:20:00 +00001832 }
1833
1834 case GeneratePCH:
Douglas Gregore650c8c2009-07-07 00:12:59 +00001835 if (RelocatablePCH.getValue() && !isysroot.getNumOccurrences()) {
1836 PP.Diag(SourceLocation(), diag::err_relocatable_without_without_isysroot);
1837 RelocatablePCH.setValue(false);
1838 }
Mike Stump1eb44332009-09-09 15:08:12 +00001839
Eli Friedman66d6f042009-05-18 22:20:00 +00001840 OS.reset(ComputeOutFile(InFile, 0, true, OutPath));
Douglas Gregore650c8c2009-07-07 00:12:59 +00001841 if (RelocatablePCH.getValue())
1842 Consumer.reset(CreatePCHGenerator(PP, OS.get(), isysroot.c_str()));
1843 else
1844 Consumer.reset(CreatePCHGenerator(PP, OS.get()));
Eli Friedman66d6f042009-05-18 22:20:00 +00001845 CompleteTranslationUnit = false;
1846 break;
1847
1848 case RewriteObjC:
1849 OS.reset(ComputeOutFile(InFile, "cpp", true, OutPath));
Eli Friedmanbce831b2009-05-18 22:29:17 +00001850 Consumer.reset(CreateObjCRewriter(InFile, OS.get(), PP.getDiagnostics(),
Eli Friedmanc6d656e2009-05-18 22:39:16 +00001851 PP.getLangOptions(),
1852 SilenceRewriteMacroWarning));
Eli Friedman66d6f042009-05-18 22:20:00 +00001853 break;
1854
1855 case RewriteBlocks:
1856 Consumer.reset(CreateBlockRewriter(InFile, PP.getDiagnostics(),
1857 PP.getLangOptions()));
1858 break;
1859
Eli Friedmane71b85f2009-05-19 10:18:02 +00001860 case RunAnalysis: {
Eli Friedman66d6f042009-05-18 22:20:00 +00001861 Consumer.reset(CreateAnalysisConsumer(PP.getDiagnostics(), &PP, &PPF,
Eli Friedmane71b85f2009-05-19 10:18:02 +00001862 PP.getLangOptions(), OutputFile,
1863 ReadAnalyzerOptions()));
Eli Friedman66d6f042009-05-18 22:20:00 +00001864 break;
Eli Friedmane71b85f2009-05-19 10:18:02 +00001865 }
Eli Friedman66d6f042009-05-18 22:20:00 +00001866
Chris Lattnerc106c102008-10-12 05:03:36 +00001867 case DumpRawTokens: {
Chris Lattner47099742009-02-18 01:51:21 +00001868 llvm::TimeRegion Timer(ClangFrontendTimer);
Chris Lattnerc106c102008-10-12 05:03:36 +00001869 SourceManager &SM = PP.getSourceManager();
Chris Lattnerc106c102008-10-12 05:03:36 +00001870 // Start lexing the specified input file.
Chris Lattner025c3a62009-01-17 07:35:14 +00001871 Lexer RawLex(SM.getMainFileID(), SM, PP.getLangOptions());
Chris Lattnerc106c102008-10-12 05:03:36 +00001872 RawLex.SetKeepWhitespaceMode(true);
1873
1874 Token RawTok;
Chris Lattnerc106c102008-10-12 05:03:36 +00001875 RawLex.LexFromRawLexer(RawTok);
1876 while (RawTok.isNot(tok::eof)) {
1877 PP.DumpToken(RawTok, true);
1878 fprintf(stderr, "\n");
1879 RawLex.LexFromRawLexer(RawTok);
1880 }
1881 ClearSourceMgr = true;
1882 break;
1883 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001884 case DumpTokens: { // Token dump mode.
Chris Lattner47099742009-02-18 01:51:21 +00001885 llvm::TimeRegion Timer(ClangFrontendTimer);
Chris Lattnerd2177732007-07-20 16:59:19 +00001886 Token Tok;
Chris Lattnerc106c102008-10-12 05:03:36 +00001887 // Start preprocessing the specified input file.
Ted Kremenek95041a22007-12-19 22:51:13 +00001888 PP.EnterMainSourceFile();
Reid Spencer5f016e22007-07-11 17:01:13 +00001889 do {
1890 PP.Lex(Tok);
1891 PP.DumpToken(Tok, true);
1892 fprintf(stderr, "\n");
Chris Lattner057aaf62007-10-09 18:03:42 +00001893 } while (Tok.isNot(tok::eof));
Chris Lattnerbd247762007-07-22 06:05:44 +00001894 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001895 break;
1896 }
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001897 case RunPreprocessorOnly:
Reid Spencer5f016e22007-07-11 17:01:13 +00001898 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001899
Douglas Gregorbf1bd6e2009-04-02 23:43:50 +00001900 case GeneratePTH: {
Chris Lattner47099742009-02-18 01:51:21 +00001901 llvm::TimeRegion Timer(ClangFrontendTimer);
Eli Friedmanf54fce82009-05-19 01:02:07 +00001902 if (OutputFile.empty() || OutputFile == "-") {
1903 // FIXME: Don't fail this way.
1904 // FIXME: Verify that we can actually seek in the given file.
Chris Lattner92bcc272009-08-23 02:59:41 +00001905 llvm::errs() << "ERROR: PTH requires an seekable file for output!\n";
Eli Friedmanf54fce82009-05-19 01:02:07 +00001906 ::exit(1);
1907 }
1908 OS.reset(ComputeOutFile(InFile, 0, true, OutPath));
1909 CacheTokens(PP, static_cast<llvm::raw_fd_ostream*>(OS.get()));
Ted Kremenek85888962008-10-21 00:54:44 +00001910 ClearSourceMgr = true;
1911 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001912 }
Douglas Gregor6ab35242009-04-09 21:40:53 +00001913
Chris Lattnercc7dea82009-04-27 22:02:30 +00001914 case PrintPreprocessedInput:
Eli Friedmanf54fce82009-05-19 01:02:07 +00001915 OS.reset(ComputeOutFile(InFile, 0, true, OutPath));
Reid Spencer5f016e22007-07-11 17:01:13 +00001916 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001917
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001918 case ParseNoop:
Reid Spencer5f016e22007-07-11 17:01:13 +00001919 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001920
Chris Lattner47099742009-02-18 01:51:21 +00001921 case ParsePrintCallbacks: {
1922 llvm::TimeRegion Timer(ClangFrontendTimer);
Eli Friedmanf54fce82009-05-19 01:02:07 +00001923 OS.reset(ComputeOutFile(InFile, 0, true, OutPath));
1924 ParseFile(PP, CreatePrintParserActionsAction(PP, OS.get()));
Chris Lattnerbd247762007-07-22 06:05:44 +00001925 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001926 break;
Chris Lattner47099742009-02-18 01:51:21 +00001927 }
1928
1929 case ParseSyntaxOnly: { // -fsyntax-only
1930 llvm::TimeRegion Timer(ClangFrontendTimer);
Ted Kremenek7e7e6252008-08-08 02:46:37 +00001931 Consumer.reset(new ASTConsumer());
Ted Kremenek2bf55142007-09-17 20:49:30 +00001932 break;
Chris Lattner47099742009-02-18 01:51:21 +00001933 }
Mike Stump1eb44332009-09-09 15:08:12 +00001934
Chris Lattnerb57e3d42008-05-08 06:52:13 +00001935 case RewriteMacros:
Eli Friedmanf54fce82009-05-19 01:02:07 +00001936 OS.reset(ComputeOutFile(InFile, 0, true, OutPath));
1937 RewriteMacrosInInput(PP, OS.get());
Chris Lattnerb57e3d42008-05-08 06:52:13 +00001938 ClearSourceMgr = true;
1939 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001940
Eli Friedmanf54fce82009-05-19 01:02:07 +00001941 case RewriteTest:
1942 OS.reset(ComputeOutFile(InFile, 0, true, OutPath));
1943 DoRewriteTest(PP, OS.get());
Chris Lattnerb13c5ee2008-10-12 05:29:20 +00001944 ClearSourceMgr = true;
1945 break;
Douglas Gregor558cb562009-04-02 01:08:08 +00001946
1947 case FixIt:
1948 llvm::TimeRegion Timer(ClangFrontendTimer);
1949 Consumer.reset(new ASTConsumer());
Douglas Gregorde4bf6a2009-04-02 17:13:00 +00001950 FixItRewrite = new FixItRewriter(PP.getDiagnostics(),
Chris Lattner2c78b872009-04-14 23:22:57 +00001951 PP.getSourceManager(),
1952 PP.getLangOptions());
Douglas Gregor558cb562009-04-02 01:08:08 +00001953 break;
Chris Lattner47099742009-02-18 01:51:21 +00001954 }
Ted Kremenek46157b52009-01-28 04:29:29 +00001955
Chris Lattner1aee61a2009-04-27 21:25:27 +00001956 if (FixItAtLocations.size() > 0) {
1957 // Even without the "-fixit" flag, with may have some specific
1958 // locations where the user has requested fixes. Process those
1959 // locations now.
1960 if (!FixItRewrite)
1961 FixItRewrite = new FixItRewriter(PP.getDiagnostics(),
1962 PP.getSourceManager(),
1963 PP.getLangOptions());
Chris Lattner9ecd26a2009-03-28 01:37:17 +00001964
Chris Lattner1aee61a2009-04-27 21:25:27 +00001965 bool AddedFixitLocation = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001966 for (unsigned Idx = 0, Last = FixItAtLocations.size();
Chris Lattner1aee61a2009-04-27 21:25:27 +00001967 Idx != Last; ++Idx) {
1968 RequestedSourceLocation Requested;
Argyrios Kyrtzidis34d25d82009-06-23 22:01:39 +00001969 if (ResolveParsedLocation(FixItAtLocations[Idx],
1970 PP.getFileManager(), Requested)) {
Chris Lattner1aee61a2009-04-27 21:25:27 +00001971 fprintf(stderr, "FIX-IT could not find file \"%s\"\n",
1972 FixItAtLocations[Idx].FileName.c_str());
1973 } else {
1974 FixItRewrite->addFixItLocation(Requested);
1975 AddedFixitLocation = true;
Douglas Gregor26df2f02009-04-02 19:05:20 +00001976 }
1977 }
1978
Chris Lattner1aee61a2009-04-27 21:25:27 +00001979 if (!AddedFixitLocation) {
1980 // All of the fix-it locations were bad. Don't fix anything.
1981 delete FixItRewrite;
1982 FixItRewrite = 0;
1983 }
1984 }
1985
1986 llvm::OwningPtr<ASTContext> ContextOwner;
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001987 if (Consumer)
Chris Lattner9ecd26a2009-03-28 01:37:17 +00001988 ContextOwner.reset(new ASTContext(PP.getLangOptions(),
1989 PP.getSourceManager(),
1990 PP.getTargetInfo(),
1991 PP.getIdentifierTable(),
1992 PP.getSelectorTable(),
Chris Lattner1b63e4f2009-06-14 01:54:56 +00001993 PP.getBuiltinInfo(),
Douglas Gregor2deaea32009-04-22 18:49:13 +00001994 /* FreeMemory = */ !DisableFree,
Chris Lattner1b63e4f2009-06-14 01:54:56 +00001995 /* size_reserve = */0));
Mike Stump1eb44332009-09-09 15:08:12 +00001996
Chris Lattnercc7dea82009-04-27 22:02:30 +00001997 llvm::OwningPtr<PCHReader> Reader;
1998 llvm::OwningPtr<ExternalASTSource> Source;
Mike Stump1eb44332009-09-09 15:08:12 +00001999
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002000 if (!ImplicitIncludePCH.empty()) {
Douglas Gregore650c8c2009-07-07 00:12:59 +00002001 // If the user specified -isysroot, it will be used for relocatable PCH
2002 // files.
2003 const char *isysrootPCH = 0;
2004 if (isysroot.getNumOccurrences() != 0)
2005 isysrootPCH = isysroot.c_str();
Mike Stump1eb44332009-09-09 15:08:12 +00002006
Douglas Gregore650c8c2009-07-07 00:12:59 +00002007 Reader.reset(new PCHReader(PP, ContextOwner.get(), isysrootPCH));
Mike Stump1eb44332009-09-09 15:08:12 +00002008
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002009 // The user has asked us to include a precompiled header. Load
2010 // the precompiled header into the AST context.
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002011 switch (Reader->ReadPCH(ImplicitIncludePCH)) {
2012 case PCHReader::Success: {
Douglas Gregore721f952009-04-28 18:58:38 +00002013 // Set the predefines buffer as suggested by the PCH
2014 // reader. Typically, the predefines buffer will be empty.
2015 PP.setPredefines(Reader->getSuggestedPredefines());
2016
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002017 // Attach the PCH reader to the AST context as an external AST
2018 // source, so that declarations will be deserialized from the
2019 // PCH file as needed.
Chris Lattnercc7dea82009-04-27 22:02:30 +00002020 if (ContextOwner) {
2021 Source.reset(Reader.take());
Douglas Gregore1d918e2009-04-10 23:10:45 +00002022 ContextOwner->setExternalSource(Source);
Chris Lattnercc7dea82009-04-27 22:02:30 +00002023 }
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002024 break;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002025 }
2026
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002027 case PCHReader::Failure:
2028 // Unrecoverable failure: don't even try to process the input
2029 // file.
2030 return;
2031
2032 case PCHReader::IgnorePCH:
Douglas Gregor1ab86ac2009-04-28 22:01:16 +00002033 // No suitable PCH file could be found. Return an error.
2034 return;
2035
2036#if 0
2037 // FIXME: We can recover from failed attempts to load PCH
2038 // files. This code will do so, if we ever want to enable it.
2039
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002040 // We delayed the initialization of builtins in the hope of
2041 // loading the PCH file. Since the PCH file could not be
2042 // loaded, initialize builtins now.
2043 if (ContextOwner)
2044 ContextOwner->InitializeBuiltins(PP.getIdentifierTable());
Douglas Gregor1ab86ac2009-04-28 22:01:16 +00002045#endif
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002046 }
2047
2048 // Finish preprocessor initialization. We do this now (rather
2049 // than earlier) because this initialization creates new source
2050 // location entries in the source manager, which must come after
2051 // the source location entries for the PCH file.
2052 if (InitializeSourceManager(PP, InFile))
2053 return;
Ted Kremenek46157b52009-01-28 04:29:29 +00002054 }
Daniel Dunbar879c3ea2008-10-27 22:03:52 +00002055
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002056
2057 // If we have an ASTConsumer, run the parser with it.
2058 if (Consumer)
Mike Stump1eb44332009-09-09 15:08:12 +00002059 ParseAST(PP, Consumer.get(), *ContextOwner.get(), Stats,
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002060 CompleteTranslationUnit);
2061
2062 if (PA == RunPreprocessorOnly) { // Just lex as fast as we can, no output.
2063 llvm::TimeRegion Timer(ClangFrontendTimer);
2064 Token Tok;
2065 // Start parsing the specified input file.
2066 PP.EnterMainSourceFile();
2067 do {
2068 PP.Lex(Tok);
2069 } while (Tok.isNot(tok::eof));
2070 ClearSourceMgr = true;
2071 } else if (PA == ParseNoop) { // -parse-noop
2072 llvm::TimeRegion Timer(ClangFrontendTimer);
2073 ParseFile(PP, new MinimalAction(PP));
2074 ClearSourceMgr = true;
Chris Lattnercc7dea82009-04-27 22:02:30 +00002075 } else if (PA == PrintPreprocessedInput){ // -E mode.
2076 llvm::TimeRegion Timer(ClangFrontendTimer);
Eli Friedman12d3b1d2009-05-19 03:06:47 +00002077 if (DumpMacros)
2078 DoPrintMacros(PP, OS.get());
2079 else
2080 DoPrintPreprocessedInput(PP, OS.get(), EnableCommentOutput,
2081 EnableMacroCommentOutput,
2082 DisableLineMarkers, DumpDefines);
Chris Lattnercc7dea82009-04-27 22:02:30 +00002083 ClearSourceMgr = true;
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002084 }
Mike Stump1eb44332009-09-09 15:08:12 +00002085
Chris Lattner1aee61a2009-04-27 21:25:27 +00002086 if (FixItRewrite)
2087 FixItRewrite->WriteFixedFile(InFile, OutputFile);
Daniel Dunbar70186ab2009-07-29 02:40:09 +00002088
2089 // Disable the consumer prior to the context, the consumer may perform actions
2090 // in its destructor which require the context.
2091 if (DisableFree)
2092 Consumer.take();
2093 else
2094 Consumer.reset();
Mike Stump1eb44332009-09-09 15:08:12 +00002095
Chris Lattner1aee61a2009-04-27 21:25:27 +00002096 // If in -disable-free mode, don't deallocate ASTContext.
2097 if (DisableFree)
2098 ContextOwner.take();
2099 else
2100 ContextOwner.reset(); // Delete ASTContext
Eli Friedman66d6f042009-05-18 22:20:00 +00002101
Daniel Dunbar879c3ea2008-10-27 22:03:52 +00002102 if (VerifyDiagnostics)
Daniel Dunbar276373d2008-10-27 22:10:13 +00002103 if (CheckDiagnostics(PP))
2104 exit(1);
Chris Lattnere66b65c2008-02-06 01:42:25 +00002105
Reid Spencer5f016e22007-07-11 17:01:13 +00002106 if (Stats) {
Ted Kremenekfdfc1982007-12-19 22:24:34 +00002107 fprintf(stderr, "\nSTATISTICS FOR '%s':\n", InFile.c_str());
Reid Spencer5f016e22007-07-11 17:01:13 +00002108 PP.PrintStats();
2109 PP.getIdentifierTable().PrintStats();
Chris Lattnerdee73592007-12-15 20:48:40 +00002110 PP.getHeaderSearchInfo().PrintStats();
Ted Kremenek1b95a652009-01-09 18:20:21 +00002111 PP.getSourceManager().PrintStats();
Reid Spencer5f016e22007-07-11 17:01:13 +00002112 fprintf(stderr, "\n");
2113 }
Chris Lattnerbd247762007-07-22 06:05:44 +00002114
Mike Stump1eb44332009-09-09 15:08:12 +00002115 // For a multi-file compilation, some things are ok with nuking the source
Chris Lattnerbd247762007-07-22 06:05:44 +00002116 // manager tables, other require stable fileid/macroid's across multiple
2117 // files.
Chris Lattnerdee73592007-12-15 20:48:40 +00002118 if (ClearSourceMgr)
2119 PP.getSourceManager().clearIDTables();
Daniel Dunbard68ba0e2008-11-11 06:35:39 +00002120
Eli Friedman66d6f042009-05-18 22:20:00 +00002121 // Always delete the output stream because we don't want to leak file
2122 // handles. Also, we don't want to try to erase an open file.
2123 OS.reset();
2124
2125 if ((HadErrors || (PP.getDiagnostics().getNumErrors() != 0)) &&
2126 !OutPath.isEmpty()) {
2127 // If we had errors, try to erase the output file.
2128 OutPath.eraseFromDisk();
2129 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002130}
2131
2132static llvm::cl::list<std::string>
2133InputFilenames(llvm::cl::Positional, llvm::cl::desc("<input files>"));
2134
Daniel Dunbar70121eb2009-08-10 03:40:28 +00002135static void LLVMErrorHandler(void *UserData, const std::string &Message) {
2136 Diagnostic &Diags = *static_cast<Diagnostic*>(UserData);
2137
2138 Diags.Report(FullSourceLoc(), diag::err_fe_error_backend) << Message;
2139
2140 // We cannot recover from llvm errors.
2141 exit(1);
2142}
2143
Reid Spencer5f016e22007-07-11 17:01:13 +00002144int main(int argc, char **argv) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002145 llvm::sys::PrintStackTraceOnErrorSignal();
Chris Lattner09e94a32009-03-04 21:41:39 +00002146 llvm::PrettyStackTraceProgram X(argc, argv);
Owen Andersond7200462009-07-16 00:14:12 +00002147 llvm::LLVMContext &Context = llvm::getGlobalContext();
Daniel Dunbard6970812009-09-02 23:20:15 +00002148
Daniel Dunbar4d861512009-09-03 04:54:12 +00002149 // Initialize targets first, so that --version shows registered targets.
Chris Lattner2fe11942009-06-17 17:25:50 +00002150 llvm::InitializeAllTargets();
2151 llvm::InitializeAllAsmPrinters();
Daniel Dunbard6970812009-09-02 23:20:15 +00002152
2153 llvm::cl::ParseCommandLineOptions(argc, argv,
2154 "LLVM 'Clang' Compiler: http://clang.llvm.org\n");
Mike Stump1eb44332009-09-09 15:08:12 +00002155
Chris Lattner47099742009-02-18 01:51:21 +00002156 if (TimeReport)
2157 ClangFrontendTimer = new llvm::Timer("Clang front-end time");
Mike Stump1eb44332009-09-09 15:08:12 +00002158
Daniel Dunbar08e6dc62009-05-28 16:37:33 +00002159 if (Verbose)
Mike Stump3cbf5a02009-09-15 21:49:22 +00002160 llvm::errs() << "clang-cc version " CLANG_VERSION_STRING
2161 << " based upon " << PACKAGE_STRING
Daniel Dunbar2e30e592009-09-04 17:43:10 +00002162 << " hosted on " << llvm::sys::getHostTriple() << "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00002163
Reid Spencer5f016e22007-07-11 17:01:13 +00002164 // If no input was specified, read from stdin.
2165 if (InputFilenames.empty())
2166 InputFilenames.push_back("-");
Douglas Gregor68a0d782009-05-02 00:03:46 +00002167
Ted Kremenek31e703b2007-12-11 23:28:38 +00002168 // Create the diagnostic client for reporting errors or for
2169 // implementing -verify.
Chris Lattner409d4e72009-04-17 20:40:01 +00002170 llvm::OwningPtr<DiagnosticClient> DiagClient;
2171 if (VerifyDiagnostics) {
2172 // When checking diagnostics, just buffer them up.
2173 DiagClient.reset(new TextDiagnosticBuffer());
2174 if (InputFilenames.size() != 1) {
2175 fprintf(stderr, "-verify only works on single input files for now.\n");
2176 return 1;
2177 }
2178 if (!HTMLDiag.empty()) {
2179 fprintf(stderr, "-verify and -html-diags don't work together\n");
2180 return 1;
2181 }
2182 } else if (HTMLDiag.empty()) {
Ted Kremenekb4398aa2008-08-07 17:49:57 +00002183 // Print diagnostics to stderr by default.
Douglas Gregor68a0d782009-05-02 00:03:46 +00002184
2185 // If -fmessage-length=N was not specified, determine whether this
2186 // is a terminal and, if so, implicitly define -fmessage-length
2187 // appropriately.
2188 if (MessageLength.getNumOccurrences() == 0)
Douglas Gregor67187ce2009-05-11 18:06:49 +00002189 MessageLength.setValue(llvm::sys::Process::StandardErrColumns());
Douglas Gregor68a0d782009-05-02 00:03:46 +00002190
Torok Edwin603fca72009-06-04 07:18:23 +00002191 if (!NoColorDiagnostic) {
2192 NoColorDiagnostic.setValue(!llvm::sys::Process::StandardErrHasColors());
2193 }
2194
Chris Lattner409d4e72009-04-17 20:40:01 +00002195 DiagClient.reset(new TextDiagnosticPrinter(llvm::errs(),
Chris Lattnera03a5b52008-11-19 06:56:25 +00002196 !NoShowColumn,
Chris Lattner65f5e642009-01-30 19:01:41 +00002197 !NoCaretDiagnostics,
Chris Lattner1fbee5d2009-03-13 01:08:23 +00002198 !NoShowLocation,
Chris Lattnerd51d74a2009-04-16 05:44:38 +00002199 PrintSourceRangeInfo,
Chris Lattneraa5bf2e2009-04-19 07:44:08 +00002200 PrintDiagnosticOption,
Douglas Gregorfffd93f2009-05-01 21:53:04 +00002201 !NoDiagnosticsFixIt,
Torok Edwin603fca72009-06-04 07:18:23 +00002202 MessageLength,
2203 !NoColorDiagnostic));
Ted Kremenekb4398aa2008-08-07 17:49:57 +00002204 } else {
Chris Lattner409d4e72009-04-17 20:40:01 +00002205 DiagClient.reset(CreateHTMLDiagnosticClient(HTMLDiag));
Reid Spencer5f016e22007-07-11 17:01:13 +00002206 }
Mike Stump1eb44332009-09-09 15:08:12 +00002207
Chris Lattner75a97cb2009-04-17 21:05:01 +00002208 if (!DumpBuildInformation.empty()) {
2209 if (!HTMLDiag.empty()) {
2210 fprintf(stderr,
2211 "-dump-build-information and -html-diags don't work together\n");
2212 return 1;
2213 }
Mike Stump1eb44332009-09-09 15:08:12 +00002214
Chris Lattner75a97cb2009-04-17 21:05:01 +00002215 SetUpBuildDumpLog(argc, argv, DiagClient);
2216 }
Mike Stump1eb44332009-09-09 15:08:12 +00002217
Ted Kremenekb4398aa2008-08-07 17:49:57 +00002218
Reid Spencer5f016e22007-07-11 17:01:13 +00002219 // Configure our handling of diagnostics.
Ted Kremenekb4398aa2008-08-07 17:49:57 +00002220 Diagnostic Diags(DiagClient.get());
Eli Friedman0eeb86e2009-05-19 01:17:04 +00002221 if (ProcessWarningOptions(Diags, OptWarnings, OptPedantic, OptPedanticErrors,
2222 OptNoWarnings))
Sebastian Redl63a9e0f2009-03-06 17:41:35 +00002223 return 1;
Ted Kremenek31e703b2007-12-11 23:28:38 +00002224
Daniel Dunbar70121eb2009-08-10 03:40:28 +00002225 // Set an error handler, so that any LLVM backend diagnostics go through our
2226 // error handler.
2227 llvm::llvm_install_error_handler(LLVMErrorHandler,
2228 static_cast<void*>(&Diags));
2229
Chris Lattner4f037832007-12-05 23:24:17 +00002230 // -I- is a deprecated GCC feature, scan for it and reject it.
2231 for (unsigned i = 0, e = I_dirs.size(); i != e; ++i) {
2232 if (I_dirs[i] == "-") {
Mike Stump1eb44332009-09-09 15:08:12 +00002233 Diags.Report(FullSourceLoc(), diag::err_pp_I_dash_not_supported);
Chris Lattner4f037832007-12-05 23:24:17 +00002234 I_dirs.erase(I_dirs.begin()+i);
2235 --i;
2236 }
2237 }
Chris Lattner11215192008-03-14 06:12:05 +00002238
2239 // Get information about the target being compiled for.
Chris Lattner2f60af72009-09-12 22:45:58 +00002240 llvm::Triple Triple = CreateTargetTriple();
2241 llvm::OwningPtr<TargetInfo>
2242 Target(TargetInfo::CreateTargetInfo(Triple.getTriple()));
Mike Stump1eb44332009-09-09 15:08:12 +00002243
Chris Lattner11215192008-03-14 06:12:05 +00002244 if (Target == 0) {
Mike Stump1eb44332009-09-09 15:08:12 +00002245 Diags.Report(FullSourceLoc(), diag::err_fe_unknown_triple)
Chris Lattner2f60af72009-09-12 22:45:58 +00002246 << Triple.getTriple().c_str();
Sebastian Redlc5613db2009-03-07 12:09:25 +00002247 return 1;
Chris Lattner11215192008-03-14 06:12:05 +00002248 }
Mike Stump1eb44332009-09-09 15:08:12 +00002249
Daniel Dunbar73b79592009-09-14 00:02:12 +00002250 // Set the target ABI if specified.
2251 if (!TargetABI.empty()) {
2252 if (!Target->setABI(TargetABI)) {
2253 Diags.Report(FullSourceLoc(), diag::err_fe_unknown_target_abi)
2254 << TargetABI;
2255 return 1;
2256 }
2257 }
2258
Daniel Dunbard4270232009-01-20 23:17:32 +00002259 if (!InheritanceViewCls.empty()) // C++ visualization?
Ted Kremenek7cae2f62008-10-23 23:36:29 +00002260 ProgAction = InheritanceView;
Mike Stump1eb44332009-09-09 15:08:12 +00002261
Ted Kremenekc0c03bc2008-06-06 22:42:39 +00002262 llvm::OwningPtr<SourceManager> SourceMgr;
Mike Stump1eb44332009-09-09 15:08:12 +00002263
Chris Lattner2c78b872009-04-14 23:22:57 +00002264 // Create a file manager object to provide access to and cache the filesystem.
2265 FileManager FileMgr;
Douglas Gregor4fed3f42009-04-27 18:38:38 +00002266
Daniel Dunbar868bd0a2009-05-06 03:16:41 +00002267 // Compute the feature set, unfortunately this effects the language!
2268 llvm::StringMap<bool> Features;
2269 ComputeFeatureMap(Target.get(), Features);
2270
Reid Spencer5f016e22007-07-11 17:01:13 +00002271 for (unsigned i = 0, e = InputFilenames.size(); i != e; ++i) {
Ted Kremenek31e703b2007-12-11 23:28:38 +00002272 const std::string &InFile = InputFilenames[i];
Mike Stump1eb44332009-09-09 15:08:12 +00002273
Chris Lattnerf63aea32009-03-04 21:40:56 +00002274 /// Create a SourceManager object. This tracks and owns all the file
2275 /// buffers allocated to a translation unit.
2276 if (!SourceMgr)
2277 SourceMgr.reset(new SourceManager());
2278 else
2279 SourceMgr->clearIDTables();
Mike Stump1eb44332009-09-09 15:08:12 +00002280
Chris Lattnerf63aea32009-03-04 21:40:56 +00002281 // Initialize language options, inferring file types from input filenames.
2282 LangOptions LangInfo;
Chris Lattner409d4e72009-04-17 20:40:01 +00002283 DiagClient->setLangOptions(&LangInfo);
Mike Stump1eb44332009-09-09 15:08:12 +00002284
Chris Lattnerf63aea32009-03-04 21:40:56 +00002285 InitializeBaseLanguage();
2286 LangKind LK = GetLanguage(InFile);
Daniel Dunbar0b5b0da2009-04-01 05:09:09 +00002287 InitializeLangOptions(LangInfo, LK);
Daniel Dunbar868bd0a2009-05-06 03:16:41 +00002288 InitializeLanguageStandard(LangInfo, LK, Target.get(), Features);
Mike Stump1eb44332009-09-09 15:08:12 +00002289
Chris Lattnerf63aea32009-03-04 21:40:56 +00002290 // Process the -I options and set them in the HeaderInfo.
2291 HeaderSearch HeaderInfo(FileMgr);
Mike Stump1eb44332009-09-09 15:08:12 +00002292
2293
Chris Lattnerf63aea32009-03-04 21:40:56 +00002294 InitializeIncludePaths(argv[0], HeaderInfo, FileMgr, LangInfo);
Mike Stump1eb44332009-09-09 15:08:12 +00002295
Chris Lattnerf63aea32009-03-04 21:40:56 +00002296 // Set up the preprocessor with these options.
Eli Friedmanf086e3b2009-05-18 07:39:39 +00002297 DriverPreprocessorFactory PPFactory(Diags, LangInfo, *Target,
Chris Lattnerf63aea32009-03-04 21:40:56 +00002298 *SourceMgr.get(), HeaderInfo);
Mike Stump1eb44332009-09-09 15:08:12 +00002299
Chris Lattnerf63aea32009-03-04 21:40:56 +00002300 llvm::OwningPtr<Preprocessor> PP(PPFactory.CreatePreprocessor());
Mike Stump1eb44332009-09-09 15:08:12 +00002301
Chris Lattnerf63aea32009-03-04 21:40:56 +00002302 if (!PP)
2303 continue;
Ted Kremenekb4398aa2008-08-07 17:49:57 +00002304
Eli Friedmanb5c8f8b2009-05-19 03:35:57 +00002305 // Handle generating dependencies, if requested
2306 if (!DependencyFile.empty()) {
2307 llvm::raw_ostream *DependencyOS;
2308 if (DependencyTargets.empty()) {
2309 // FIXME: Use a proper diagnostic
Chris Lattner92bcc272009-08-23 02:59:41 +00002310 llvm::errs() << "-dependency-file requires at least one -MT option\n";
Eli Friedmanb5c8f8b2009-05-19 03:35:57 +00002311 HadErrors = true;
2312 continue;
2313 }
2314 std::string ErrStr;
2315 DependencyOS =
Dan Gohmanb044c472009-08-25 15:36:09 +00002316 new llvm::raw_fd_ostream(DependencyFile.c_str(), ErrStr);
Eli Friedmanb5c8f8b2009-05-19 03:35:57 +00002317 if (!ErrStr.empty()) {
2318 // FIXME: Use a proper diagnostic
Chris Lattner92bcc272009-08-23 02:59:41 +00002319 llvm::errs() << "unable to open dependency file: " + ErrStr;
Eli Friedmanb5c8f8b2009-05-19 03:35:57 +00002320 HadErrors = true;
2321 continue;
2322 }
2323
2324 AttachDependencyFileGen(PP.get(), DependencyOS, DependencyTargets,
2325 DependenciesIncludeSystemHeaders,
2326 PhonyDependencyTarget);
2327 }
2328
Chris Lattner1b63e4f2009-06-14 01:54:56 +00002329 if (ImplicitIncludePCH.empty()) {
2330 if (InitializeSourceManager(*PP.get(), InFile))
2331 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00002332
Chris Lattner1b63e4f2009-06-14 01:54:56 +00002333 // Initialize builtin info.
2334 PP->getBuiltinInfo().InitializeBuiltins(PP->getIdentifierTable(),
Chris Lattner1b63e4f2009-06-14 01:54:56 +00002335 PP->getLangOptions().NoBuiltin);
2336 }
Douglas Gregor14f79002009-04-10 03:52:48 +00002337
Chris Lattner409d4e72009-04-17 20:40:01 +00002338 if (!HTMLDiag.empty())
2339 ((PathDiagnosticClient*)DiagClient.get())->SetPreprocessor(PP.get());
Chris Lattnerf63aea32009-03-04 21:40:56 +00002340
2341 // Process the source file.
Owen Andersonc93f4982009-07-01 21:23:16 +00002342 ProcessInputFile(*PP, PPFactory, InFile, ProgAction, Features, Context);
Mike Stump1eb44332009-09-09 15:08:12 +00002343
Chris Lattner40469652009-04-17 20:16:08 +00002344 HeaderInfo.ClearFileInfo();
Chris Lattner409d4e72009-04-17 20:40:01 +00002345 DiagClient->setLangOptions(0);
Reid Spencer5f016e22007-07-11 17:01:13 +00002346 }
Chris Lattner11215192008-03-14 06:12:05 +00002347
Mike Stumpfc0fed32009-04-28 01:19:10 +00002348 if (!NoCaretDiagnostics)
2349 if (unsigned NumDiagnostics = Diags.getNumDiagnostics())
2350 fprintf(stderr, "%d diagnostic%s generated.\n", NumDiagnostics,
2351 (NumDiagnostics == 1 ? "" : "s"));
Mike Stump1eb44332009-09-09 15:08:12 +00002352
Reid Spencer5f016e22007-07-11 17:01:13 +00002353 if (Stats) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002354 FileMgr.PrintStats();
2355 fprintf(stderr, "\n");
2356 }
Chris Lattner75a97cb2009-04-17 21:05:01 +00002357
2358 delete ClangFrontendTimer;
2359 delete BuildLogFile;
Mike Stump1eb44332009-09-09 15:08:12 +00002360
Daniel Dunbar276373d2008-10-27 22:10:13 +00002361 // If verifying diagnostics and we reached here, all is well.
2362 if (VerifyDiagnostics)
2363 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002364
Daniel Dunbar524b86f2008-10-28 00:38:08 +00002365 // Managed static deconstruction. Useful for making things like
2366 // -time-passes usable.
2367 llvm::llvm_shutdown();
2368
Daniel Dunbarb0adbba2008-10-04 23:42:49 +00002369 return HadErrors || (Diags.getNumErrors() != 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00002370}