blob: 31aeb7404999445b201a9bd365393e1e55c6ea59 [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>
Fariborz Jahanianb123ea32009-09-16 21:37:16 +0000375ObjCEnableNewGCAPI("fobjc-newgc-api",
376 llvm::cl::desc("Enable Objective-C garbage collection's new API"));
377
378static llvm::cl::opt<bool>
Fariborz Jahanian448f5e62009-04-17 03:04:15 +0000379ObjCEnableGCBitmapPrint("print-ivar-layout",
380 llvm::cl::desc("Enable Objective-C Ivar layout bitmap print trace"));
381
Chris Lattner2c78b872009-04-14 23:22:57 +0000382static llvm::cl::opt<LangOptions::VisibilityMode>
383SymbolVisibility("fvisibility",
384 llvm::cl::desc("Set the default symbol visibility:"),
385 llvm::cl::init(LangOptions::Default),
386 llvm::cl::values(clEnumValN(LangOptions::Default, "default",
387 "Use default symbol visibility"),
388 clEnumValN(LangOptions::Hidden, "hidden",
389 "Use hidden symbol visibility"),
390 clEnumValN(LangOptions::Protected,"protected",
391 "Use protected symbol visibility"),
392 clEnumValEnd));
393
394static llvm::cl::opt<bool>
395OverflowChecking("ftrapv",
396 llvm::cl::desc("Trap on integer overflow"),
397 llvm::cl::init(false));
398
Fariborz Jahanian34e65772009-05-22 20:17:16 +0000399static llvm::cl::opt<bool>
Nate Begeman2ef13e52009-08-10 23:49:36 +0000400AltiVec("faltivec", llvm::cl::desc("Enable AltiVec vector initializer syntax"),
401 llvm::cl::init(false));
402
403static llvm::cl::opt<bool>
Daniel Dunbar5345c392009-09-03 04:54:28 +0000404PThread("pthread", llvm::cl::desc("Support POSIX threads in generated code"),
405 llvm::cl::init(false));
406
Ted Kremenek8904f152007-12-05 23:49:08 +0000407/// InitializeBaseLanguage - Handle the -x foo options.
408static void InitializeBaseLanguage() {
409 if (LangObjC)
410 BaseLang = langkind_objc;
411 else if (LangObjCXX)
412 BaseLang = langkind_objcxx;
413}
414
415static LangKind GetLanguage(const std::string &Filename) {
416 if (BaseLang != langkind_unspecified)
417 return BaseLang;
Mike Stump1eb44332009-09-09 15:08:12 +0000418
Ted Kremenek8904f152007-12-05 23:49:08 +0000419 std::string::size_type DotPos = Filename.rfind('.');
420
421 if (DotPos == std::string::npos) {
422 BaseLang = langkind_c; // Default to C if no extension.
Chris Lattner9b2f6c42008-01-04 19:12:28 +0000423 return langkind_c;
Reid Spencer5f016e22007-07-11 17:01:13 +0000424 }
Mike Stump1eb44332009-09-09 15:08:12 +0000425
Ted Kremenek8904f152007-12-05 23:49:08 +0000426 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
427 // C header: .h
428 // C++ header: .hh or .H;
429 // assembler no preprocessing: .s
430 // assembler: .S
431 if (Ext == "c")
432 return langkind_c;
Chris Lattnerd9cd4c92009-03-23 16:24:37 +0000433 else if (Ext == "S" ||
434 // If the compiler is run on a .s file, preprocess it as .S
435 Ext == "s")
Chris Lattnera778d7d2008-10-22 17:29:21 +0000436 return langkind_asm_cpp;
Ted Kremenek8904f152007-12-05 23:49:08 +0000437 else if (Ext == "i")
438 return langkind_c_cpp;
439 else if (Ext == "ii")
440 return langkind_cxx_cpp;
441 else if (Ext == "m")
442 return langkind_objc;
443 else if (Ext == "mi")
444 return langkind_objc_cpp;
445 else if (Ext == "mm" || Ext == "M")
446 return langkind_objcxx;
447 else if (Ext == "mii")
448 return langkind_objcxx_cpp;
449 else if (Ext == "C" || Ext == "cc" || Ext == "cpp" || Ext == "CPP" ||
450 Ext == "c++" || Ext == "cp" || Ext == "cxx")
451 return langkind_cxx;
Nate Begeman4e3629e2009-06-25 22:43:10 +0000452 else if (Ext == "cl")
453 return langkind_ocl;
Ted Kremenek8904f152007-12-05 23:49:08 +0000454 else
455 return langkind_c;
456}
457
458
Ted Kremenek85888962008-10-21 00:54:44 +0000459static void InitializeCOptions(LangOptions &Options) {
460 // Do nothing.
461}
462
463static void InitializeObjCOptions(LangOptions &Options) {
464 Options.ObjC1 = Options.ObjC2 = 1;
465}
Mike Stump1eb44332009-09-09 15:08:12 +0000466
Ted Kremenek85888962008-10-21 00:54:44 +0000467
Daniel Dunbar0b5b0da2009-04-01 05:09:09 +0000468static void InitializeLangOptions(LangOptions &Options, LangKind LK){
Reid Spencer5f016e22007-07-11 17:01:13 +0000469 // FIXME: implement -fpreprocessed mode.
470 bool NoPreprocess = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000471
Ted Kremenek8904f152007-12-05 23:49:08 +0000472 switch (LK) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000473 default: assert(0 && "Unknown language kind!");
Chris Lattnera778d7d2008-10-22 17:29:21 +0000474 case langkind_asm_cpp:
Daniel Dunbarc1571452008-12-01 18:55:22 +0000475 Options.AsmPreprocessor = 1;
Chris Lattnera778d7d2008-10-22 17:29:21 +0000476 // FALLTHROUGH
Reid Spencer5f016e22007-07-11 17:01:13 +0000477 case langkind_c_cpp:
478 NoPreprocess = true;
479 // FALLTHROUGH
480 case langkind_c:
Ted Kremenek85888962008-10-21 00:54:44 +0000481 InitializeCOptions(Options);
Reid Spencer5f016e22007-07-11 17:01:13 +0000482 break;
483 case langkind_cxx_cpp:
484 NoPreprocess = true;
485 // FALLTHROUGH
486 case langkind_cxx:
487 Options.CPlusPlus = 1;
488 break;
489 case langkind_objc_cpp:
490 NoPreprocess = true;
491 // FALLTHROUGH
492 case langkind_objc:
Ted Kremenek85888962008-10-21 00:54:44 +0000493 InitializeObjCOptions(Options);
Reid Spencer5f016e22007-07-11 17:01:13 +0000494 break;
495 case langkind_objcxx_cpp:
496 NoPreprocess = true;
497 // FALLTHROUGH
498 case langkind_objcxx:
499 Options.ObjC1 = Options.ObjC2 = 1;
500 Options.CPlusPlus = 1;
501 break;
Nate Begeman4e3629e2009-06-25 22:43:10 +0000502 case langkind_ocl:
503 Options.OpenCL = 1;
504 Options.AltiVec = 1;
505 Options.CXXOperatorNames = 1;
506 Options.LaxVectorConversions = 1;
507 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000508 }
Mike Stump1eb44332009-09-09 15:08:12 +0000509
Chris Lattner2c78b872009-04-14 23:22:57 +0000510 if (ObjCExclusiveGC)
511 Options.setGCMode(LangOptions::GCOnly);
512 else if (ObjCEnableGC)
513 Options.setGCMode(LangOptions::HybridGC);
Mike Stump1eb44332009-09-09 15:08:12 +0000514
Fariborz Jahanianb123ea32009-09-16 21:37:16 +0000515 if (ObjCEnableNewGCAPI)
516 Options.ObjCNewGCAPI = 1;
517
Fariborz Jahanian448f5e62009-04-17 03:04:15 +0000518 if (ObjCEnableGCBitmapPrint)
519 Options.ObjCGCBitmapPrint = 1;
Mike Stump1eb44332009-09-09 15:08:12 +0000520
Nate Begeman2ef13e52009-08-10 23:49:36 +0000521 if (AltiVec)
522 Options.AltiVec = 1;
Daniel Dunbar5345c392009-09-03 04:54:28 +0000523
524 if (PThread)
525 Options.POSIXThreads = 1;
Mike Stump1eb44332009-09-09 15:08:12 +0000526
Chris Lattner2c78b872009-04-14 23:22:57 +0000527 Options.setVisibilityMode(SymbolVisibility);
528 Options.OverflowChecking = OverflowChecking;
Reid Spencer5f016e22007-07-11 17:01:13 +0000529}
530
531/// LangStds - Language standards we support.
532enum LangStds {
Mike Stump1eb44332009-09-09 15:08:12 +0000533 lang_unspecified,
Reid Spencer5f016e22007-07-11 17:01:13 +0000534 lang_c89, lang_c94, lang_c99,
Ted Kremenekea644d82008-09-03 21:22:16 +0000535 lang_gnu_START,
536 lang_gnu89 = lang_gnu_START, lang_gnu99,
Chris Lattnerd4b80f12007-07-16 04:18:29 +0000537 lang_cxx98, lang_gnucxx98,
538 lang_cxx0x, lang_gnucxx0x
Reid Spencer5f016e22007-07-11 17:01:13 +0000539};
540
541static llvm::cl::opt<LangStds>
542LangStd("std", llvm::cl::desc("Language standard to compile for"),
543 llvm::cl::init(lang_unspecified),
544 llvm::cl::values(clEnumValN(lang_c89, "c89", "ISO C 1990"),
545 clEnumValN(lang_c89, "c90", "ISO C 1990"),
546 clEnumValN(lang_c89, "iso9899:1990", "ISO C 1990"),
547 clEnumValN(lang_c94, "iso9899:199409",
548 "ISO C 1990 with amendment 1"),
549 clEnumValN(lang_c99, "c99", "ISO C 1999"),
Chris Lattner50748f42009-04-06 17:17:55 +0000550 clEnumValN(lang_c99, "c9x", "ISO C 1999"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000551 clEnumValN(lang_c99, "iso9899:1999", "ISO C 1999"),
Chris Lattner50748f42009-04-06 17:17:55 +0000552 clEnumValN(lang_c99, "iso9899:199x", "ISO C 1999"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000553 clEnumValN(lang_gnu89, "gnu89",
Gabor Greif10b26142009-02-28 09:22:15 +0000554 "ISO C 1990 with GNU extensions"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000555 clEnumValN(lang_gnu99, "gnu99",
Gabor Greif10b26142009-02-28 09:22:15 +0000556 "ISO C 1999 with GNU extensions (default for C)"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000557 clEnumValN(lang_gnu99, "gnu9x",
558 "ISO C 1999 with GNU extensions"),
559 clEnumValN(lang_cxx98, "c++98",
560 "ISO C++ 1998 with amendments"),
561 clEnumValN(lang_gnucxx98, "gnu++98",
562 "ISO C++ 1998 with amendments and GNU "
563 "extensions (default for C++)"),
Chris Lattnerd4b80f12007-07-16 04:18:29 +0000564 clEnumValN(lang_cxx0x, "c++0x",
565 "Upcoming ISO C++ 200x with amendments"),
566 clEnumValN(lang_gnucxx0x, "gnu++0x",
567 "Upcoming ISO C++ 200x with amendments and GNU "
Gabor Greif5f8d1db2009-03-11 23:07:18 +0000568 "extensions"),
Reid Spencer5f016e22007-07-11 17:01:13 +0000569 clEnumValEnd));
570
571static llvm::cl::opt<bool>
572NoOperatorNames("fno-operator-names",
573 llvm::cl::desc("Do not treat C++ operator name keywords as "
574 "synonyms for operators"));
575
Anders Carlssonee98ac52007-10-15 02:50:23 +0000576static llvm::cl::opt<bool>
577PascalStrings("fpascal-strings",
578 llvm::cl::desc("Recognize and construct Pascal-style "
579 "string literals"));
Mike Stump1eb44332009-09-09 15:08:12 +0000580
Steve Naroffd62701b2008-02-07 03:50:06 +0000581static llvm::cl::opt<bool>
582MSExtensions("fms-extensions",
583 llvm::cl::desc("Accept some non-standard constructs used in "
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000584 "Microsoft header files "));
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000585
586static llvm::cl::opt<bool>
587WritableStrings("fwritable-strings",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000588 llvm::cl::desc("Store string literals as writable data"));
Anders Carlsson695dbb62007-11-30 04:21:22 +0000589
590static llvm::cl::opt<bool>
Anders Carlssonad53eff2009-01-30 23:26:40 +0000591NoLaxVectorConversions("fno-lax-vector-conversions",
Anders Carlssonb0f90cc2009-01-30 23:17:46 +0000592 llvm::cl::desc("Disallow implicit conversions between "
593 "vectors with a different number of "
594 "elements or different element types"));
Chris Lattnerae0ee032008-12-04 23:20:07 +0000595
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000596static llvm::cl::opt<bool>
Daniel Dunbar48d1ef72009-04-07 21:16:11 +0000597EnableBlocks("fblocks", llvm::cl::desc("enable the 'blocks' language feature"));
Mike Stumpa0f02aa2009-02-02 22:57:57 +0000598
599static llvm::cl::opt<bool>
Chris Lattner810f6d52009-03-13 17:38:01 +0000600EnableHeinousExtensions("fheinous-gnu-extensions",
601 llvm::cl::desc("enable GNU extensions that you really really shouldn't use"),
602 llvm::cl::ValueDisallowed, llvm::cl::Hidden);
603
604static llvm::cl::opt<bool>
Mike Stumpa0f02aa2009-02-02 22:57:57 +0000605ObjCNonFragileABI("fobjc-nonfragile-abi",
606 llvm::cl::desc("enable objective-c's nonfragile abi"));
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000607
Daniel Dunbard6884a02009-05-04 05:16:21 +0000608
609static llvm::cl::opt<bool>
Daniel Dunbard604c402009-02-04 21:19:06 +0000610EmitAllDecls("femit-all-decls",
611 llvm::cl::desc("Emit all declarations, even if unused"));
Ted Kremenek01d9dbf2008-04-29 04:37:03 +0000612
Daniel Dunbar6379a7a2008-08-11 17:36:14 +0000613static llvm::cl::opt<bool>
614Exceptions("fexceptions",
Chris Lattnerf5db8f82009-04-19 07:00:02 +0000615 llvm::cl::desc("Enable support for exception handling"));
Daniel Dunbar6379a7a2008-08-11 17:36:14 +0000616
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000617static llvm::cl::opt<bool>
Mike Stump738f8c22009-07-31 23:15:31 +0000618Rtti("frtti", llvm::cl::init(true),
619 llvm::cl::desc("Enable generation of rtti information"));
620
621static llvm::cl::opt<bool>
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000622GNURuntime("fgnu-runtime",
Ted Kremenek85888962008-10-21 00:54:44 +0000623 llvm::cl::desc("Generate output compatible with the standard GNU "
Chris Lattnerf5db8f82009-04-19 07:00:02 +0000624 "Objective-C runtime"));
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000625
626static llvm::cl::opt<bool>
627NeXTRuntime("fnext-runtime",
Ted Kremenek85888962008-10-21 00:54:44 +0000628 llvm::cl::desc("Generate output compatible with the NeXT "
Chris Lattnerf5db8f82009-04-19 07:00:02 +0000629 "runtime"));
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000630
Eli Friedmanc4757bd2009-06-05 07:12:17 +0000631static llvm::cl::opt<bool>
632CharIsSigned("fsigned-char",
633 llvm::cl::desc("Force char to be a signed/unsigned type"));
Ted Kremenekea644d82008-09-03 21:22:16 +0000634
635
636static llvm::cl::opt<bool>
Chris Lattnerf5db8f82009-04-19 07:00:02 +0000637Trigraphs("trigraphs", llvm::cl::desc("Process trigraph sequences"));
Ted Kremenekea644d82008-09-03 21:22:16 +0000638
Douglas Gregor26dce442009-03-10 00:06:19 +0000639static llvm::cl::opt<unsigned>
640TemplateDepth("ftemplate-depth", llvm::cl::init(99),
641 llvm::cl::desc("Maximum depth of recursive template "
642 "instantiation"));
Chris Lattnerf5db8f82009-04-19 07:00:02 +0000643static llvm::cl::opt<bool>
644DollarsInIdents("fdollars-in-identifiers",
645 llvm::cl::desc("Allow '$' in identifiers"));
Chris Lattner16167a62009-03-02 22:11:07 +0000646
Anders Carlsson4ca076f2009-04-06 17:37:10 +0000647
648static llvm::cl::opt<bool>
649OptSize("Os", llvm::cl::desc("Optimize for size"));
650
651static llvm::cl::opt<bool>
Mike Stump1eb44332009-09-09 15:08:12 +0000652DisableLLVMOptimizations("disable-llvm-optzns",
Daniel Dunbar877db382009-06-02 22:07:45 +0000653 llvm::cl::desc("Don't run LLVM optimization passes"));
654
655static llvm::cl::opt<bool>
Anders Carlsson4ca076f2009-04-06 17:37:10 +0000656NoCommon("fno-common",
657 llvm::cl::desc("Compile common globals like normal definitions"),
658 llvm::cl::ValueDisallowed);
659
Daniel Dunbarc9abc042009-04-08 05:11:16 +0000660static llvm::cl::opt<std::string>
661MainFileName("main-file-name",
662 llvm::cl::desc("Main file name to use for debug info"));
Anders Carlsson4ca076f2009-04-06 17:37:10 +0000663
Anders Carlssona33d9b42009-05-13 19:49:53 +0000664// FIXME: Also add an "-fno-access-control" option.
665static llvm::cl::opt<bool>
Mike Stump1eb44332009-09-09 15:08:12 +0000666AccessControl("faccess-control",
Anders Carlssona33d9b42009-05-13 19:49:53 +0000667 llvm::cl::desc("Enable C++ access control"));
668
Anders Carlsson92f58222009-08-22 22:30:33 +0000669static llvm::cl::opt<bool>
670NoElideConstructors("fno-elide-constructors",
671 llvm::cl::desc("Disable C++ copy constructor elision"));
672
Daniel Dunbar73b79592009-09-14 00:02:12 +0000673static llvm::cl::opt<std::string>
674TargetABI("target-abi",
675 llvm::cl::desc("Target a particular ABI type"));
676
Anders Carlsson92f58222009-08-22 22:30:33 +0000677
Anders Carlsson4ca076f2009-04-06 17:37:10 +0000678// It might be nice to add bounds to the CommandLine library directly.
679struct OptLevelParser : public llvm::cl::parser<unsigned> {
680 bool parse(llvm::cl::Option &O, const char *ArgName,
681 const std::string &Arg, unsigned &Val) {
682 if (llvm::cl::parser<unsigned>::parse(O, ArgName, Arg, Val))
683 return true;
Anders Carlsson4ca076f2009-04-06 17:37:10 +0000684 if (Val > 3)
Benjamin Kramer21fde992009-08-02 12:12:11 +0000685 return O.error("'" + Arg + "' invalid optimization level!");
Anders Carlsson4ca076f2009-04-06 17:37:10 +0000686 return false;
687 }
688};
689static llvm::cl::opt<unsigned, false, OptLevelParser>
690OptLevel("O", llvm::cl::Prefix,
691 llvm::cl::desc("Optimization level"),
692 llvm::cl::init(0));
693
Daniel Dunbar9fd0b1f2009-04-08 03:03:23 +0000694static llvm::cl::opt<unsigned>
Daniel Dunbar3bbc7532009-04-08 18:03:55 +0000695PICLevel("pic-level", llvm::cl::desc("Value for __PIC__"));
696
697static llvm::cl::opt<bool>
698StaticDefine("static-define", llvm::cl::desc("Should __STATIC__ be defined"));
Daniel Dunbar9fd0b1f2009-04-08 03:03:23 +0000699
Bill Wendling45483f72009-06-28 07:36:13 +0000700static llvm::cl::opt<int>
701StackProtector("stack-protector",
702 llvm::cl::desc("Enable stack protectors"),
703 llvm::cl::init(-1));
704
Daniel Dunbardcb4a1a2008-08-23 08:43:39 +0000705static void InitializeLanguageStandard(LangOptions &Options, LangKind LK,
Daniel Dunbar868bd0a2009-05-06 03:16:41 +0000706 TargetInfo *Target,
707 const llvm::StringMap<bool> &Features) {
Chris Lattner8fc4dfb2008-12-04 22:54:33 +0000708 // Allow the target to set the default the langauge options as it sees fit.
709 Target->getDefaultLangOptions(Options);
Daniel Dunbar868bd0a2009-05-06 03:16:41 +0000710
711 // Pass the map of target features to the target for validation and
712 // processing.
713 Target->HandleTargetFeatures(Features);
Mike Stump1eb44332009-09-09 15:08:12 +0000714
Reid Spencer5f016e22007-07-11 17:01:13 +0000715 if (LangStd == lang_unspecified) {
716 // Based on the base language, pick one.
Ted Kremenek8904f152007-12-05 23:49:08 +0000717 switch (LK) {
Ted Kremenekf2a17b12009-03-19 19:02:20 +0000718 case lang_unspecified: assert(0 && "Unknown base language");
Nate Begeman4e3629e2009-06-25 22:43:10 +0000719 case langkind_ocl:
720 LangStd = lang_c99;
721 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000722 case langkind_c:
Chris Lattnera778d7d2008-10-22 17:29:21 +0000723 case langkind_asm_cpp:
Reid Spencer5f016e22007-07-11 17:01:13 +0000724 case langkind_c_cpp:
725 case langkind_objc:
726 case langkind_objc_cpp:
727 LangStd = lang_gnu99;
728 break;
729 case langkind_cxx:
730 case langkind_cxx_cpp:
731 case langkind_objcxx:
732 case langkind_objcxx_cpp:
733 LangStd = lang_gnucxx98;
734 break;
735 }
736 }
Mike Stump1eb44332009-09-09 15:08:12 +0000737
Reid Spencer5f016e22007-07-11 17:01:13 +0000738 switch (LangStd) {
739 default: assert(0 && "Unknown language standard!");
740
741 // Fall through from newer standards to older ones. This isn't really right.
742 // FIXME: Enable specifically the right features based on the language stds.
Chris Lattnerd4b80f12007-07-16 04:18:29 +0000743 case lang_gnucxx0x:
744 case lang_cxx0x:
745 Options.CPlusPlus0x = 1;
746 // FALL THROUGH
Reid Spencer5f016e22007-07-11 17:01:13 +0000747 case lang_gnucxx98:
748 case lang_cxx98:
749 Options.CPlusPlus = 1;
750 Options.CXXOperatorNames = !NoOperatorNames;
751 // FALL THROUGH.
752 case lang_gnu99:
753 case lang_c99:
Reid Spencer5f016e22007-07-11 17:01:13 +0000754 Options.C99 = 1;
755 Options.HexFloats = 1;
756 // FALL THROUGH.
757 case lang_gnu89:
758 Options.BCPLComment = 1; // Only for C99/C++.
759 // FALL THROUGH.
760 case lang_c94:
Chris Lattner3426b9b2008-02-25 04:01:39 +0000761 Options.Digraphs = 1; // C94, C99, C++.
762 // FALL THROUGH.
Reid Spencer5f016e22007-07-11 17:01:13 +0000763 case lang_c89:
764 break;
765 }
Argyrios Kyrtzidisd1465522008-09-11 04:21:06 +0000766
Chris Lattner7e9c90b2009-03-20 15:44:26 +0000767 // GNUMode - Set if we're in gnu99, gnu89, gnucxx98, etc.
768 Options.GNUMode = LangStd >= lang_gnu_START;
Mike Stump1eb44332009-09-09 15:08:12 +0000769
Argyrios Kyrtzidisd1465522008-09-11 04:21:06 +0000770 if (Options.CPlusPlus) {
771 Options.C99 = 0;
Eli Friedmanab24c8d2009-08-26 20:15:14 +0000772 Options.HexFloats = 0;
Argyrios Kyrtzidisd1465522008-09-11 04:21:06 +0000773 }
Mike Stump1eb44332009-09-09 15:08:12 +0000774
Chris Lattnerd658b562008-04-05 06:32:51 +0000775 if (LangStd == lang_c89 || LangStd == lang_c94 || LangStd == lang_gnu89)
776 Options.ImplicitInt = 1;
777 else
778 Options.ImplicitInt = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000779
Daniel Dunbard573d262009-04-07 22:13:21 +0000780 // Mimicing gcc's behavior, trigraphs are only enabled if -trigraphs
781 // is specified, or -std is set to a conforming mode.
Chris Lattner7e9c90b2009-03-20 15:44:26 +0000782 Options.Trigraphs = !Options.GNUMode;
Chris Lattner802db9b2008-12-05 00:10:44 +0000783 if (Trigraphs.getPosition())
Chris Lattner7e9c90b2009-03-20 15:44:26 +0000784 Options.Trigraphs = Trigraphs; // Command line option wins if specified.
Ted Kremenekea644d82008-09-03 21:22:16 +0000785
Chris Lattner802db9b2008-12-05 00:10:44 +0000786 // If in a conformant language mode (e.g. -std=c99) Blocks defaults to off
787 // even if they are normally on for the target. In GNU modes (e.g.
788 // -std=gnu99) the default for blocks depends on the target settings.
Anders Carlssone56f6ff2009-01-21 18:47:36 +0000789 // However, blocks are not turned off when compiling Obj-C or Obj-C++ code.
Chris Lattner7e9c90b2009-03-20 15:44:26 +0000790 if (!Options.ObjC1 && !Options.GNUMode)
Chris Lattner802db9b2008-12-05 00:10:44 +0000791 Options.Blocks = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000792
Chris Lattner01638a62009-04-19 07:06:52 +0000793 // Default to not accepting '$' in identifiers when preprocessing assembler,
794 // but do accept when preprocessing C. FIXME: these defaults are right for
795 // darwin, are they right everywhere?
796 Options.DollarIdents = LK != langkind_asm_cpp;
797 if (DollarsInIdents.getPosition()) // Explicit setting overrides default.
Chris Lattnerf5db8f82009-04-19 07:00:02 +0000798 Options.DollarIdents = DollarsInIdents;
Mike Stump1eb44332009-09-09 15:08:12 +0000799
Chris Lattnerae0ee032008-12-04 23:20:07 +0000800 if (PascalStrings.getPosition())
801 Options.PascalStrings = PascalStrings;
Eli Friedmanabc4e322009-06-08 06:11:14 +0000802 if (MSExtensions.getPosition())
803 Options.Microsoft = MSExtensions;
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000804 Options.WritableStrings = WritableStrings;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +0000805 if (NoLaxVectorConversions.getPosition())
806 Options.LaxVectorConversions = 0;
Daniel Dunbar6379a7a2008-08-11 17:36:14 +0000807 Options.Exceptions = Exceptions;
Mike Stump738f8c22009-07-31 23:15:31 +0000808 Options.Rtti = Rtti;
Mike Stumpa0f02aa2009-02-02 22:57:57 +0000809 if (EnableBlocks.getPosition())
Chris Lattnerae0ee032008-12-04 23:20:07 +0000810 Options.Blocks = EnableBlocks;
Eli Friedmanc4757bd2009-06-05 07:12:17 +0000811 if (CharIsSigned.getPosition())
812 Options.CharIsSigned = CharIsSigned;
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000813
Daniel Dunbar9f9768c2009-03-20 23:49:28 +0000814 if (!AllowBuiltins)
Chris Lattner7644f072009-03-13 22:38:49 +0000815 Options.NoBuiltin = 1;
Douglas Gregor3573c0c2009-02-14 20:49:29 +0000816 if (Freestanding)
Chris Lattner7644f072009-03-13 22:38:49 +0000817 Options.Freestanding = Options.NoBuiltin = 1;
Mike Stump1eb44332009-09-09 15:08:12 +0000818
Chris Lattner810f6d52009-03-13 17:38:01 +0000819 if (EnableHeinousExtensions)
820 Options.HeinousExtensions = 1;
Douglas Gregor3573c0c2009-02-14 20:49:29 +0000821
Anders Carlssona33d9b42009-05-13 19:49:53 +0000822 if (AccessControl)
823 Options.AccessControl = 1;
Mike Stump1eb44332009-09-09 15:08:12 +0000824
Anders Carlsson92f58222009-08-22 22:30:33 +0000825 Options.ElideConstructors = !NoElideConstructors;
Mike Stump1eb44332009-09-09 15:08:12 +0000826
Chris Lattnere4f21422009-06-30 01:26:17 +0000827 // OpenCL and C++ both have bool, true, false keywords.
828 Options.Bool = Options.OpenCL | Options.CPlusPlus;
Mike Stump1eb44332009-09-09 15:08:12 +0000829
Daniel Dunbaref2abfe2009-02-16 22:43:43 +0000830 Options.MathErrno = MathErrno;
831
Douglas Gregor26dce442009-03-10 00:06:19 +0000832 Options.InstantiationDepth = TemplateDepth;
833
Chris Lattner8fc4dfb2008-12-04 22:54:33 +0000834 // Override the default runtime if the user requested it.
835 if (NeXTRuntime)
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000836 Options.NeXTRuntime = 1;
Chris Lattner8fc4dfb2008-12-04 22:54:33 +0000837 else if (GNURuntime)
Daniel Dunbarf77ac862008-08-11 21:35:06 +0000838 Options.NeXTRuntime = 0;
Fariborz Jahanianee0af742009-01-21 22:04:16 +0000839
David Chisnall8a5a9aa2009-08-31 16:41:57 +0000840 if (!ObjCConstantStringClass.empty())
841 Options.ObjCConstantStringClass = ObjCConstantStringClass.c_str();
842
Fariborz Jahanian30bc5712009-01-22 23:02:58 +0000843 if (ObjCNonFragileABI)
844 Options.ObjCNonFragileABI = 1;
Fariborz Jahanian34e65772009-05-22 20:17:16 +0000845
Daniel Dunbard604c402009-02-04 21:19:06 +0000846 if (EmitAllDecls)
847 Options.EmitAllDecls = 1;
Anders Carlsson4ca076f2009-04-06 17:37:10 +0000848
Daniel Dunbar3bbc7532009-04-08 18:03:55 +0000849 // The __OPTIMIZE_SIZE__ define is tied to -Oz, which we don't
850 // support.
851 Options.OptimizeSize = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000852
Anders Carlsson4ca076f2009-04-06 17:37:10 +0000853 // -Os implies -O2
Daniel Dunbar3bbc7532009-04-08 18:03:55 +0000854 if (OptSize || OptLevel)
Anders Carlsson4ca076f2009-04-06 17:37:10 +0000855 Options.Optimize = 1;
Daniel Dunbar9fd0b1f2009-04-08 03:03:23 +0000856
857 assert(PICLevel <= 2 && "Invalid value for -pic-level");
858 Options.PICLevel = PICLevel;
Daniel Dunbarc9abc042009-04-08 05:11:16 +0000859
Daniel Dunbar3bbc7532009-04-08 18:03:55 +0000860 Options.GNUInline = !Options.C99;
Mike Stump1eb44332009-09-09 15:08:12 +0000861 // FIXME: This is affected by other options (-fno-inline).
Daniel Dunbar3bbc7532009-04-08 18:03:55 +0000862 Options.NoInline = !OptSize && !OptLevel;
863
864 Options.Static = StaticDefine;
865
Bill Wendling4ebe3e42009-06-28 23:01:01 +0000866 switch (StackProtector) {
867 default:
868 assert(StackProtector <= 2 && "Invalid value for -stack-protector");
869 case -1: break;
870 case 0: Options.setStackProtectorMode(LangOptions::SSPOff); break;
871 case 1: Options.setStackProtectorMode(LangOptions::SSPOn); break;
872 case 2: Options.setStackProtectorMode(LangOptions::SSPReq); break;
873 }
Bill Wendling45483f72009-06-28 07:36:13 +0000874
Daniel Dunbarc9abc042009-04-08 05:11:16 +0000875 if (MainFileName.getPosition())
876 Options.setMainFileName(MainFileName.c_str());
Reid Spencer5f016e22007-07-11 17:01:13 +0000877}
878
879//===----------------------------------------------------------------------===//
Ted Kremenekae360762007-12-03 22:06:55 +0000880// Target Triple Processing.
881//===----------------------------------------------------------------------===//
882
883static llvm::cl::opt<std::string>
884TargetTriple("triple",
Sanjiv Gupta56cf96b2008-05-08 08:28:14 +0000885 llvm::cl::desc("Specify target triple (e.g. i686-apple-darwin9)"));
Ted Kremenekae360762007-12-03 22:06:55 +0000886
Chris Lattner42e67372008-03-05 01:18:20 +0000887static llvm::cl::opt<std::string>
Mike Stump1eb44332009-09-09 15:08:12 +0000888MacOSVersionMin("mmacosx-version-min",
Daniel Dunbar8d33cd72009-04-10 19:52:24 +0000889 llvm::cl::desc("Specify target Mac OS X version (e.g. 10.5)"));
Chris Lattner6a30c1f2008-09-30 01:13:12 +0000890
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000891// If -mmacosx-version-min=10.3.9 is specified, change the triple from being
892// something like powerpc-apple-darwin9 to powerpc-apple-darwin7
Daniel Dunbar64ffc142009-03-31 20:10:05 +0000893
894// FIXME: We should have the driver do this instead.
Chris Lattner2f60af72009-09-12 22:45:58 +0000895static void HandleMacOSVersionMin(llvm::Triple &Triple) {
896 if (Triple.getOS() != llvm::Triple::Darwin) {
Mike Stump1eb44332009-09-09 15:08:12 +0000897 fprintf(stderr,
Daniel Dunbar8d33cd72009-04-10 19:52:24 +0000898 "-mmacosx-version-min only valid for darwin (Mac OS X) targets\n");
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000899 exit(1);
900 }
Chris Lattner2f60af72009-09-12 22:45:58 +0000901
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000902 // Validate that MacOSVersionMin is a 'version number', starting with 10.[3-9]
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000903 if (MacOSVersionMin.size() < 4 ||
904 MacOSVersionMin.substr(0, 3) != "10." ||
905 !isdigit(MacOSVersionMin[3])) {
Mike Stump1eb44332009-09-09 15:08:12 +0000906 fprintf(stderr,
Daniel Dunbaraf07f932009-03-31 17:35:15 +0000907 "-mmacosx-version-min=%s is invalid, expected something like '10.4'.\n",
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000908 MacOSVersionMin.c_str());
909 exit(1);
910 }
Chris Lattner2f60af72009-09-12 22:45:58 +0000911
912 unsigned VersionNum = MacOSVersionMin[3]-'0';
913
914 if (VersionNum <= 4 && Triple.getArch() == llvm::Triple::x86_64) {
Mike Stump1eb44332009-09-09 15:08:12 +0000915 fprintf(stderr,
Chris Lattner2f60af72009-09-12 22:45:58 +0000916 "-mmacosx-version-min=%s is invalid with -arch x86_64.\n",
Fariborz Jahanian6a1284a2009-04-10 20:33:45 +0000917 MacOSVersionMin.c_str());
918 exit(1);
919 }
920
Chris Lattner2f60af72009-09-12 22:45:58 +0000921
922 llvm::SmallString<16> NewDarwinString;
923 NewDarwinString += "darwin";
924
925 // Turn MacOSVersionMin into a darwin number: e.g. 10.3.9 is 3 -> darwin7.
926 VersionNum += 4;
927 if (VersionNum > 9) {
928 NewDarwinString += '1';
929 VersionNum -= 10;
930 }
931 NewDarwinString += (VersionNum+'0');
932
933 if (MacOSVersionMin.size() == 4) {
934 // "10.4" is ok.
935 } else if (MacOSVersionMin.size() == 6 &&
936 MacOSVersionMin[4] == '.' &&
937 isdigit(MacOSVersionMin[5])) { // 10.4.7 is ok.
938 // Add the period piece (.7) to the end of the triple. This gives us
939 // something like ...-darwin8.7
940 NewDarwinString += '.';
941 NewDarwinString += MacOSVersionMin[5];
942 } else { // "10.4" is ok. 10.4x is not.
943 fprintf(stderr,
944 "-mmacosx-version-min=%s is invalid, expected something like '10.4'.\n",
945 MacOSVersionMin.c_str());
946 exit(1);
947 }
948
949 Triple.setOSName(NewDarwinString.str());
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000950}
951
Daniel Dunbar8d33cd72009-04-10 19:52:24 +0000952static llvm::cl::opt<std::string>
Mike Stump1eb44332009-09-09 15:08:12 +0000953IPhoneOSVersionMin("miphoneos-version-min",
Daniel Dunbar8d33cd72009-04-10 19:52:24 +0000954 llvm::cl::desc("Specify target iPhone OS version (e.g. 2.0)"));
955
956// If -miphoneos-version-min=2.2 is specified, change the triple from being
957// something like armv6-apple-darwin10 to armv6-apple-darwin9.2.2. We use
958// 9 as the default major Darwin number, and encode the iPhone OS version
959// number in the minor version and revision.
960
961// FIXME: We should have the driver do this instead.
Chris Lattner2f60af72009-09-12 22:45:58 +0000962static void HandleIPhoneOSVersionMin(llvm::Triple &Triple) {
963 if (Triple.getOS() != llvm::Triple::Darwin) {
Mike Stump1eb44332009-09-09 15:08:12 +0000964 fprintf(stderr,
Chris Lattner2f60af72009-09-12 22:45:58 +0000965 "-miphoneos-version-min only valid for darwin (Mac OS X) targets\n");
Daniel Dunbar8d33cd72009-04-10 19:52:24 +0000966 exit(1);
967 }
Mike Stump1eb44332009-09-09 15:08:12 +0000968
Chris Lattner2f60af72009-09-12 22:45:58 +0000969 // Validate that IPhoneOSVersionMin is a 'version number', starting with
970 // [2-9].[0-9]
971 if (IPhoneOSVersionMin.size() != 3 || !isdigit(IPhoneOSVersionMin[0]) ||
972 IPhoneOSVersionMin[1] != '.' || !isdigit(IPhoneOSVersionMin[2])) {
Mike Stump1eb44332009-09-09 15:08:12 +0000973 fprintf(stderr,
Chris Lattner2f60af72009-09-12 22:45:58 +0000974 "-miphoneos-version-min=%s is invalid, expected something like '2.0'.\n",
Daniel Dunbar8d33cd72009-04-10 19:52:24 +0000975 IPhoneOSVersionMin.c_str());
976 exit(1);
977 }
Chris Lattner2f60af72009-09-12 22:45:58 +0000978
979 // Turn IPhoneOSVersionMin into a darwin number: e.g. 2.0 is 2 -> 9.2.0
980 llvm::SmallString<16> NewDarwinString;
981 NewDarwinString += "darwin9.";
982 NewDarwinString += IPhoneOSVersionMin;
983 Triple.setOSName(NewDarwinString.str());
Daniel Dunbar8d33cd72009-04-10 19:52:24 +0000984}
985
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000986/// CreateTargetTriple - Process the various options that affect the target
987/// triple and build a final aggregate triple that we are compiling for.
Chris Lattner2f60af72009-09-12 22:45:58 +0000988static llvm::Triple CreateTargetTriple() {
Ted Kremenekae360762007-12-03 22:06:55 +0000989 // Initialize base triple. If a -triple option has been specified, use
990 // that triple. Otherwise, default to the host triple.
Chris Lattner2f60af72009-09-12 22:45:58 +0000991 llvm::Triple Triple(TargetTriple);
992 if (Triple.getTriple().empty())
993 Triple = llvm::Triple(llvm::sys::getHostTriple());
Chris Lattner6a30c1f2008-09-30 01:13:12 +0000994
995 // If -mmacosx-version-min=10.3.9 is specified, change the triple from being
996 // something like powerpc-apple-darwin9 to powerpc-apple-darwin7
Chris Lattnerba0f25f2008-09-30 20:16:56 +0000997 if (!MacOSVersionMin.empty())
998 HandleMacOSVersionMin(Triple);
Daniel Dunbar8d33cd72009-04-10 19:52:24 +0000999 else if (!IPhoneOSVersionMin.empty())
Chris Lattner2f60af72009-09-12 22:45:58 +00001000 HandleIPhoneOSVersionMin(Triple);
Mike Stump1eb44332009-09-09 15:08:12 +00001001
Chris Lattner6a30c1f2008-09-30 01:13:12 +00001002 return Triple;
Ted Kremenekae360762007-12-03 22:06:55 +00001003}
1004
1005//===----------------------------------------------------------------------===//
Chris Lattnere116ccf2009-04-21 05:40:52 +00001006// SourceManager initialization.
Reid Spencer5f016e22007-07-11 17:01:13 +00001007//===----------------------------------------------------------------------===//
1008
Douglas Gregore1d918e2009-04-10 23:10:45 +00001009static bool InitializeSourceManager(Preprocessor &PP,
1010 const std::string &InFile) {
1011 // Figure out where to get and map in the main file.
1012 SourceManager &SourceMgr = PP.getSourceManager();
1013 FileManager &FileMgr = PP.getFileManager();
Daniel Dunbar57cbfc02009-04-27 21:19:07 +00001014
1015 if (EmptyInputOnly) {
1016 const char *EmptyStr = "";
Mike Stump1eb44332009-09-09 15:08:12 +00001017 llvm::MemoryBuffer *SB =
Daniel Dunbar57cbfc02009-04-27 21:19:07 +00001018 llvm::MemoryBuffer::getMemBuffer(EmptyStr, EmptyStr, "<empty input>");
1019 SourceMgr.createMainFileIDForMemBuffer(SB);
1020 } else if (InFile != "-") {
Douglas Gregore1d918e2009-04-10 23:10:45 +00001021 const FileEntry *File = FileMgr.getFile(InFile);
1022 if (File) SourceMgr.createMainFileID(File, SourceLocation());
1023 if (SourceMgr.getMainFileID().isInvalid()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001024 PP.getDiagnostics().Report(FullSourceLoc(), diag::err_fe_error_reading)
Douglas Gregore1d918e2009-04-10 23:10:45 +00001025 << InFile.c_str();
1026 return true;
1027 }
1028 } else {
1029 llvm::MemoryBuffer *SB = llvm::MemoryBuffer::getSTDIN();
1030
1031 // If stdin was empty, SB is null. Cons up an empty memory
1032 // buffer now.
1033 if (!SB) {
1034 const char *EmptyStr = "";
1035 SB = llvm::MemoryBuffer::getMemBuffer(EmptyStr, EmptyStr, "<stdin>");
1036 }
1037
1038 SourceMgr.createMainFileIDForMemBuffer(SB);
1039 if (SourceMgr.getMainFileID().isInvalid()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001040 PP.getDiagnostics().Report(FullSourceLoc(),
Douglas Gregore1d918e2009-04-10 23:10:45 +00001041 diag::err_fe_error_reading_stdin);
1042 return true;
1043 }
1044 }
1045
1046 return false;
1047}
1048
Chris Lattneraa391972008-04-19 23:09:31 +00001049
Chris Lattnere116ccf2009-04-21 05:40:52 +00001050//===----------------------------------------------------------------------===//
1051// Preprocessor Initialization
1052//===----------------------------------------------------------------------===//
Sam Bishop1102d6b2008-04-14 14:41:57 +00001053
Chris Lattnere116ccf2009-04-21 05:40:52 +00001054// FIXME: Preprocessor builtins to support.
1055// -A... - Play with #assertions
1056// -undef - Undefine all predefined macros
Chris Lattnerb31ac222009-04-08 20:15:42 +00001057
Chris Lattnere116ccf2009-04-21 05:40:52 +00001058static llvm::cl::list<std::string>
1059D_macros("D", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
1060 llvm::cl::desc("Predefine the specified macro"));
1061static llvm::cl::list<std::string>
1062U_macros("U", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
1063 llvm::cl::desc("Undefine the specified macro"));
Chris Lattnerb8e240e2009-04-08 18:24:34 +00001064
Chris Lattnere116ccf2009-04-21 05:40:52 +00001065static llvm::cl::list<std::string>
1066ImplicitIncludes("include", llvm::cl::value_desc("file"),
1067 llvm::cl::desc("Include file before parsing"));
1068static llvm::cl::list<std::string>
1069ImplicitMacroIncludes("imacros", llvm::cl::value_desc("file"),
1070 llvm::cl::desc("Include macros from file before parsing"));
Chris Lattnerb8e240e2009-04-08 18:24:34 +00001071
Chris Lattnere116ccf2009-04-21 05:40:52 +00001072static llvm::cl::opt<std::string>
1073ImplicitIncludePCH("include-pch", llvm::cl::value_desc("file"),
1074 llvm::cl::desc("Include precompiled header file"));
1075
1076static llvm::cl::opt<std::string>
1077ImplicitIncludePTH("include-pth", llvm::cl::value_desc("file"),
1078 llvm::cl::desc("Include file before parsing"));
1079
Douglas Gregore650c8c2009-07-07 00:12:59 +00001080static llvm::cl::opt<bool>
Mike Stump1eb44332009-09-09 15:08:12 +00001081RelocatablePCH("relocatable-pch",
Douglas Gregore650c8c2009-07-07 00:12:59 +00001082 llvm::cl::desc("Whether to build a relocatable precompiled "
1083 "header"));
Reid Spencer5f016e22007-07-11 17:01:13 +00001084
1085//===----------------------------------------------------------------------===//
1086// Preprocessor include path information.
1087//===----------------------------------------------------------------------===//
1088
1089// This tool exports a large number of command line options to control how the
1090// preprocessor searches for header files. At root, however, the Preprocessor
1091// object takes a very simple interface: a list of directories to search for
Mike Stump1eb44332009-09-09 15:08:12 +00001092//
Daniel Dunbarfb4ac7b2009-05-06 03:48:17 +00001093// FIXME: -nostdinc++
Chris Lattner0c946412007-08-26 17:47:35 +00001094// FIXME: -imultilib
Reid Spencer5f016e22007-07-11 17:01:13 +00001095//
Reid Spencer5f016e22007-07-11 17:01:13 +00001096
1097static llvm::cl::opt<bool>
1098nostdinc("nostdinc", llvm::cl::desc("Disable standard #include directories"));
1099
1100// Various command line options. These four add directories to each chain.
1101static llvm::cl::list<std::string>
1102F_dirs("F", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1103 llvm::cl::desc("Add directory to framework include search path"));
1104static llvm::cl::list<std::string>
1105I_dirs("I", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1106 llvm::cl::desc("Add directory to include search path"));
1107static llvm::cl::list<std::string>
1108idirafter_dirs("idirafter", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1109 llvm::cl::desc("Add directory to AFTER include search path"));
1110static llvm::cl::list<std::string>
1111iquote_dirs("iquote", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1112 llvm::cl::desc("Add directory to QUOTE include search path"));
1113static llvm::cl::list<std::string>
1114isystem_dirs("isystem", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
1115 llvm::cl::desc("Add directory to SYSTEM include search path"));
1116
1117// These handle -iprefix/-iwithprefix/-iwithprefixbefore.
1118static llvm::cl::list<std::string>
1119iprefix_vals("iprefix", llvm::cl::value_desc("prefix"), llvm::cl::Prefix,
1120 llvm::cl::desc("Set the -iwithprefix/-iwithprefixbefore prefix"));
1121static llvm::cl::list<std::string>
1122iwithprefix_vals("iwithprefix", llvm::cl::value_desc("dir"), llvm::cl::Prefix,
1123 llvm::cl::desc("Set directory to SYSTEM include search path with prefix"));
1124static llvm::cl::list<std::string>
1125iwithprefixbefore_vals("iwithprefixbefore", llvm::cl::value_desc("dir"),
1126 llvm::cl::Prefix,
1127 llvm::cl::desc("Set directory to include search path with prefix"));
1128
Chris Lattner0c946412007-08-26 17:47:35 +00001129static llvm::cl::opt<std::string>
1130isysroot("isysroot", llvm::cl::value_desc("dir"), llvm::cl::init("/"),
1131 llvm::cl::desc("Set the system root directory (usually /)"));
1132
Reid Spencer5f016e22007-07-11 17:01:13 +00001133// Finally, implement the code that groks the options above.
Chris Lattner5f9eae52008-03-01 08:07:28 +00001134
Reid Spencer5f016e22007-07-11 17:01:13 +00001135/// InitializeIncludePaths - Process the -I options and set them in the
1136/// HeaderSearch object.
Nico Weber0fca0222008-08-22 09:25:22 +00001137void InitializeIncludePaths(const char *Argv0, HeaderSearch &Headers,
1138 FileManager &FM, const LangOptions &Lang) {
1139 InitHeaderSearch Init(Headers, Verbose, isysroot);
1140
Ted Kremenekf3721112008-05-31 00:27:00 +00001141 // Handle -I... and -F... options, walking the lists in parallel.
1142 unsigned Iidx = 0, Fidx = 0;
1143 while (Iidx < I_dirs.size() && Fidx < F_dirs.size()) {
1144 if (I_dirs.getPosition(Iidx) < F_dirs.getPosition(Fidx)) {
Nico Weber0fca0222008-08-22 09:25:22 +00001145 Init.AddPath(I_dirs[Iidx], InitHeaderSearch::Angled, false, true, false);
Ted Kremenekf3721112008-05-31 00:27:00 +00001146 ++Iidx;
1147 } else {
Nico Weber0fca0222008-08-22 09:25:22 +00001148 Init.AddPath(F_dirs[Fidx], InitHeaderSearch::Angled, false, true, true);
Ted Kremenekf3721112008-05-31 00:27:00 +00001149 ++Fidx;
1150 }
1151 }
Mike Stump1eb44332009-09-09 15:08:12 +00001152
Ted Kremenekf3721112008-05-31 00:27:00 +00001153 // Consume what's left from whatever list was longer.
1154 for (; Iidx != I_dirs.size(); ++Iidx)
Nico Weber0fca0222008-08-22 09:25:22 +00001155 Init.AddPath(I_dirs[Iidx], InitHeaderSearch::Angled, false, true, false);
Ted Kremenekf3721112008-05-31 00:27:00 +00001156 for (; Fidx != F_dirs.size(); ++Fidx)
Nico Weber0fca0222008-08-22 09:25:22 +00001157 Init.AddPath(F_dirs[Fidx], InitHeaderSearch::Angled, false, true, true);
Mike Stump1eb44332009-09-09 15:08:12 +00001158
Reid Spencer5f016e22007-07-11 17:01:13 +00001159 // Handle -idirafter... options.
1160 for (unsigned i = 0, e = idirafter_dirs.size(); i != e; ++i)
Nico Weber0fca0222008-08-22 09:25:22 +00001161 Init.AddPath(idirafter_dirs[i], InitHeaderSearch::After,
1162 false, true, false);
Mike Stump1eb44332009-09-09 15:08:12 +00001163
Reid Spencer5f016e22007-07-11 17:01:13 +00001164 // Handle -iquote... options.
1165 for (unsigned i = 0, e = iquote_dirs.size(); i != e; ++i)
Nico Weber0fca0222008-08-22 09:25:22 +00001166 Init.AddPath(iquote_dirs[i], InitHeaderSearch::Quoted, false, true, false);
Mike Stump1eb44332009-09-09 15:08:12 +00001167
Reid Spencer5f016e22007-07-11 17:01:13 +00001168 // Handle -isystem... options.
1169 for (unsigned i = 0, e = isystem_dirs.size(); i != e; ++i)
Nico Weber0fca0222008-08-22 09:25:22 +00001170 Init.AddPath(isystem_dirs[i], InitHeaderSearch::System, false, true, false);
Reid Spencer5f016e22007-07-11 17:01:13 +00001171
1172 // Walk the -iprefix/-iwithprefix/-iwithprefixbefore argument lists in
1173 // parallel, processing the values in order of occurance to get the right
1174 // prefixes.
1175 {
1176 std::string Prefix = ""; // FIXME: this isn't the correct default prefix.
1177 unsigned iprefix_idx = 0;
1178 unsigned iwithprefix_idx = 0;
1179 unsigned iwithprefixbefore_idx = 0;
1180 bool iprefix_done = iprefix_vals.empty();
1181 bool iwithprefix_done = iwithprefix_vals.empty();
1182 bool iwithprefixbefore_done = iwithprefixbefore_vals.empty();
1183 while (!iprefix_done || !iwithprefix_done || !iwithprefixbefore_done) {
1184 if (!iprefix_done &&
Mike Stump1eb44332009-09-09 15:08:12 +00001185 (iwithprefix_done ||
1186 iprefix_vals.getPosition(iprefix_idx) <
Reid Spencer5f016e22007-07-11 17:01:13 +00001187 iwithprefix_vals.getPosition(iwithprefix_idx)) &&
Mike Stump1eb44332009-09-09 15:08:12 +00001188 (iwithprefixbefore_done ||
1189 iprefix_vals.getPosition(iprefix_idx) <
Reid Spencer5f016e22007-07-11 17:01:13 +00001190 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
1191 Prefix = iprefix_vals[iprefix_idx];
1192 ++iprefix_idx;
1193 iprefix_done = iprefix_idx == iprefix_vals.size();
1194 } else if (!iwithprefix_done &&
Mike Stump1eb44332009-09-09 15:08:12 +00001195 (iwithprefixbefore_done ||
1196 iwithprefix_vals.getPosition(iwithprefix_idx) <
Reid Spencer5f016e22007-07-11 17:01:13 +00001197 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
Mike Stump1eb44332009-09-09 15:08:12 +00001198 Init.AddPath(Prefix+iwithprefix_vals[iwithprefix_idx],
Nico Weber0fca0222008-08-22 09:25:22 +00001199 InitHeaderSearch::System, false, false, false);
Reid Spencer5f016e22007-07-11 17:01:13 +00001200 ++iwithprefix_idx;
1201 iwithprefix_done = iwithprefix_idx == iwithprefix_vals.size();
1202 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00001203 Init.AddPath(Prefix+iwithprefixbefore_vals[iwithprefixbefore_idx],
Nico Weber0fca0222008-08-22 09:25:22 +00001204 InitHeaderSearch::Angled, false, false, false);
Reid Spencer5f016e22007-07-11 17:01:13 +00001205 ++iwithprefixbefore_idx;
Mike Stump1eb44332009-09-09 15:08:12 +00001206 iwithprefixbefore_done =
Reid Spencer5f016e22007-07-11 17:01:13 +00001207 iwithprefixbefore_idx == iwithprefixbefore_vals.size();
1208 }
1209 }
1210 }
Chris Lattner5f9eae52008-03-01 08:07:28 +00001211
Nico Weber0fca0222008-08-22 09:25:22 +00001212 Init.AddDefaultEnvVarPaths(Lang);
Chris Lattner5f9eae52008-03-01 08:07:28 +00001213
Daniel Dunbaradcf5b32009-02-21 20:52:41 +00001214 // Add the clang headers, which are relative to the clang binary.
Mike Stump1eb44332009-09-09 15:08:12 +00001215 llvm::sys::Path MainExecutablePath =
Chris Lattner985e1822008-03-03 05:57:43 +00001216 llvm::sys::Path::GetMainExecutable(Argv0,
1217 (void*)(intptr_t)InitializeIncludePaths);
Chris Lattnerdcaa0962008-03-03 03:16:03 +00001218 if (!MainExecutablePath.isEmpty()) {
1219 MainExecutablePath.eraseComponent(); // Remove /clang from foo/bin/clang
1220 MainExecutablePath.eraseComponent(); // Remove /bin from foo/bin
Daniel Dunbaradcf5b32009-02-21 20:52:41 +00001221
Mike Stump1eb44332009-09-09 15:08:12 +00001222 // Get foo/lib/clang/<version>/include
Daniel Dunbaradcf5b32009-02-21 20:52:41 +00001223 MainExecutablePath.appendComponent("lib");
1224 MainExecutablePath.appendComponent("clang");
Daniel Dunbarfb4ac7b2009-05-06 03:48:17 +00001225 MainExecutablePath.appendComponent(CLANG_VERSION_STRING);
Daniel Dunbaradcf5b32009-02-21 20:52:41 +00001226 MainExecutablePath.appendComponent("include");
Mike Stump1eb44332009-09-09 15:08:12 +00001227
Chris Lattner6858dd32009-02-19 06:48:28 +00001228 // We pass true to ignore sysroot so that we *always* look for clang headers
1229 // relative to our executable, never relative to -isysroot.
1230 Init.AddPath(MainExecutablePath.c_str(), InitHeaderSearch::System,
1231 false, false, false, true /*ignore sysroot*/);
Chris Lattnerdcaa0962008-03-03 03:16:03 +00001232 }
Mike Stump1eb44332009-09-09 15:08:12 +00001233
1234 if (!nostdinc)
Nico Weber0fca0222008-08-22 09:25:22 +00001235 Init.AddDefaultSystemIncludePaths(Lang);
Reid Spencer5f016e22007-07-11 17:01:13 +00001236
1237 // Now that we have collected all of the include paths, merge them all
1238 // together and tell the preprocessor about them.
Mike Stump1eb44332009-09-09 15:08:12 +00001239
Nico Weber0fca0222008-08-22 09:25:22 +00001240 Init.Realize();
Reid Spencer5f016e22007-07-11 17:01:13 +00001241}
1242
Mike Stump1eb44332009-09-09 15:08:12 +00001243void InitializePreprocessorInitOptions(PreprocessorInitOptions &InitOpts) {
Chris Lattnere116ccf2009-04-21 05:40:52 +00001244 // Add macros from the command line.
1245 unsigned d = 0, D = D_macros.size();
1246 unsigned u = 0, U = U_macros.size();
1247 while (d < D || u < U) {
1248 if (u == U || (d < D && D_macros.getPosition(d) < U_macros.getPosition(u)))
1249 InitOpts.addMacroDef(D_macros[d++]);
1250 else
1251 InitOpts.addMacroUndef(U_macros[u++]);
1252 }
1253
1254 // If -imacros are specified, include them now. These are processed before
1255 // any -include directives.
1256 for (unsigned i = 0, e = ImplicitMacroIncludes.size(); i != e; ++i)
1257 InitOpts.addMacroInclude(ImplicitMacroIncludes[i]);
1258
Douglas Gregorb64c1932009-05-12 01:31:05 +00001259 if (!ImplicitIncludePTH.empty() || !ImplicitIncludes.empty() ||
1260 (!ImplicitIncludePCH.empty() && ProgAction == PrintPreprocessedInput)) {
Chris Lattnere116ccf2009-04-21 05:40:52 +00001261 // We want to add these paths to the predefines buffer in order, make a
1262 // temporary vector to sort by their occurrence.
1263 llvm::SmallVector<std::pair<unsigned, std::string*>, 8> OrderedPaths;
1264
1265 if (!ImplicitIncludePTH.empty())
1266 OrderedPaths.push_back(std::make_pair(ImplicitIncludePTH.getPosition(),
1267 &ImplicitIncludePTH));
Douglas Gregorb64c1932009-05-12 01:31:05 +00001268 if (!ImplicitIncludePCH.empty() && ProgAction == PrintPreprocessedInput)
1269 OrderedPaths.push_back(std::make_pair(ImplicitIncludePCH.getPosition(),
1270 &ImplicitIncludePCH));
Chris Lattnere116ccf2009-04-21 05:40:52 +00001271 for (unsigned i = 0, e = ImplicitIncludes.size(); i != e; ++i)
1272 OrderedPaths.push_back(std::make_pair(ImplicitIncludes.getPosition(i),
1273 &ImplicitIncludes[i]));
1274 llvm::array_pod_sort(OrderedPaths.begin(), OrderedPaths.end());
1275
1276
1277 // Now that they are ordered by position, add to the predefines buffer.
1278 for (unsigned i = 0, e = OrderedPaths.size(); i != e; ++i) {
1279 std::string *Ptr = OrderedPaths[i].second;
1280 if (!ImplicitIncludes.empty() &&
1281 Ptr >= &ImplicitIncludes[0] &&
1282 Ptr <= &ImplicitIncludes[ImplicitIncludes.size()-1]) {
1283 InitOpts.addInclude(*Ptr, false);
Douglas Gregorb64c1932009-05-12 01:31:05 +00001284 } else if (Ptr == &ImplicitIncludePTH) {
Chris Lattnere116ccf2009-04-21 05:40:52 +00001285 InitOpts.addInclude(*Ptr, true);
Douglas Gregorb64c1932009-05-12 01:31:05 +00001286 } else {
1287 // We end up here when we're producing preprocessed output and
1288 // we loaded a PCH file. In this case, just include the header
1289 // file that was used to build the precompiled header.
1290 assert(Ptr == &ImplicitIncludePCH);
1291 std::string OriginalFile = PCHReader::getOriginalSourceFile(*Ptr);
1292 if (!OriginalFile.empty()) {
1293 InitOpts.addInclude(OriginalFile, false);
1294 ImplicitIncludePCH.clear();
1295 }
Chris Lattnere116ccf2009-04-21 05:40:52 +00001296 }
1297 }
1298 }
1299}
1300
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001301//===----------------------------------------------------------------------===//
1302// Driver PreprocessorFactory - For lazily generating preprocessors ...
1303//===----------------------------------------------------------------------===//
1304
1305namespace {
1306class VISIBILITY_HIDDEN DriverPreprocessorFactory : public PreprocessorFactory {
1307 Diagnostic &Diags;
1308 const LangOptions &LangInfo;
1309 TargetInfo &Target;
1310 SourceManager &SourceMgr;
1311 HeaderSearch &HeaderInfo;
Mike Stump1eb44332009-09-09 15:08:12 +00001312
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001313public:
Eli Friedmanf086e3b2009-05-18 07:39:39 +00001314 DriverPreprocessorFactory(Diagnostic &diags, const LangOptions &opts,
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001315 TargetInfo &target, SourceManager &SM,
Mike Stump1eb44332009-09-09 15:08:12 +00001316 HeaderSearch &Headers)
Eli Friedmanf086e3b2009-05-18 07:39:39 +00001317 : Diags(diags), LangInfo(opts), Target(target),
Douglas Gregore1d918e2009-04-10 23:10:45 +00001318 SourceMgr(SM), HeaderInfo(Headers) {}
Mike Stump1eb44332009-09-09 15:08:12 +00001319
1320
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001321 virtual ~DriverPreprocessorFactory() {}
Mike Stump1eb44332009-09-09 15:08:12 +00001322
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001323 virtual Preprocessor* CreatePreprocessor() {
Ted Kremenek72b1b152009-01-15 18:47:46 +00001324 llvm::OwningPtr<PTHManager> PTHMgr;
1325
Ted Kremenek748d5d62009-03-20 00:26:38 +00001326 if (!TokenCache.empty() && !ImplicitIncludePTH.empty()) {
1327 fprintf(stderr, "error: cannot use both -token-cache and -include-pth "
1328 "options\n");
Ted Kremenek22f0d092009-03-22 06:42:39 +00001329 exit(1);
Ted Kremenek748d5d62009-03-20 00:26:38 +00001330 }
Mike Stump1eb44332009-09-09 15:08:12 +00001331
Ted Kremenek72b1b152009-01-15 18:47:46 +00001332 // Use PTH?
Ted Kremenek748d5d62009-03-20 00:26:38 +00001333 if (!TokenCache.empty() || !ImplicitIncludePTH.empty()) {
1334 const std::string& x = TokenCache.empty() ? ImplicitIncludePTH:TokenCache;
Mike Stump1eb44332009-09-09 15:08:12 +00001335 PTHMgr.reset(PTHManager::Create(x, &Diags,
Ted Kremenek22f0d092009-03-22 06:42:39 +00001336 TokenCache.empty() ? Diagnostic::Error
1337 : Diagnostic::Warning));
Ted Kremenek748d5d62009-03-20 00:26:38 +00001338 }
Mike Stump1eb44332009-09-09 15:08:12 +00001339
Ted Kremenek22f0d092009-03-22 06:42:39 +00001340 if (Diags.hasErrorOccurred())
1341 exit(1);
Mike Stump1eb44332009-09-09 15:08:12 +00001342
Ted Kremenek72b1b152009-01-15 18:47:46 +00001343 // Create the Preprocessor.
1344 llvm::OwningPtr<Preprocessor> PP(new Preprocessor(Diags, LangInfo, Target,
1345 SourceMgr, HeaderInfo,
1346 PTHMgr.get()));
Mike Stump1eb44332009-09-09 15:08:12 +00001347
Ted Kremenek72b1b152009-01-15 18:47:46 +00001348 // Note that this is different then passing PTHMgr to Preprocessor's ctor.
1349 // That argument is used as the IdentifierInfoLookup argument to
1350 // IdentifierTable's ctor.
1351 if (PTHMgr) {
1352 PTHMgr->setPreprocessor(PP.get());
1353 PP->setPTHManager(PTHMgr.take());
1354 }
Douglas Gregor14f79002009-04-10 03:52:48 +00001355
Chris Lattnere116ccf2009-04-21 05:40:52 +00001356 PreprocessorInitOptions InitOpts;
1357 InitializePreprocessorInitOptions(InitOpts);
Eli Friedmanf086e3b2009-05-18 07:39:39 +00001358 if (InitializePreprocessor(*PP, InitOpts))
Douglas Gregore1d918e2009-04-10 23:10:45 +00001359 return 0;
Chris Lattnere116ccf2009-04-21 05:40:52 +00001360
Douglas Gregore1d918e2009-04-10 23:10:45 +00001361 return PP.take();
Ted Kremeneka42cf2e2008-04-17 21:38:34 +00001362 }
1363};
1364}
Reid Spencer5f016e22007-07-11 17:01:13 +00001365
Reid Spencer5f016e22007-07-11 17:01:13 +00001366//===----------------------------------------------------------------------===//
1367// Basic Parser driver
1368//===----------------------------------------------------------------------===//
1369
Chris Lattner51574ea2008-04-19 23:25:44 +00001370static void ParseFile(Preprocessor &PP, MinimalAction *PA) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001371 Parser P(PP, *PA);
Ted Kremenek95041a22007-12-19 22:51:13 +00001372 PP.EnterMainSourceFile();
Mike Stump1eb44332009-09-09 15:08:12 +00001373
Reid Spencer5f016e22007-07-11 17:01:13 +00001374 // Parsing the specified input file.
1375 P.ParseTranslationUnit();
1376 delete PA;
1377}
1378
1379//===----------------------------------------------------------------------===//
Daniel Dunbar70f92432008-10-23 05:50:47 +00001380// Code generation options
1381//===----------------------------------------------------------------------===//
1382
1383static llvm::cl::opt<bool>
Chris Lattner15104882009-03-09 22:05:03 +00001384GenerateDebugInfo("g",
1385 llvm::cl::desc("Generate source level debug information"));
1386
Daniel Dunbara034ba82009-02-17 19:47:34 +00001387static llvm::cl::opt<std::string>
1388TargetCPU("mcpu",
1389 llvm::cl::desc("Target a specific cpu type (-mcpu=help for details)"));
1390
Daniel Dunbar868bd0a2009-05-06 03:16:41 +00001391static llvm::cl::list<std::string>
1392TargetFeatures("target-feature", llvm::cl::desc("Target specific attributes"));
1393
Devang Patel24095da2009-06-04 23:32:02 +00001394
1395static llvm::cl::opt<bool>
1396DisableRedZone("disable-red-zone",
1397 llvm::cl::desc("Do not emit code that uses the red zone."),
1398 llvm::cl::init(false));
1399
Devang Patelacebb392009-06-05 22:05:48 +00001400static llvm::cl::opt<bool>
1401NoImplicitFloat("no-implicit-float",
1402 llvm::cl::desc("Don't generate implicit floating point instructions (x86-only)"),
1403 llvm::cl::init(false));
1404
Daniel Dunbar868bd0a2009-05-06 03:16:41 +00001405/// ComputeTargetFeatures - Recompute the target feature list to only
1406/// be the list of things that are enabled, based on the target cpu
1407/// and feature list.
1408static void ComputeFeatureMap(TargetInfo *Target,
1409 llvm::StringMap<bool> &Features) {
Mike Stump1eb44332009-09-09 15:08:12 +00001410 assert(Features.empty() && "invalid map");
Daniel Dunbar868bd0a2009-05-06 03:16:41 +00001411
1412 // Initialize the feature map based on the target.
1413 Target->getDefaultFeatures(TargetCPU, Features);
1414
1415 // Apply the user specified deltas.
Mike Stump1eb44332009-09-09 15:08:12 +00001416 for (llvm::cl::list<std::string>::iterator it = TargetFeatures.begin(),
Daniel Dunbar868bd0a2009-05-06 03:16:41 +00001417 ie = TargetFeatures.end(); it != ie; ++it) {
1418 const char *Name = it->c_str();
Mike Stump1eb44332009-09-09 15:08:12 +00001419
Daniel Dunbar868bd0a2009-05-06 03:16:41 +00001420 // FIXME: Don't handle errors like this.
1421 if (Name[0] != '-' && Name[0] != '+') {
Mike Stump1eb44332009-09-09 15:08:12 +00001422 fprintf(stderr, "error: clang-cc: invalid target feature string: %s\n",
Daniel Dunbar868bd0a2009-05-06 03:16:41 +00001423 Name);
1424 exit(1);
1425 }
Daniel Dunbar17ca3632009-05-06 21:07:50 +00001426 if (!Target->setFeatureEnabled(Features, Name + 1, (Name[0] == '+'))) {
Mike Stump1eb44332009-09-09 15:08:12 +00001427 fprintf(stderr, "error: clang-cc: invalid target feature name: %s\n",
Daniel Dunbar17ca3632009-05-06 21:07:50 +00001428 Name + 1);
Daniel Dunbar868bd0a2009-05-06 03:16:41 +00001429 exit(1);
1430 }
Daniel Dunbar868bd0a2009-05-06 03:16:41 +00001431 }
1432}
1433
Chris Lattner7afae712009-03-16 18:41:18 +00001434static void InitializeCompileOptions(CompileOptions &Opts,
Daniel Dunbar868bd0a2009-05-06 03:16:41 +00001435 const LangOptions &LangOpts,
1436 const llvm::StringMap<bool> &Features) {
Daniel Dunbar70f92432008-10-23 05:50:47 +00001437 Opts.OptimizeSize = OptSize;
Chris Lattner20126042009-03-09 22:00:34 +00001438 Opts.DebugInfo = GenerateDebugInfo;
Daniel Dunbar877db382009-06-02 22:07:45 +00001439
1440 if (DisableLLVMOptimizations) {
1441 Opts.OptimizationLevel = 0;
1442 Opts.Inlining = CompileOptions::NoInlining;
Daniel Dunbarac7ffe02008-10-29 07:56:11 +00001443 } else {
Daniel Dunbar877db382009-06-02 22:07:45 +00001444 if (OptSize) {
1445 // -Os implies -O2
1446 Opts.OptimizationLevel = 2;
1447 } else {
1448 Opts.OptimizationLevel = OptLevel;
1449 }
1450
1451 // We must always run at least the always inlining pass.
1452 if (Opts.OptimizationLevel > 1)
1453 Opts.Inlining = CompileOptions::NormalInlining;
1454 else
1455 Opts.Inlining = CompileOptions::OnlyAlwaysInlining;
Daniel Dunbarac7ffe02008-10-29 07:56:11 +00001456 }
Daniel Dunbar8e8f3b72008-10-29 03:42:18 +00001457
1458 // FIXME: There are llvm-gcc options to control these selectively.
Daniel Dunbar8e8f3b72008-10-29 03:42:18 +00001459 Opts.UnrollLoops = (Opts.OptimizationLevel > 1 && !OptSize);
Chris Lattner7afae712009-03-16 18:41:18 +00001460 Opts.SimplifyLibCalls = !LangOpts.NoBuiltin;
Daniel Dunbardd913e52008-10-31 09:34:21 +00001461
1462#ifdef NDEBUG
1463 Opts.VerifyModule = 0;
1464#endif
Daniel Dunbara034ba82009-02-17 19:47:34 +00001465
1466 Opts.CPU = TargetCPU;
Daniel Dunbar868bd0a2009-05-06 03:16:41 +00001467 Opts.Features.clear();
Mike Stump1eb44332009-09-09 15:08:12 +00001468 for (llvm::StringMap<bool>::const_iterator it = Features.begin(),
Daniel Dunbar868bd0a2009-05-06 03:16:41 +00001469 ie = Features.end(); it != ie; ++it) {
1470 // FIXME: If we are completely confident that we have the right
1471 // set, we only need to pass the minuses.
1472 std::string Name(it->second ? "+" : "-");
1473 Name += it->first();
1474 Opts.Features.push_back(Name);
1475 }
Mike Stump1eb44332009-09-09 15:08:12 +00001476
Chris Lattnerbd360642009-03-26 05:00:52 +00001477 Opts.NoCommon = NoCommon | LangOpts.CPlusPlus;
Mike Stump1eb44332009-09-09 15:08:12 +00001478
Chris Lattner44502662009-02-18 01:23:44 +00001479 // Handle -ftime-report.
1480 Opts.TimePasses = TimeReport;
Devang Patel24095da2009-06-04 23:32:02 +00001481
1482 Opts.DisableRedZone = DisableRedZone;
Devang Patelacebb392009-06-05 22:05:48 +00001483 Opts.NoImplicitFloat = NoImplicitFloat;
Daniel Dunbar70f92432008-10-23 05:50:47 +00001484}
1485
1486//===----------------------------------------------------------------------===//
Douglas Gregor26df2f02009-04-02 19:05:20 +00001487// Fix-It Options
1488//===----------------------------------------------------------------------===//
1489static llvm::cl::list<ParsedSourceLocation>
1490FixItAtLocations("fixit-at", llvm::cl::value_desc("source-location"),
1491 llvm::cl::desc("Perform Fix-It modifications at the given source location"));
1492
1493//===----------------------------------------------------------------------===//
Eli Friedmanc6d656e2009-05-18 22:39:16 +00001494// ObjC Rewriter Options
1495//===----------------------------------------------------------------------===//
1496static llvm::cl::opt<bool>
1497SilenceRewriteMacroWarning("Wno-rewrite-macros", llvm::cl::init(false),
1498 llvm::cl::desc("Silence ObjC rewriting warnings"));
1499
1500//===----------------------------------------------------------------------===//
Eli Friedman0eeb86e2009-05-19 01:17:04 +00001501// Warning Options
1502//===----------------------------------------------------------------------===//
1503
1504// This gets all -W options, including -Werror, -W[no-]system-headers, etc. The
1505// driver has stripped off -Wa,foo etc. The driver has also translated -W to
1506// -Wextra, so we don't need to worry about it.
1507static llvm::cl::list<std::string>
1508OptWarnings("W", llvm::cl::Prefix, llvm::cl::ValueOptional);
1509
1510static llvm::cl::opt<bool> OptPedantic("pedantic");
1511static llvm::cl::opt<bool> OptPedanticErrors("pedantic-errors");
1512static llvm::cl::opt<bool> OptNoWarnings("w");
1513
1514//===----------------------------------------------------------------------===//
Eli Friedman12d3b1d2009-05-19 03:06:47 +00001515// Preprocessing (-E mode) Options
1516//===----------------------------------------------------------------------===//
1517static llvm::cl::opt<bool>
1518DisableLineMarkers("P", llvm::cl::desc("Disable linemarker output in -E mode"));
1519static llvm::cl::opt<bool>
1520EnableCommentOutput("C", llvm::cl::desc("Enable comment output in -E mode"));
1521static llvm::cl::opt<bool>
1522EnableMacroCommentOutput("CC",
1523 llvm::cl::desc("Enable comment output in -E mode, "
1524 "even from macro expansions"));
1525static llvm::cl::opt<bool>
1526DumpMacros("dM", llvm::cl::desc("Print macro definitions in -E mode instead of"
1527 " normal output"));
1528static llvm::cl::opt<bool>
1529DumpDefines("dD", llvm::cl::desc("Print macro definitions in -E mode in "
1530 "addition to normal output"));
Eli Friedmanb5c8f8b2009-05-19 03:35:57 +00001531
1532//===----------------------------------------------------------------------===//
1533// Dependency file options
1534//===----------------------------------------------------------------------===//
1535static llvm::cl::opt<std::string>
1536DependencyFile("dependency-file",
1537 llvm::cl::desc("Filename (or -) to write dependency output to"));
1538
1539static llvm::cl::opt<bool>
1540DependenciesIncludeSystemHeaders("sys-header-deps",
1541 llvm::cl::desc("Include system headers in dependency output"));
1542
1543static llvm::cl::list<std::string>
1544DependencyTargets("MT",
1545 llvm::cl::desc("Specify target for dependency"));
1546
1547// FIXME: Implement feature
1548static llvm::cl::opt<bool>
1549PhonyDependencyTarget("MP",
1550 llvm::cl::desc("Create phony target for each dependency "
1551 "(other than main file)"));
1552
Eli Friedman12d3b1d2009-05-19 03:06:47 +00001553//===----------------------------------------------------------------------===//
Eli Friedmane71b85f2009-05-19 10:18:02 +00001554// Analysis options
1555//===----------------------------------------------------------------------===//
1556
1557static llvm::cl::list<Analyses>
1558AnalysisList(llvm::cl::desc("Source Code Analysis - Checks and Analyses"),
1559llvm::cl::values(
1560#define ANALYSIS(NAME, CMDFLAG, DESC, SCOPE)\
1561clEnumValN(NAME, CMDFLAG, DESC),
Eli Friedman0ec78fa2009-05-19 21:10:40 +00001562#include "clang/Frontend/Analyses.def"
Eli Friedmane71b85f2009-05-19 10:18:02 +00001563clEnumValEnd));
1564
Mike Stump1eb44332009-09-09 15:08:12 +00001565static llvm::cl::opt<AnalysisStores>
Eli Friedmane71b85f2009-05-19 10:18:02 +00001566AnalysisStoreOpt("analyzer-store",
1567 llvm::cl::desc("Source Code Analysis - Abstract Memory Store Models"),
1568 llvm::cl::init(BasicStoreModel),
1569 llvm::cl::values(
1570#define ANALYSIS_STORE(NAME, CMDFLAG, DESC, CREATFN)\
1571clEnumValN(NAME##Model, CMDFLAG, DESC),
Eli Friedman0ec78fa2009-05-19 21:10:40 +00001572#include "clang/Frontend/Analyses.def"
Eli Friedmane71b85f2009-05-19 10:18:02 +00001573clEnumValEnd));
1574
Mike Stump1eb44332009-09-09 15:08:12 +00001575static llvm::cl::opt<AnalysisConstraints>
Eli Friedmane71b85f2009-05-19 10:18:02 +00001576AnalysisConstraintsOpt("analyzer-constraints",
1577 llvm::cl::desc("Source Code Analysis - Symbolic Constraint Engines"),
1578 llvm::cl::init(RangeConstraintsModel),
1579 llvm::cl::values(
1580#define ANALYSIS_CONSTRAINTS(NAME, CMDFLAG, DESC, CREATFN)\
1581clEnumValN(NAME##Model, CMDFLAG, DESC),
Eli Friedman0ec78fa2009-05-19 21:10:40 +00001582#include "clang/Frontend/Analyses.def"
Eli Friedmane71b85f2009-05-19 10:18:02 +00001583clEnumValEnd));
1584
1585static llvm::cl::opt<AnalysisDiagClients>
1586AnalysisDiagOpt("analyzer-output",
1587 llvm::cl::desc("Source Code Analysis - Output Options"),
1588 llvm::cl::init(PD_HTML),
1589 llvm::cl::values(
1590#define ANALYSIS_DIAGNOSTICS(NAME, CMDFLAG, DESC, CREATFN, AUTOCREATE)\
1591clEnumValN(PD_##NAME, CMDFLAG, DESC),
Eli Friedman0ec78fa2009-05-19 21:10:40 +00001592#include "clang/Frontend/Analyses.def"
Eli Friedmane71b85f2009-05-19 10:18:02 +00001593clEnumValEnd));
1594
1595static llvm::cl::opt<bool>
1596VisualizeEGDot("analyzer-viz-egraph-graphviz",
1597 llvm::cl::desc("Display exploded graph using GraphViz"));
1598
1599static llvm::cl::opt<bool>
1600VisualizeEGUbi("analyzer-viz-egraph-ubigraph",
1601 llvm::cl::desc("Display exploded graph using Ubigraph"));
1602
1603static llvm::cl::opt<bool>
1604AnalyzeAll("analyzer-opt-analyze-headers",
1605 llvm::cl::desc("Force the static analyzer to analyze "
1606 "functions defined in header files"));
1607
1608static llvm::cl::opt<bool>
1609AnalyzerDisplayProgress("analyzer-display-progress",
1610 llvm::cl::desc("Emit verbose output about the analyzer's progress."));
1611
1612static llvm::cl::opt<bool>
1613PurgeDead("analyzer-purge-dead",
1614 llvm::cl::init(true),
1615 llvm::cl::desc("Remove dead symbols, bindings, and constraints before"
1616 " processing a statement."));
1617
1618static llvm::cl::opt<bool>
1619EagerlyAssume("analyzer-eagerly-assume",
1620 llvm::cl::init(false),
1621 llvm::cl::desc("Eagerly assume the truth/falseness of some "
1622 "symbolic constraints."));
1623
1624static llvm::cl::opt<std::string>
1625AnalyzeSpecificFunction("analyze-function",
1626 llvm::cl::desc("Run analysis on specific function"));
1627
1628static llvm::cl::opt<bool>
1629TrimGraph("trim-egraph",
1630 llvm::cl::desc("Only show error-related paths in the analysis graph"));
1631
1632static AnalyzerOptions ReadAnalyzerOptions() {
1633 AnalyzerOptions Opts;
1634 Opts.AnalysisList = AnalysisList;
1635 Opts.AnalysisStoreOpt = AnalysisStoreOpt;
1636 Opts.AnalysisConstraintsOpt = AnalysisConstraintsOpt;
1637 Opts.AnalysisDiagOpt = AnalysisDiagOpt;
1638 Opts.VisualizeEGDot = VisualizeEGDot;
1639 Opts.VisualizeEGUbi = VisualizeEGUbi;
1640 Opts.AnalyzeAll = AnalyzeAll;
1641 Opts.AnalyzerDisplayProgress = AnalyzerDisplayProgress;
1642 Opts.PurgeDead = PurgeDead;
1643 Opts.EagerlyAssume = EagerlyAssume;
1644 Opts.AnalyzeSpecificFunction = AnalyzeSpecificFunction;
1645 Opts.TrimGraph = TrimGraph;
1646 return Opts;
1647}
1648
1649//===----------------------------------------------------------------------===//
Chris Lattner75a97cb2009-04-17 21:05:01 +00001650// -dump-build-information Stuff
1651//===----------------------------------------------------------------------===//
1652
1653static llvm::cl::opt<std::string>
1654DumpBuildInformation("dump-build-information",
1655 llvm::cl::value_desc("filename"),
1656 llvm::cl::desc("output a dump of some build information to a file"));
1657
1658static llvm::raw_ostream *BuildLogFile = 0;
1659
1660/// LoggingDiagnosticClient - This is a simple diagnostic client that forwards
1661/// all diagnostics to both BuildLogFile and a chained DiagnosticClient.
1662namespace {
1663class LoggingDiagnosticClient : public DiagnosticClient {
1664 llvm::OwningPtr<DiagnosticClient> Chain1;
1665 llvm::OwningPtr<DiagnosticClient> Chain2;
1666public:
Mike Stump1eb44332009-09-09 15:08:12 +00001667
Chris Lattner75a97cb2009-04-17 21:05:01 +00001668 LoggingDiagnosticClient(DiagnosticClient *Normal) {
1669 // Output diags both where requested...
1670 Chain1.reset(Normal);
1671 // .. and to our log file.
1672 Chain2.reset(new TextDiagnosticPrinter(*BuildLogFile,
1673 !NoShowColumn,
1674 !NoCaretDiagnostics,
1675 !NoShowLocation,
1676 PrintSourceRangeInfo,
Chris Lattneraa5bf2e2009-04-19 07:44:08 +00001677 PrintDiagnosticOption,
Douglas Gregorfffd93f2009-05-01 21:53:04 +00001678 !NoDiagnosticsFixIt,
Nate Begeman4e3629e2009-06-25 22:43:10 +00001679 MessageLength));
Chris Lattner75a97cb2009-04-17 21:05:01 +00001680 }
Mike Stump1eb44332009-09-09 15:08:12 +00001681
Chris Lattner75a97cb2009-04-17 21:05:01 +00001682 virtual void setLangOptions(const LangOptions *LO) {
1683 Chain1->setLangOptions(LO);
1684 Chain2->setLangOptions(LO);
1685 }
Mike Stump1eb44332009-09-09 15:08:12 +00001686
Chris Lattner75a97cb2009-04-17 21:05:01 +00001687 virtual bool IncludeInDiagnosticCounts() const {
1688 return Chain1->IncludeInDiagnosticCounts();
1689 }
1690
1691 virtual void HandleDiagnostic(Diagnostic::Level DiagLevel,
1692 const DiagnosticInfo &Info) {
1693 Chain1->HandleDiagnostic(DiagLevel, Info);
1694 Chain2->HandleDiagnostic(DiagLevel, Info);
1695 }
1696};
1697} // end anonymous namespace.
1698
1699static void SetUpBuildDumpLog(unsigned argc, char **argv,
1700 llvm::OwningPtr<DiagnosticClient> &DiagClient) {
Mike Stump1eb44332009-09-09 15:08:12 +00001701
Chris Lattner75a97cb2009-04-17 21:05:01 +00001702 std::string ErrorInfo;
Chris Lattner92bcc272009-08-23 02:59:41 +00001703 BuildLogFile = new llvm::raw_fd_ostream(DumpBuildInformation.c_str(),
Dan Gohmanb044c472009-08-25 15:36:09 +00001704 ErrorInfo);
Mike Stump1eb44332009-09-09 15:08:12 +00001705
Chris Lattner75a97cb2009-04-17 21:05:01 +00001706 if (!ErrorInfo.empty()) {
1707 llvm::errs() << "error opening -dump-build-information file '"
1708 << DumpBuildInformation << "', option ignored!\n";
1709 delete BuildLogFile;
1710 BuildLogFile = 0;
1711 DumpBuildInformation = "";
1712 return;
1713 }
1714
1715 (*BuildLogFile) << "clang-cc command line arguments: ";
1716 for (unsigned i = 0; i != argc; ++i)
1717 (*BuildLogFile) << argv[i] << ' ';
1718 (*BuildLogFile) << '\n';
Mike Stump1eb44332009-09-09 15:08:12 +00001719
Chris Lattner75a97cb2009-04-17 21:05:01 +00001720 // LoggingDiagnosticClient - Insert a new logging diagnostic client in between
1721 // the diagnostic producers and the normal receiver.
1722 DiagClient.reset(new LoggingDiagnosticClient(DiagClient.take()));
1723}
1724
1725
1726
1727//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +00001728// Main driver
1729//===----------------------------------------------------------------------===//
1730
Chris Lattner92bcc272009-08-23 02:59:41 +00001731static llvm::raw_ostream *ComputeOutFile(const std::string &InFile,
1732 const char *Extension,
Eli Friedman66d6f042009-05-18 22:20:00 +00001733 bool Binary,
1734 llvm::sys::Path& OutPath) {
Chris Lattner92bcc272009-08-23 02:59:41 +00001735 llvm::raw_ostream *Ret;
Eli Friedman66d6f042009-05-18 22:20:00 +00001736 std::string OutFile;
Chris Lattner92bcc272009-08-23 02:59:41 +00001737 if (!OutputFile.empty())
Eli Friedman66d6f042009-05-18 22:20:00 +00001738 OutFile = OutputFile;
Chris Lattner92bcc272009-08-23 02:59:41 +00001739 else if (InFile == "-") {
1740 OutFile = "-";
Eli Friedman66d6f042009-05-18 22:20:00 +00001741 } else if (Extension) {
1742 llvm::sys::Path Path(InFile);
1743 Path.eraseSuffix();
1744 Path.appendSuffix(Extension);
Chris Lattnerd57a7ef2009-08-23 22:45:33 +00001745 OutFile = Path.str();
Eli Friedman66d6f042009-05-18 22:20:00 +00001746 } else {
Chris Lattner92bcc272009-08-23 02:59:41 +00001747 OutFile = "-";
Chris Lattner8a5c8092009-02-18 01:20:05 +00001748 }
Seo Sanghyeonfe947ad2007-12-24 01:52:34 +00001749
Chris Lattner92bcc272009-08-23 02:59:41 +00001750 std::string Error;
1751 Ret = new llvm::raw_fd_ostream(OutFile.c_str(), Error,
Dan Gohmanb044c472009-08-25 15:36:09 +00001752 (Binary ? llvm::raw_fd_ostream::F_Binary : 0));
Chris Lattner92bcc272009-08-23 02:59:41 +00001753 if (!Error.empty()) {
1754 // FIXME: Don't fail this way.
1755 llvm::errs() << "ERROR: " << Error << "\n";
1756 ::exit(1);
Ted Kremenekdb094a22007-12-05 18:27:04 +00001757 }
Mike Stump1eb44332009-09-09 15:08:12 +00001758
Chris Lattner92bcc272009-08-23 02:59:41 +00001759 if (OutFile != "-")
1760 OutPath = OutFile;
Eli Friedman66d6f042009-05-18 22:20:00 +00001761
1762 return Ret;
Ted Kremenekdb094a22007-12-05 18:27:04 +00001763}
1764
Reid Spencer5f016e22007-07-11 17:01:13 +00001765/// ProcessInputFile - Process a single input file with the specified state.
1766///
Ted Kremenek339b9c22008-04-17 22:31:54 +00001767static void ProcessInputFile(Preprocessor &PP, PreprocessorFactory &PPF,
Daniel Dunbar868bd0a2009-05-06 03:16:41 +00001768 const std::string &InFile, ProgActions PA,
Owen Anderson42253cc2009-07-01 17:00:06 +00001769 const llvm::StringMap<bool> &Features,
Owen Anderson8f1ca782009-07-01 23:14:14 +00001770 llvm::LLVMContext& Context) {
Eli Friedman66d6f042009-05-18 22:20:00 +00001771 llvm::OwningPtr<llvm::raw_ostream> OS;
Ted Kremenek7e7e6252008-08-08 02:46:37 +00001772 llvm::OwningPtr<ASTConsumer> Consumer;
Chris Lattnerbd247762007-07-22 06:05:44 +00001773 bool ClearSourceMgr = false;
Douglas Gregor558cb562009-04-02 01:08:08 +00001774 FixItRewriter *FixItRewrite = 0;
Douglas Gregorf807fe02009-04-14 16:27:31 +00001775 bool CompleteTranslationUnit = true;
Eli Friedman66d6f042009-05-18 22:20:00 +00001776 llvm::sys::Path OutPath;
Douglas Gregor558cb562009-04-02 01:08:08 +00001777
Ted Kremenek85888962008-10-21 00:54:44 +00001778 switch (PA) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001779 default:
Eli Friedman66d6f042009-05-18 22:20:00 +00001780 fprintf(stderr, "Unexpected program action!\n");
1781 HadErrors = true;
1782 return;
1783
1784 case ASTPrint:
1785 OS.reset(ComputeOutFile(InFile, 0, false, OutPath));
1786 Consumer.reset(CreateASTPrinter(OS.get()));
1787 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001788
Douglas Gregoree75c052009-05-21 20:55:50 +00001789 case ASTPrintXML:
1790 OS.reset(ComputeOutFile(InFile, "xml", false, OutPath));
1791 Consumer.reset(CreateASTPrinterXML(OS.get()));
1792 break;
1793
Eli Friedman66d6f042009-05-18 22:20:00 +00001794 case ASTDump:
Douglas Gregor4fe0c8e2009-05-30 00:08:05 +00001795 Consumer.reset(CreateASTDumper());
Eli Friedman66d6f042009-05-18 22:20:00 +00001796 break;
1797
Eli Friedman66d6f042009-05-18 22:20:00 +00001798 case ASTView:
Douglas Gregor4fe0c8e2009-05-30 00:08:05 +00001799 Consumer.reset(CreateASTViewer());
Eli Friedman66d6f042009-05-18 22:20:00 +00001800 break;
1801
1802 case PrintDeclContext:
1803 Consumer.reset(CreateDeclContextPrinter());
1804 break;
1805
1806 case EmitHTML:
1807 OS.reset(ComputeOutFile(InFile, 0, true, OutPath));
1808 Consumer.reset(CreateHTMLPrinter(OS.get(), PP.getDiagnostics(), &PP, &PPF));
1809 break;
1810
1811 case InheritanceView:
1812 Consumer.reset(CreateInheritanceViewer(InheritanceViewCls));
1813 break;
1814
1815 case EmitAssembly:
1816 case EmitLLVM:
Mike Stump1eb44332009-09-09 15:08:12 +00001817 case EmitBC:
Eli Friedman66d6f042009-05-18 22:20:00 +00001818 case EmitLLVMOnly: {
1819 BackendAction Act;
1820 if (ProgAction == EmitAssembly) {
1821 Act = Backend_EmitAssembly;
1822 OS.reset(ComputeOutFile(InFile, "s", true, OutPath));
1823 } else if (ProgAction == EmitLLVM) {
1824 Act = Backend_EmitLL;
1825 OS.reset(ComputeOutFile(InFile, "ll", true, OutPath));
1826 } else if (ProgAction == EmitLLVMOnly) {
1827 Act = Backend_EmitNothing;
1828 } else {
1829 Act = Backend_EmitBC;
1830 OS.reset(ComputeOutFile(InFile, "bc", true, OutPath));
Ted Kremenekdb094a22007-12-05 18:27:04 +00001831 }
Ted Kremenekfdfc1982007-12-19 22:24:34 +00001832
Eli Friedman66d6f042009-05-18 22:20:00 +00001833 CompileOptions Opts;
1834 InitializeCompileOptions(Opts, PP.getLangOptions(), Features);
1835 Consumer.reset(CreateBackendConsumer(Act, PP.getDiagnostics(),
1836 PP.getLangOptions(), Opts, InFile,
Owen Anderson42253cc2009-07-01 17:00:06 +00001837 OS.get(), Context));
Ted Kremenekdb094a22007-12-05 18:27:04 +00001838 break;
Eli Friedman66d6f042009-05-18 22:20:00 +00001839 }
1840
1841 case GeneratePCH:
Douglas Gregore650c8c2009-07-07 00:12:59 +00001842 if (RelocatablePCH.getValue() && !isysroot.getNumOccurrences()) {
1843 PP.Diag(SourceLocation(), diag::err_relocatable_without_without_isysroot);
1844 RelocatablePCH.setValue(false);
1845 }
Mike Stump1eb44332009-09-09 15:08:12 +00001846
Eli Friedman66d6f042009-05-18 22:20:00 +00001847 OS.reset(ComputeOutFile(InFile, 0, true, OutPath));
Douglas Gregore650c8c2009-07-07 00:12:59 +00001848 if (RelocatablePCH.getValue())
1849 Consumer.reset(CreatePCHGenerator(PP, OS.get(), isysroot.c_str()));
1850 else
1851 Consumer.reset(CreatePCHGenerator(PP, OS.get()));
Eli Friedman66d6f042009-05-18 22:20:00 +00001852 CompleteTranslationUnit = false;
1853 break;
1854
1855 case RewriteObjC:
1856 OS.reset(ComputeOutFile(InFile, "cpp", true, OutPath));
Eli Friedmanbce831b2009-05-18 22:29:17 +00001857 Consumer.reset(CreateObjCRewriter(InFile, OS.get(), PP.getDiagnostics(),
Eli Friedmanc6d656e2009-05-18 22:39:16 +00001858 PP.getLangOptions(),
1859 SilenceRewriteMacroWarning));
Eli Friedman66d6f042009-05-18 22:20:00 +00001860 break;
1861
1862 case RewriteBlocks:
1863 Consumer.reset(CreateBlockRewriter(InFile, PP.getDiagnostics(),
1864 PP.getLangOptions()));
1865 break;
1866
Eli Friedmane71b85f2009-05-19 10:18:02 +00001867 case RunAnalysis: {
Eli Friedman66d6f042009-05-18 22:20:00 +00001868 Consumer.reset(CreateAnalysisConsumer(PP.getDiagnostics(), &PP, &PPF,
Eli Friedmane71b85f2009-05-19 10:18:02 +00001869 PP.getLangOptions(), OutputFile,
1870 ReadAnalyzerOptions()));
Eli Friedman66d6f042009-05-18 22:20:00 +00001871 break;
Eli Friedmane71b85f2009-05-19 10:18:02 +00001872 }
Eli Friedman66d6f042009-05-18 22:20:00 +00001873
Chris Lattnerc106c102008-10-12 05:03:36 +00001874 case DumpRawTokens: {
Chris Lattner47099742009-02-18 01:51:21 +00001875 llvm::TimeRegion Timer(ClangFrontendTimer);
Chris Lattnerc106c102008-10-12 05:03:36 +00001876 SourceManager &SM = PP.getSourceManager();
Chris Lattnerc106c102008-10-12 05:03:36 +00001877 // Start lexing the specified input file.
Chris Lattner025c3a62009-01-17 07:35:14 +00001878 Lexer RawLex(SM.getMainFileID(), SM, PP.getLangOptions());
Chris Lattnerc106c102008-10-12 05:03:36 +00001879 RawLex.SetKeepWhitespaceMode(true);
1880
1881 Token RawTok;
Chris Lattnerc106c102008-10-12 05:03:36 +00001882 RawLex.LexFromRawLexer(RawTok);
1883 while (RawTok.isNot(tok::eof)) {
1884 PP.DumpToken(RawTok, true);
1885 fprintf(stderr, "\n");
1886 RawLex.LexFromRawLexer(RawTok);
1887 }
1888 ClearSourceMgr = true;
1889 break;
1890 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001891 case DumpTokens: { // Token dump mode.
Chris Lattner47099742009-02-18 01:51:21 +00001892 llvm::TimeRegion Timer(ClangFrontendTimer);
Chris Lattnerd2177732007-07-20 16:59:19 +00001893 Token Tok;
Chris Lattnerc106c102008-10-12 05:03:36 +00001894 // Start preprocessing the specified input file.
Ted Kremenek95041a22007-12-19 22:51:13 +00001895 PP.EnterMainSourceFile();
Reid Spencer5f016e22007-07-11 17:01:13 +00001896 do {
1897 PP.Lex(Tok);
1898 PP.DumpToken(Tok, true);
1899 fprintf(stderr, "\n");
Chris Lattner057aaf62007-10-09 18:03:42 +00001900 } while (Tok.isNot(tok::eof));
Chris Lattnerbd247762007-07-22 06:05:44 +00001901 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001902 break;
1903 }
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001904 case RunPreprocessorOnly:
Reid Spencer5f016e22007-07-11 17:01:13 +00001905 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001906
Douglas Gregorbf1bd6e2009-04-02 23:43:50 +00001907 case GeneratePTH: {
Chris Lattner47099742009-02-18 01:51:21 +00001908 llvm::TimeRegion Timer(ClangFrontendTimer);
Eli Friedmanf54fce82009-05-19 01:02:07 +00001909 if (OutputFile.empty() || OutputFile == "-") {
1910 // FIXME: Don't fail this way.
1911 // FIXME: Verify that we can actually seek in the given file.
Chris Lattner92bcc272009-08-23 02:59:41 +00001912 llvm::errs() << "ERROR: PTH requires an seekable file for output!\n";
Eli Friedmanf54fce82009-05-19 01:02:07 +00001913 ::exit(1);
1914 }
1915 OS.reset(ComputeOutFile(InFile, 0, true, OutPath));
1916 CacheTokens(PP, static_cast<llvm::raw_fd_ostream*>(OS.get()));
Ted Kremenek85888962008-10-21 00:54:44 +00001917 ClearSourceMgr = true;
1918 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001919 }
Douglas Gregor6ab35242009-04-09 21:40:53 +00001920
Chris Lattnercc7dea82009-04-27 22:02:30 +00001921 case PrintPreprocessedInput:
Eli Friedmanf54fce82009-05-19 01:02:07 +00001922 OS.reset(ComputeOutFile(InFile, 0, true, OutPath));
Reid Spencer5f016e22007-07-11 17:01:13 +00001923 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001924
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001925 case ParseNoop:
Reid Spencer5f016e22007-07-11 17:01:13 +00001926 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001927
Chris Lattner47099742009-02-18 01:51:21 +00001928 case ParsePrintCallbacks: {
1929 llvm::TimeRegion Timer(ClangFrontendTimer);
Eli Friedmanf54fce82009-05-19 01:02:07 +00001930 OS.reset(ComputeOutFile(InFile, 0, true, OutPath));
1931 ParseFile(PP, CreatePrintParserActionsAction(PP, OS.get()));
Chris Lattnerbd247762007-07-22 06:05:44 +00001932 ClearSourceMgr = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001933 break;
Chris Lattner47099742009-02-18 01:51:21 +00001934 }
1935
1936 case ParseSyntaxOnly: { // -fsyntax-only
1937 llvm::TimeRegion Timer(ClangFrontendTimer);
Ted Kremenek7e7e6252008-08-08 02:46:37 +00001938 Consumer.reset(new ASTConsumer());
Ted Kremenek2bf55142007-09-17 20:49:30 +00001939 break;
Chris Lattner47099742009-02-18 01:51:21 +00001940 }
Mike Stump1eb44332009-09-09 15:08:12 +00001941
Chris Lattnerb57e3d42008-05-08 06:52:13 +00001942 case RewriteMacros:
Eli Friedmanf54fce82009-05-19 01:02:07 +00001943 OS.reset(ComputeOutFile(InFile, 0, true, OutPath));
1944 RewriteMacrosInInput(PP, OS.get());
Chris Lattnerb57e3d42008-05-08 06:52:13 +00001945 ClearSourceMgr = true;
1946 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001947
Eli Friedmanf54fce82009-05-19 01:02:07 +00001948 case RewriteTest:
1949 OS.reset(ComputeOutFile(InFile, 0, true, OutPath));
1950 DoRewriteTest(PP, OS.get());
Chris Lattnerb13c5ee2008-10-12 05:29:20 +00001951 ClearSourceMgr = true;
1952 break;
Douglas Gregor558cb562009-04-02 01:08:08 +00001953
1954 case FixIt:
1955 llvm::TimeRegion Timer(ClangFrontendTimer);
1956 Consumer.reset(new ASTConsumer());
Douglas Gregorde4bf6a2009-04-02 17:13:00 +00001957 FixItRewrite = new FixItRewriter(PP.getDiagnostics(),
Chris Lattner2c78b872009-04-14 23:22:57 +00001958 PP.getSourceManager(),
1959 PP.getLangOptions());
Douglas Gregor558cb562009-04-02 01:08:08 +00001960 break;
Chris Lattner47099742009-02-18 01:51:21 +00001961 }
Ted Kremenek46157b52009-01-28 04:29:29 +00001962
Chris Lattner1aee61a2009-04-27 21:25:27 +00001963 if (FixItAtLocations.size() > 0) {
1964 // Even without the "-fixit" flag, with may have some specific
1965 // locations where the user has requested fixes. Process those
1966 // locations now.
1967 if (!FixItRewrite)
1968 FixItRewrite = new FixItRewriter(PP.getDiagnostics(),
1969 PP.getSourceManager(),
1970 PP.getLangOptions());
Chris Lattner9ecd26a2009-03-28 01:37:17 +00001971
Chris Lattner1aee61a2009-04-27 21:25:27 +00001972 bool AddedFixitLocation = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001973 for (unsigned Idx = 0, Last = FixItAtLocations.size();
Chris Lattner1aee61a2009-04-27 21:25:27 +00001974 Idx != Last; ++Idx) {
1975 RequestedSourceLocation Requested;
Argyrios Kyrtzidis34d25d82009-06-23 22:01:39 +00001976 if (ResolveParsedLocation(FixItAtLocations[Idx],
1977 PP.getFileManager(), Requested)) {
Chris Lattner1aee61a2009-04-27 21:25:27 +00001978 fprintf(stderr, "FIX-IT could not find file \"%s\"\n",
1979 FixItAtLocations[Idx].FileName.c_str());
1980 } else {
1981 FixItRewrite->addFixItLocation(Requested);
1982 AddedFixitLocation = true;
Douglas Gregor26df2f02009-04-02 19:05:20 +00001983 }
1984 }
1985
Chris Lattner1aee61a2009-04-27 21:25:27 +00001986 if (!AddedFixitLocation) {
1987 // All of the fix-it locations were bad. Don't fix anything.
1988 delete FixItRewrite;
1989 FixItRewrite = 0;
1990 }
1991 }
1992
1993 llvm::OwningPtr<ASTContext> ContextOwner;
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001994 if (Consumer)
Chris Lattner9ecd26a2009-03-28 01:37:17 +00001995 ContextOwner.reset(new ASTContext(PP.getLangOptions(),
1996 PP.getSourceManager(),
1997 PP.getTargetInfo(),
1998 PP.getIdentifierTable(),
1999 PP.getSelectorTable(),
Chris Lattner1b63e4f2009-06-14 01:54:56 +00002000 PP.getBuiltinInfo(),
Douglas Gregor2deaea32009-04-22 18:49:13 +00002001 /* FreeMemory = */ !DisableFree,
Chris Lattner1b63e4f2009-06-14 01:54:56 +00002002 /* size_reserve = */0));
Mike Stump1eb44332009-09-09 15:08:12 +00002003
Chris Lattnercc7dea82009-04-27 22:02:30 +00002004 llvm::OwningPtr<PCHReader> Reader;
2005 llvm::OwningPtr<ExternalASTSource> Source;
Mike Stump1eb44332009-09-09 15:08:12 +00002006
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002007 if (!ImplicitIncludePCH.empty()) {
Douglas Gregore650c8c2009-07-07 00:12:59 +00002008 // If the user specified -isysroot, it will be used for relocatable PCH
2009 // files.
2010 const char *isysrootPCH = 0;
2011 if (isysroot.getNumOccurrences() != 0)
2012 isysrootPCH = isysroot.c_str();
Mike Stump1eb44332009-09-09 15:08:12 +00002013
Douglas Gregore650c8c2009-07-07 00:12:59 +00002014 Reader.reset(new PCHReader(PP, ContextOwner.get(), isysrootPCH));
Mike Stump1eb44332009-09-09 15:08:12 +00002015
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002016 // The user has asked us to include a precompiled header. Load
2017 // the precompiled header into the AST context.
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002018 switch (Reader->ReadPCH(ImplicitIncludePCH)) {
2019 case PCHReader::Success: {
Douglas Gregore721f952009-04-28 18:58:38 +00002020 // Set the predefines buffer as suggested by the PCH
2021 // reader. Typically, the predefines buffer will be empty.
2022 PP.setPredefines(Reader->getSuggestedPredefines());
2023
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002024 // Attach the PCH reader to the AST context as an external AST
2025 // source, so that declarations will be deserialized from the
2026 // PCH file as needed.
Chris Lattnercc7dea82009-04-27 22:02:30 +00002027 if (ContextOwner) {
2028 Source.reset(Reader.take());
Douglas Gregore1d918e2009-04-10 23:10:45 +00002029 ContextOwner->setExternalSource(Source);
Chris Lattnercc7dea82009-04-27 22:02:30 +00002030 }
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002031 break;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002032 }
2033
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002034 case PCHReader::Failure:
2035 // Unrecoverable failure: don't even try to process the input
2036 // file.
2037 return;
2038
2039 case PCHReader::IgnorePCH:
Douglas Gregor1ab86ac2009-04-28 22:01:16 +00002040 // No suitable PCH file could be found. Return an error.
2041 return;
2042
2043#if 0
2044 // FIXME: We can recover from failed attempts to load PCH
2045 // files. This code will do so, if we ever want to enable it.
2046
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002047 // We delayed the initialization of builtins in the hope of
2048 // loading the PCH file. Since the PCH file could not be
2049 // loaded, initialize builtins now.
2050 if (ContextOwner)
2051 ContextOwner->InitializeBuiltins(PP.getIdentifierTable());
Douglas Gregor1ab86ac2009-04-28 22:01:16 +00002052#endif
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002053 }
2054
2055 // Finish preprocessor initialization. We do this now (rather
2056 // than earlier) because this initialization creates new source
2057 // location entries in the source manager, which must come after
2058 // the source location entries for the PCH file.
2059 if (InitializeSourceManager(PP, InFile))
2060 return;
Ted Kremenek46157b52009-01-28 04:29:29 +00002061 }
Daniel Dunbar879c3ea2008-10-27 22:03:52 +00002062
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002063
2064 // If we have an ASTConsumer, run the parser with it.
2065 if (Consumer)
Mike Stump1eb44332009-09-09 15:08:12 +00002066 ParseAST(PP, Consumer.get(), *ContextOwner.get(), Stats,
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002067 CompleteTranslationUnit);
2068
2069 if (PA == RunPreprocessorOnly) { // Just lex as fast as we can, no output.
2070 llvm::TimeRegion Timer(ClangFrontendTimer);
2071 Token Tok;
2072 // Start parsing the specified input file.
2073 PP.EnterMainSourceFile();
2074 do {
2075 PP.Lex(Tok);
2076 } while (Tok.isNot(tok::eof));
2077 ClearSourceMgr = true;
2078 } else if (PA == ParseNoop) { // -parse-noop
2079 llvm::TimeRegion Timer(ClangFrontendTimer);
2080 ParseFile(PP, new MinimalAction(PP));
2081 ClearSourceMgr = true;
Chris Lattnercc7dea82009-04-27 22:02:30 +00002082 } else if (PA == PrintPreprocessedInput){ // -E mode.
2083 llvm::TimeRegion Timer(ClangFrontendTimer);
Eli Friedman12d3b1d2009-05-19 03:06:47 +00002084 if (DumpMacros)
2085 DoPrintMacros(PP, OS.get());
2086 else
2087 DoPrintPreprocessedInput(PP, OS.get(), EnableCommentOutput,
2088 EnableMacroCommentOutput,
2089 DisableLineMarkers, DumpDefines);
Chris Lattnercc7dea82009-04-27 22:02:30 +00002090 ClearSourceMgr = true;
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002091 }
Mike Stump1eb44332009-09-09 15:08:12 +00002092
Chris Lattner1aee61a2009-04-27 21:25:27 +00002093 if (FixItRewrite)
2094 FixItRewrite->WriteFixedFile(InFile, OutputFile);
Daniel Dunbar70186ab2009-07-29 02:40:09 +00002095
2096 // Disable the consumer prior to the context, the consumer may perform actions
2097 // in its destructor which require the context.
2098 if (DisableFree)
2099 Consumer.take();
2100 else
2101 Consumer.reset();
Mike Stump1eb44332009-09-09 15:08:12 +00002102
Chris Lattner1aee61a2009-04-27 21:25:27 +00002103 // If in -disable-free mode, don't deallocate ASTContext.
2104 if (DisableFree)
2105 ContextOwner.take();
2106 else
2107 ContextOwner.reset(); // Delete ASTContext
Eli Friedman66d6f042009-05-18 22:20:00 +00002108
Daniel Dunbar879c3ea2008-10-27 22:03:52 +00002109 if (VerifyDiagnostics)
Daniel Dunbar276373d2008-10-27 22:10:13 +00002110 if (CheckDiagnostics(PP))
2111 exit(1);
Chris Lattnere66b65c2008-02-06 01:42:25 +00002112
Reid Spencer5f016e22007-07-11 17:01:13 +00002113 if (Stats) {
Ted Kremenekfdfc1982007-12-19 22:24:34 +00002114 fprintf(stderr, "\nSTATISTICS FOR '%s':\n", InFile.c_str());
Reid Spencer5f016e22007-07-11 17:01:13 +00002115 PP.PrintStats();
2116 PP.getIdentifierTable().PrintStats();
Chris Lattnerdee73592007-12-15 20:48:40 +00002117 PP.getHeaderSearchInfo().PrintStats();
Ted Kremenek1b95a652009-01-09 18:20:21 +00002118 PP.getSourceManager().PrintStats();
Reid Spencer5f016e22007-07-11 17:01:13 +00002119 fprintf(stderr, "\n");
2120 }
Chris Lattnerbd247762007-07-22 06:05:44 +00002121
Mike Stump1eb44332009-09-09 15:08:12 +00002122 // For a multi-file compilation, some things are ok with nuking the source
Chris Lattnerbd247762007-07-22 06:05:44 +00002123 // manager tables, other require stable fileid/macroid's across multiple
2124 // files.
Chris Lattnerdee73592007-12-15 20:48:40 +00002125 if (ClearSourceMgr)
2126 PP.getSourceManager().clearIDTables();
Daniel Dunbard68ba0e2008-11-11 06:35:39 +00002127
Eli Friedman66d6f042009-05-18 22:20:00 +00002128 // Always delete the output stream because we don't want to leak file
2129 // handles. Also, we don't want to try to erase an open file.
2130 OS.reset();
2131
2132 if ((HadErrors || (PP.getDiagnostics().getNumErrors() != 0)) &&
2133 !OutPath.isEmpty()) {
2134 // If we had errors, try to erase the output file.
2135 OutPath.eraseFromDisk();
2136 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002137}
2138
2139static llvm::cl::list<std::string>
2140InputFilenames(llvm::cl::Positional, llvm::cl::desc("<input files>"));
2141
Daniel Dunbar70121eb2009-08-10 03:40:28 +00002142static void LLVMErrorHandler(void *UserData, const std::string &Message) {
2143 Diagnostic &Diags = *static_cast<Diagnostic*>(UserData);
2144
2145 Diags.Report(FullSourceLoc(), diag::err_fe_error_backend) << Message;
2146
2147 // We cannot recover from llvm errors.
2148 exit(1);
2149}
2150
Reid Spencer5f016e22007-07-11 17:01:13 +00002151int main(int argc, char **argv) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002152 llvm::sys::PrintStackTraceOnErrorSignal();
Chris Lattner09e94a32009-03-04 21:41:39 +00002153 llvm::PrettyStackTraceProgram X(argc, argv);
Owen Andersond7200462009-07-16 00:14:12 +00002154 llvm::LLVMContext &Context = llvm::getGlobalContext();
Daniel Dunbard6970812009-09-02 23:20:15 +00002155
Daniel Dunbar4d861512009-09-03 04:54:12 +00002156 // Initialize targets first, so that --version shows registered targets.
Chris Lattner2fe11942009-06-17 17:25:50 +00002157 llvm::InitializeAllTargets();
2158 llvm::InitializeAllAsmPrinters();
Daniel Dunbard6970812009-09-02 23:20:15 +00002159
2160 llvm::cl::ParseCommandLineOptions(argc, argv,
2161 "LLVM 'Clang' Compiler: http://clang.llvm.org\n");
Mike Stump1eb44332009-09-09 15:08:12 +00002162
Chris Lattner47099742009-02-18 01:51:21 +00002163 if (TimeReport)
2164 ClangFrontendTimer = new llvm::Timer("Clang front-end time");
Mike Stump1eb44332009-09-09 15:08:12 +00002165
Daniel Dunbar08e6dc62009-05-28 16:37:33 +00002166 if (Verbose)
Mike Stump3cbf5a02009-09-15 21:49:22 +00002167 llvm::errs() << "clang-cc version " CLANG_VERSION_STRING
2168 << " based upon " << PACKAGE_STRING
Daniel Dunbar2e30e592009-09-04 17:43:10 +00002169 << " hosted on " << llvm::sys::getHostTriple() << "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00002170
Reid Spencer5f016e22007-07-11 17:01:13 +00002171 // If no input was specified, read from stdin.
2172 if (InputFilenames.empty())
2173 InputFilenames.push_back("-");
Douglas Gregor68a0d782009-05-02 00:03:46 +00002174
Ted Kremenek31e703b2007-12-11 23:28:38 +00002175 // Create the diagnostic client for reporting errors or for
2176 // implementing -verify.
Chris Lattner409d4e72009-04-17 20:40:01 +00002177 llvm::OwningPtr<DiagnosticClient> DiagClient;
2178 if (VerifyDiagnostics) {
2179 // When checking diagnostics, just buffer them up.
2180 DiagClient.reset(new TextDiagnosticBuffer());
2181 if (InputFilenames.size() != 1) {
2182 fprintf(stderr, "-verify only works on single input files for now.\n");
2183 return 1;
2184 }
2185 if (!HTMLDiag.empty()) {
2186 fprintf(stderr, "-verify and -html-diags don't work together\n");
2187 return 1;
2188 }
2189 } else if (HTMLDiag.empty()) {
Ted Kremenekb4398aa2008-08-07 17:49:57 +00002190 // Print diagnostics to stderr by default.
Douglas Gregor68a0d782009-05-02 00:03:46 +00002191
2192 // If -fmessage-length=N was not specified, determine whether this
2193 // is a terminal and, if so, implicitly define -fmessage-length
2194 // appropriately.
2195 if (MessageLength.getNumOccurrences() == 0)
Douglas Gregor67187ce2009-05-11 18:06:49 +00002196 MessageLength.setValue(llvm::sys::Process::StandardErrColumns());
Douglas Gregor68a0d782009-05-02 00:03:46 +00002197
Torok Edwin603fca72009-06-04 07:18:23 +00002198 if (!NoColorDiagnostic) {
2199 NoColorDiagnostic.setValue(!llvm::sys::Process::StandardErrHasColors());
2200 }
2201
Chris Lattner409d4e72009-04-17 20:40:01 +00002202 DiagClient.reset(new TextDiagnosticPrinter(llvm::errs(),
Chris Lattnera03a5b52008-11-19 06:56:25 +00002203 !NoShowColumn,
Chris Lattner65f5e642009-01-30 19:01:41 +00002204 !NoCaretDiagnostics,
Chris Lattner1fbee5d2009-03-13 01:08:23 +00002205 !NoShowLocation,
Chris Lattnerd51d74a2009-04-16 05:44:38 +00002206 PrintSourceRangeInfo,
Chris Lattneraa5bf2e2009-04-19 07:44:08 +00002207 PrintDiagnosticOption,
Douglas Gregorfffd93f2009-05-01 21:53:04 +00002208 !NoDiagnosticsFixIt,
Torok Edwin603fca72009-06-04 07:18:23 +00002209 MessageLength,
2210 !NoColorDiagnostic));
Ted Kremenekb4398aa2008-08-07 17:49:57 +00002211 } else {
Chris Lattner409d4e72009-04-17 20:40:01 +00002212 DiagClient.reset(CreateHTMLDiagnosticClient(HTMLDiag));
Reid Spencer5f016e22007-07-11 17:01:13 +00002213 }
Mike Stump1eb44332009-09-09 15:08:12 +00002214
Chris Lattner75a97cb2009-04-17 21:05:01 +00002215 if (!DumpBuildInformation.empty()) {
2216 if (!HTMLDiag.empty()) {
2217 fprintf(stderr,
2218 "-dump-build-information and -html-diags don't work together\n");
2219 return 1;
2220 }
Mike Stump1eb44332009-09-09 15:08:12 +00002221
Chris Lattner75a97cb2009-04-17 21:05:01 +00002222 SetUpBuildDumpLog(argc, argv, DiagClient);
2223 }
Mike Stump1eb44332009-09-09 15:08:12 +00002224
Ted Kremenekb4398aa2008-08-07 17:49:57 +00002225
Reid Spencer5f016e22007-07-11 17:01:13 +00002226 // Configure our handling of diagnostics.
Ted Kremenekb4398aa2008-08-07 17:49:57 +00002227 Diagnostic Diags(DiagClient.get());
Eli Friedman0eeb86e2009-05-19 01:17:04 +00002228 if (ProcessWarningOptions(Diags, OptWarnings, OptPedantic, OptPedanticErrors,
2229 OptNoWarnings))
Sebastian Redl63a9e0f2009-03-06 17:41:35 +00002230 return 1;
Ted Kremenek31e703b2007-12-11 23:28:38 +00002231
Daniel Dunbar70121eb2009-08-10 03:40:28 +00002232 // Set an error handler, so that any LLVM backend diagnostics go through our
2233 // error handler.
2234 llvm::llvm_install_error_handler(LLVMErrorHandler,
2235 static_cast<void*>(&Diags));
2236
Chris Lattner4f037832007-12-05 23:24:17 +00002237 // -I- is a deprecated GCC feature, scan for it and reject it.
2238 for (unsigned i = 0, e = I_dirs.size(); i != e; ++i) {
2239 if (I_dirs[i] == "-") {
Mike Stump1eb44332009-09-09 15:08:12 +00002240 Diags.Report(FullSourceLoc(), diag::err_pp_I_dash_not_supported);
Chris Lattner4f037832007-12-05 23:24:17 +00002241 I_dirs.erase(I_dirs.begin()+i);
2242 --i;
2243 }
2244 }
Chris Lattner11215192008-03-14 06:12:05 +00002245
2246 // Get information about the target being compiled for.
Chris Lattner2f60af72009-09-12 22:45:58 +00002247 llvm::Triple Triple = CreateTargetTriple();
2248 llvm::OwningPtr<TargetInfo>
2249 Target(TargetInfo::CreateTargetInfo(Triple.getTriple()));
Mike Stump1eb44332009-09-09 15:08:12 +00002250
Chris Lattner11215192008-03-14 06:12:05 +00002251 if (Target == 0) {
Mike Stump1eb44332009-09-09 15:08:12 +00002252 Diags.Report(FullSourceLoc(), diag::err_fe_unknown_triple)
Chris Lattner2f60af72009-09-12 22:45:58 +00002253 << Triple.getTriple().c_str();
Sebastian Redlc5613db2009-03-07 12:09:25 +00002254 return 1;
Chris Lattner11215192008-03-14 06:12:05 +00002255 }
Mike Stump1eb44332009-09-09 15:08:12 +00002256
Daniel Dunbar73b79592009-09-14 00:02:12 +00002257 // Set the target ABI if specified.
2258 if (!TargetABI.empty()) {
2259 if (!Target->setABI(TargetABI)) {
2260 Diags.Report(FullSourceLoc(), diag::err_fe_unknown_target_abi)
2261 << TargetABI;
2262 return 1;
2263 }
2264 }
2265
Daniel Dunbard4270232009-01-20 23:17:32 +00002266 if (!InheritanceViewCls.empty()) // C++ visualization?
Ted Kremenek7cae2f62008-10-23 23:36:29 +00002267 ProgAction = InheritanceView;
Mike Stump1eb44332009-09-09 15:08:12 +00002268
Ted Kremenekc0c03bc2008-06-06 22:42:39 +00002269 llvm::OwningPtr<SourceManager> SourceMgr;
Mike Stump1eb44332009-09-09 15:08:12 +00002270
Chris Lattner2c78b872009-04-14 23:22:57 +00002271 // Create a file manager object to provide access to and cache the filesystem.
2272 FileManager FileMgr;
Douglas Gregor4fed3f42009-04-27 18:38:38 +00002273
Daniel Dunbar868bd0a2009-05-06 03:16:41 +00002274 // Compute the feature set, unfortunately this effects the language!
2275 llvm::StringMap<bool> Features;
2276 ComputeFeatureMap(Target.get(), Features);
2277
Reid Spencer5f016e22007-07-11 17:01:13 +00002278 for (unsigned i = 0, e = InputFilenames.size(); i != e; ++i) {
Ted Kremenek31e703b2007-12-11 23:28:38 +00002279 const std::string &InFile = InputFilenames[i];
Mike Stump1eb44332009-09-09 15:08:12 +00002280
Chris Lattnerf63aea32009-03-04 21:40:56 +00002281 /// Create a SourceManager object. This tracks and owns all the file
2282 /// buffers allocated to a translation unit.
2283 if (!SourceMgr)
2284 SourceMgr.reset(new SourceManager());
2285 else
2286 SourceMgr->clearIDTables();
Mike Stump1eb44332009-09-09 15:08:12 +00002287
Chris Lattnerf63aea32009-03-04 21:40:56 +00002288 // Initialize language options, inferring file types from input filenames.
2289 LangOptions LangInfo;
Chris Lattner409d4e72009-04-17 20:40:01 +00002290 DiagClient->setLangOptions(&LangInfo);
Mike Stump1eb44332009-09-09 15:08:12 +00002291
Chris Lattnerf63aea32009-03-04 21:40:56 +00002292 InitializeBaseLanguage();
2293 LangKind LK = GetLanguage(InFile);
Daniel Dunbar0b5b0da2009-04-01 05:09:09 +00002294 InitializeLangOptions(LangInfo, LK);
Daniel Dunbar868bd0a2009-05-06 03:16:41 +00002295 InitializeLanguageStandard(LangInfo, LK, Target.get(), Features);
Mike Stump1eb44332009-09-09 15:08:12 +00002296
Chris Lattnerf63aea32009-03-04 21:40:56 +00002297 // Process the -I options and set them in the HeaderInfo.
2298 HeaderSearch HeaderInfo(FileMgr);
Mike Stump1eb44332009-09-09 15:08:12 +00002299
2300
Chris Lattnerf63aea32009-03-04 21:40:56 +00002301 InitializeIncludePaths(argv[0], HeaderInfo, FileMgr, LangInfo);
Mike Stump1eb44332009-09-09 15:08:12 +00002302
Chris Lattnerf63aea32009-03-04 21:40:56 +00002303 // Set up the preprocessor with these options.
Eli Friedmanf086e3b2009-05-18 07:39:39 +00002304 DriverPreprocessorFactory PPFactory(Diags, LangInfo, *Target,
Chris Lattnerf63aea32009-03-04 21:40:56 +00002305 *SourceMgr.get(), HeaderInfo);
Mike Stump1eb44332009-09-09 15:08:12 +00002306
Chris Lattnerf63aea32009-03-04 21:40:56 +00002307 llvm::OwningPtr<Preprocessor> PP(PPFactory.CreatePreprocessor());
Mike Stump1eb44332009-09-09 15:08:12 +00002308
Chris Lattnerf63aea32009-03-04 21:40:56 +00002309 if (!PP)
2310 continue;
Ted Kremenekb4398aa2008-08-07 17:49:57 +00002311
Eli Friedmanb5c8f8b2009-05-19 03:35:57 +00002312 // Handle generating dependencies, if requested
2313 if (!DependencyFile.empty()) {
2314 llvm::raw_ostream *DependencyOS;
2315 if (DependencyTargets.empty()) {
2316 // FIXME: Use a proper diagnostic
Chris Lattner92bcc272009-08-23 02:59:41 +00002317 llvm::errs() << "-dependency-file requires at least one -MT option\n";
Eli Friedmanb5c8f8b2009-05-19 03:35:57 +00002318 HadErrors = true;
2319 continue;
2320 }
2321 std::string ErrStr;
2322 DependencyOS =
Dan Gohmanb044c472009-08-25 15:36:09 +00002323 new llvm::raw_fd_ostream(DependencyFile.c_str(), ErrStr);
Eli Friedmanb5c8f8b2009-05-19 03:35:57 +00002324 if (!ErrStr.empty()) {
2325 // FIXME: Use a proper diagnostic
Chris Lattner92bcc272009-08-23 02:59:41 +00002326 llvm::errs() << "unable to open dependency file: " + ErrStr;
Eli Friedmanb5c8f8b2009-05-19 03:35:57 +00002327 HadErrors = true;
2328 continue;
2329 }
2330
2331 AttachDependencyFileGen(PP.get(), DependencyOS, DependencyTargets,
2332 DependenciesIncludeSystemHeaders,
2333 PhonyDependencyTarget);
2334 }
2335
Chris Lattner1b63e4f2009-06-14 01:54:56 +00002336 if (ImplicitIncludePCH.empty()) {
2337 if (InitializeSourceManager(*PP.get(), InFile))
2338 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00002339
Chris Lattner1b63e4f2009-06-14 01:54:56 +00002340 // Initialize builtin info.
2341 PP->getBuiltinInfo().InitializeBuiltins(PP->getIdentifierTable(),
Chris Lattner1b63e4f2009-06-14 01:54:56 +00002342 PP->getLangOptions().NoBuiltin);
2343 }
Douglas Gregor14f79002009-04-10 03:52:48 +00002344
Chris Lattner409d4e72009-04-17 20:40:01 +00002345 if (!HTMLDiag.empty())
2346 ((PathDiagnosticClient*)DiagClient.get())->SetPreprocessor(PP.get());
Chris Lattnerf63aea32009-03-04 21:40:56 +00002347
2348 // Process the source file.
Owen Andersonc93f4982009-07-01 21:23:16 +00002349 ProcessInputFile(*PP, PPFactory, InFile, ProgAction, Features, Context);
Mike Stump1eb44332009-09-09 15:08:12 +00002350
Chris Lattner40469652009-04-17 20:16:08 +00002351 HeaderInfo.ClearFileInfo();
Chris Lattner409d4e72009-04-17 20:40:01 +00002352 DiagClient->setLangOptions(0);
Reid Spencer5f016e22007-07-11 17:01:13 +00002353 }
Chris Lattner11215192008-03-14 06:12:05 +00002354
Mike Stumpfc0fed32009-04-28 01:19:10 +00002355 if (!NoCaretDiagnostics)
2356 if (unsigned NumDiagnostics = Diags.getNumDiagnostics())
2357 fprintf(stderr, "%d diagnostic%s generated.\n", NumDiagnostics,
2358 (NumDiagnostics == 1 ? "" : "s"));
Mike Stump1eb44332009-09-09 15:08:12 +00002359
Reid Spencer5f016e22007-07-11 17:01:13 +00002360 if (Stats) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002361 FileMgr.PrintStats();
2362 fprintf(stderr, "\n");
2363 }
Chris Lattner75a97cb2009-04-17 21:05:01 +00002364
2365 delete ClangFrontendTimer;
2366 delete BuildLogFile;
Mike Stump1eb44332009-09-09 15:08:12 +00002367
Daniel Dunbar276373d2008-10-27 22:10:13 +00002368 // If verifying diagnostics and we reached here, all is well.
2369 if (VerifyDiagnostics)
2370 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002371
Daniel Dunbar524b86f2008-10-28 00:38:08 +00002372 // Managed static deconstruction. Useful for making things like
2373 // -time-passes usable.
2374 llvm::llvm_shutdown();
2375
Daniel Dunbarb0adbba2008-10-04 23:42:49 +00002376 return HadErrors || (Diags.getNumErrors() != 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00002377}