blob: 92798c8c292d3de6c5c59e74743f3079883ccbf5 [file] [log] [blame]
Daniel Dunbar2a79e162009-11-13 03:51:44 +00001//===--- CompilerInstance.cpp ---------------------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10#include "clang/Frontend/CompilerInstance.h"
Douglas Gregorf18d0d82010-08-12 23:31:19 +000011#include "clang/Sema/Sema.h"
Daniel Dunbar12ce6942009-11-14 02:47:17 +000012#include "clang/AST/ASTConsumer.h"
Daniel Dunbar5eb81002009-11-13 08:20:47 +000013#include "clang/AST/ASTContext.h"
Daniel Dunbar2a79e162009-11-13 03:51:44 +000014#include "clang/Basic/Diagnostic.h"
Daniel Dunbar16b74492009-11-13 04:12:06 +000015#include "clang/Basic/FileManager.h"
16#include "clang/Basic/SourceManager.h"
Daniel Dunbar2a79e162009-11-13 03:51:44 +000017#include "clang/Basic/TargetInfo.h"
Daniel Dunbar0397af22010-01-13 00:48:06 +000018#include "clang/Basic/Version.h"
Daniel Dunbar22dacfa2009-11-13 05:52:11 +000019#include "clang/Lex/HeaderSearch.h"
20#include "clang/Lex/Preprocessor.h"
21#include "clang/Lex/PTHManager.h"
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +000022#include "clang/Frontend/ChainedDiagnosticClient.h"
Daniel Dunbar0397af22010-01-13 00:48:06 +000023#include "clang/Frontend/FrontendAction.h"
Douglas Gregor21cae202011-09-12 23:31:24 +000024#include "clang/Frontend/FrontendActions.h"
Daniel Dunbarc2f484f2009-11-13 09:36:05 +000025#include "clang/Frontend/FrontendDiagnostic.h"
Daniel Dunbar9df23492011-04-07 18:31:10 +000026#include "clang/Frontend/LogDiagnosticPrinter.h"
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +000027#include "clang/Frontend/TextDiagnosticPrinter.h"
Daniel Dunbarf79dced2009-11-14 03:24:39 +000028#include "clang/Frontend/VerifyDiagnosticsClient.h"
Daniel Dunbar22dacfa2009-11-13 05:52:11 +000029#include "clang/Frontend/Utils.h"
Sebastian Redl6ab7cd82010-08-18 23:57:17 +000030#include "clang/Serialization/ASTReader.h"
Daniel Dunbarc2f484f2009-11-13 09:36:05 +000031#include "clang/Sema/CodeCompleteConsumer.h"
Michael J. Spencer32bef4e2011-01-10 02:34:13 +000032#include "llvm/Support/FileSystem.h"
Daniel Dunbarccb6cb62009-11-14 07:53:04 +000033#include "llvm/Support/MemoryBuffer.h"
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +000034#include "llvm/Support/raw_ostream.h"
Douglas Gregor95dd5582010-03-30 17:33:59 +000035#include "llvm/ADT/Statistic.h"
Kovarththanan Rajaratnamf79bafa2009-11-29 09:57:35 +000036#include "llvm/Support/Timer.h"
Michael J. Spencer03013fa2010-11-29 18:12:39 +000037#include "llvm/Support/Host.h"
38#include "llvm/Support/Path.h"
39#include "llvm/Support/Program.h"
40#include "llvm/Support/Signals.h"
Michael J. Spencer3a321e22010-12-09 17:36:38 +000041#include "llvm/Support/system_error.h"
Dylan Noblesmith16266012011-06-23 12:20:57 +000042#include "llvm/Config/config.h"
Daniel Dunbar2a79e162009-11-13 03:51:44 +000043using namespace clang;
44
Daniel Dunbar42e9f8e42010-02-16 01:54:47 +000045CompilerInstance::CompilerInstance()
Douglas Gregorf62d43d2011-07-19 16:10:42 +000046 : Invocation(new CompilerInvocation()), ModuleManager(0) {
Daniel Dunbar6228ca02010-01-30 21:47:07 +000047}
Daniel Dunbar2a79e162009-11-13 03:51:44 +000048
49CompilerInstance::~CompilerInstance() {
Daniel Dunbar42e9f8e42010-02-16 01:54:47 +000050}
51
Daniel Dunbar6228ca02010-01-30 21:47:07 +000052void CompilerInstance::setInvocation(CompilerInvocation *Value) {
Ted Kremenek4f327862011-03-21 18:40:17 +000053 Invocation = Value;
Daniel Dunbar6228ca02010-01-30 21:47:07 +000054}
55
Daniel Dunbar8a9f5692009-11-14 01:20:40 +000056void CompilerInstance::setDiagnostics(Diagnostic *Value) {
Douglas Gregor28019772010-04-05 23:52:57 +000057 Diagnostics = Value;
Daniel Dunbar8a9f5692009-11-14 01:20:40 +000058}
59
Daniel Dunbar8a9f5692009-11-14 01:20:40 +000060void CompilerInstance::setTarget(TargetInfo *Value) {
Ted Kremenek4f327862011-03-21 18:40:17 +000061 Target = Value;
Daniel Dunbar8a9f5692009-11-14 01:20:40 +000062}
63
64void CompilerInstance::setFileManager(FileManager *Value) {
Ted Kremenek4f327862011-03-21 18:40:17 +000065 FileMgr = Value;
Daniel Dunbar8a9f5692009-11-14 01:20:40 +000066}
67
Ted Kremenek4f327862011-03-21 18:40:17 +000068void CompilerInstance::setSourceManager(SourceManager *Value) {
69 SourceMgr = Value;
Daniel Dunbar8a9f5692009-11-14 01:20:40 +000070}
71
Ted Kremenek4f327862011-03-21 18:40:17 +000072void CompilerInstance::setPreprocessor(Preprocessor *Value) { PP = Value; }
Daniel Dunbar8a9f5692009-11-14 01:20:40 +000073
Ted Kremenek4f327862011-03-21 18:40:17 +000074void CompilerInstance::setASTContext(ASTContext *Value) { Context = Value; }
Daniel Dunbar8a9f5692009-11-14 01:20:40 +000075
Douglas Gregorf18d0d82010-08-12 23:31:19 +000076void CompilerInstance::setSema(Sema *S) {
77 TheSema.reset(S);
78}
79
Daniel Dunbar12ce6942009-11-14 02:47:17 +000080void CompilerInstance::setASTConsumer(ASTConsumer *Value) {
81 Consumer.reset(Value);
82}
83
Daniel Dunbar8a9f5692009-11-14 01:20:40 +000084void CompilerInstance::setCodeCompletionConsumer(CodeCompleteConsumer *Value) {
85 CompletionConsumer.reset(Value);
86}
87
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +000088// Diagnostics
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +000089static void SetUpBuildDumpLog(const DiagnosticOptions &DiagOpts,
Axel Naumann7d0c4cc2010-10-11 09:13:46 +000090 unsigned argc, const char* const *argv,
Kovarththanan Rajaratnam3d67b1e2010-03-17 09:24:48 +000091 Diagnostic &Diags) {
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +000092 std::string ErrorInfo;
Chris Lattner5f9e2722011-07-23 10:55:15 +000093 llvm::OwningPtr<raw_ostream> OS(
Kovarththanan Rajaratnam69247132010-03-17 09:47:30 +000094 new llvm::raw_fd_ostream(DiagOpts.DumpBuildInformation.c_str(), ErrorInfo));
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +000095 if (!ErrorInfo.empty()) {
Kovarththanan Rajaratnam3d67b1e2010-03-17 09:24:48 +000096 Diags.Report(diag::err_fe_unable_to_open_logfile)
97 << DiagOpts.DumpBuildInformation << ErrorInfo;
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +000098 return;
99 }
100
Daniel Dunbardd63b282009-12-11 23:04:35 +0000101 (*OS) << "clang -cc1 command line arguments: ";
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000102 for (unsigned i = 0; i != argc; ++i)
103 (*OS) << argv[i] << ' ';
104 (*OS) << '\n';
105
106 // Chain in a diagnostic client which will log the diagnostics.
107 DiagnosticClient *Logger =
Kovarththanan Rajaratnam69247132010-03-17 09:47:30 +0000108 new TextDiagnosticPrinter(*OS.take(), DiagOpts, /*OwnsOutputStream=*/true);
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000109 Diags.setClient(new ChainedDiagnosticClient(Diags.takeClient(), Logger));
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000110}
111
Daniel Dunbar9df23492011-04-07 18:31:10 +0000112static void SetUpDiagnosticLog(const DiagnosticOptions &DiagOpts,
Daniel Dunbarb6534bb2011-04-07 18:59:02 +0000113 const CodeGenOptions *CodeGenOpts,
Daniel Dunbar9df23492011-04-07 18:31:10 +0000114 Diagnostic &Diags) {
115 std::string ErrorInfo;
116 bool OwnsStream = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000117 raw_ostream *OS = &llvm::errs();
Daniel Dunbar9df23492011-04-07 18:31:10 +0000118 if (DiagOpts.DiagnosticLogFile != "-") {
119 // Create the output stream.
120 llvm::raw_fd_ostream *FileOS(
121 new llvm::raw_fd_ostream(DiagOpts.DiagnosticLogFile.c_str(),
Daniel Dunbare01eceb2011-04-07 20:19:21 +0000122 ErrorInfo, llvm::raw_fd_ostream::F_Append));
Daniel Dunbar9df23492011-04-07 18:31:10 +0000123 if (!ErrorInfo.empty()) {
124 Diags.Report(diag::warn_fe_cc_log_diagnostics_failure)
125 << DiagOpts.DumpBuildInformation << ErrorInfo;
126 } else {
127 FileOS->SetUnbuffered();
128 FileOS->SetUseAtomicWrites(true);
129 OS = FileOS;
130 OwnsStream = true;
131 }
132 }
133
134 // Chain in the diagnostic client which will log the diagnostics.
Daniel Dunbarb6534bb2011-04-07 18:59:02 +0000135 LogDiagnosticPrinter *Logger = new LogDiagnosticPrinter(*OS, DiagOpts,
136 OwnsStream);
137 if (CodeGenOpts)
138 Logger->setDwarfDebugFlags(CodeGenOpts->DwarfDebugFlags);
Daniel Dunbar9df23492011-04-07 18:31:10 +0000139 Diags.setClient(new ChainedDiagnosticClient(Diags.takeClient(), Logger));
140}
141
Douglas Gregore47be3e2010-11-11 00:39:14 +0000142void CompilerInstance::createDiagnostics(int Argc, const char* const *Argv,
Douglas Gregor78243652011-09-13 01:26:44 +0000143 DiagnosticClient *Client,
144 bool ShouldOwnClient) {
Daniel Dunbarb6534bb2011-04-07 18:59:02 +0000145 Diagnostics = createDiagnostics(getDiagnosticOpts(), Argc, Argv, Client,
Douglas Gregor78243652011-09-13 01:26:44 +0000146 ShouldOwnClient, &getCodeGenOpts());
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000147}
148
Douglas Gregor28019772010-04-05 23:52:57 +0000149llvm::IntrusiveRefCntPtr<Diagnostic>
150CompilerInstance::createDiagnostics(const DiagnosticOptions &Opts,
Douglas Gregore47be3e2010-11-11 00:39:14 +0000151 int Argc, const char* const *Argv,
Daniel Dunbarb6534bb2011-04-07 18:59:02 +0000152 DiagnosticClient *Client,
Douglas Gregor78243652011-09-13 01:26:44 +0000153 bool ShouldOwnClient,
Daniel Dunbarb6534bb2011-04-07 18:59:02 +0000154 const CodeGenOptions *CodeGenOpts) {
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000155 llvm::IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
156 llvm::IntrusiveRefCntPtr<Diagnostic> Diags(new Diagnostic(DiagID));
Daniel Dunbar221c7212009-11-14 07:53:24 +0000157
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000158 // Create the diagnostic client for reporting errors or for
159 // implementing -verify.
Douglas Gregore47be3e2010-11-11 00:39:14 +0000160 if (Client)
Douglas Gregor78243652011-09-13 01:26:44 +0000161 Diags->setClient(Client, ShouldOwnClient);
Douglas Gregore47be3e2010-11-11 00:39:14 +0000162 else
163 Diags->setClient(new TextDiagnosticPrinter(llvm::errs(), Opts));
Daniel Dunbarf79dced2009-11-14 03:24:39 +0000164
165 // Chain in -verify checker, if requested.
Douglas Gregor78243652011-09-13 01:26:44 +0000166 if (Opts.VerifyDiagnostics)
167 Diags->setClient(new VerifyDiagnosticsClient(*Diags));
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000168
Daniel Dunbar9df23492011-04-07 18:31:10 +0000169 // Chain in -diagnostic-log-file dumper, if requested.
170 if (!Opts.DiagnosticLogFile.empty())
Daniel Dunbarb6534bb2011-04-07 18:59:02 +0000171 SetUpDiagnosticLog(Opts, CodeGenOpts, *Diags);
Daniel Dunbar9df23492011-04-07 18:31:10 +0000172
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000173 if (!Opts.DumpBuildInformation.empty())
Kovarththanan Rajaratnam3d67b1e2010-03-17 09:24:48 +0000174 SetUpBuildDumpLog(Opts, Argc, Argv, *Diags);
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000175
176 // Configure our handling of diagnostics.
Kovarththanan Rajaratnam5bf932b2010-03-17 09:36:02 +0000177 ProcessWarningOptions(*Diags, Opts);
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000178
Douglas Gregor28019772010-04-05 23:52:57 +0000179 return Diags;
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000180}
181
182// File Manager
183
Daniel Dunbar16b74492009-11-13 04:12:06 +0000184void CompilerInstance::createFileManager() {
Ted Kremenek4f327862011-03-21 18:40:17 +0000185 FileMgr = new FileManager(getFileSystemOpts());
Daniel Dunbar16b74492009-11-13 04:12:06 +0000186}
187
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000188// Source Manager
189
Chris Lattner39b49bc2010-11-23 08:35:12 +0000190void CompilerInstance::createSourceManager(FileManager &FileMgr) {
Ted Kremenek4f327862011-03-21 18:40:17 +0000191 SourceMgr = new SourceManager(getDiagnostics(), FileMgr);
Daniel Dunbar16b74492009-11-13 04:12:06 +0000192}
Daniel Dunbar22dacfa2009-11-13 05:52:11 +0000193
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000194// Preprocessor
195
Daniel Dunbar22dacfa2009-11-13 05:52:11 +0000196void CompilerInstance::createPreprocessor() {
Douglas Gregor6aa52ec2011-08-26 23:56:07 +0000197 const PreprocessorOptions &PPOpts = getPreprocessorOpts();
198
Daniel Dunbar22dacfa2009-11-13 05:52:11 +0000199 // Create a PTH manager if we are using some form of a token cache.
200 PTHManager *PTHMgr = 0;
Daniel Dunbar049d3a02009-11-17 05:52:41 +0000201 if (!PPOpts.TokenCache.empty())
Douglas Gregor6aa52ec2011-08-26 23:56:07 +0000202 PTHMgr = PTHManager::Create(PPOpts.TokenCache, getDiagnostics());
203
Daniel Dunbar22dacfa2009-11-13 05:52:11 +0000204 // Create the Preprocessor.
Douglas Gregor6aa52ec2011-08-26 23:56:07 +0000205 HeaderSearch *HeaderInfo = new HeaderSearch(getFileManager());
Douglas Gregor998b3d32011-09-01 23:39:15 +0000206 PP = new Preprocessor(getDiagnostics(), getLangOpts(), &getTarget(),
Douglas Gregor6aa52ec2011-08-26 23:56:07 +0000207 getSourceManager(), *HeaderInfo, *this, PTHMgr,
208 /*OwnsHeaderSearch=*/true);
209
Daniel Dunbar22dacfa2009-11-13 05:52:11 +0000210 // Note that this is different then passing PTHMgr to Preprocessor's ctor.
211 // That argument is used as the IdentifierInfoLookup argument to
212 // IdentifierTable's ctor.
213 if (PTHMgr) {
Douglas Gregor6aa52ec2011-08-26 23:56:07 +0000214 PTHMgr->setPreprocessor(&*PP);
Daniel Dunbar22dacfa2009-11-13 05:52:11 +0000215 PP->setPTHManager(PTHMgr);
216 }
Douglas Gregor6aa52ec2011-08-26 23:56:07 +0000217
Douglas Gregor94dc8f62010-03-19 16:15:56 +0000218 if (PPOpts.DetailedRecord)
Douglas Gregordca8ee82011-05-06 16:33:08 +0000219 PP->createPreprocessingRecord(
Douglas Gregor6aa52ec2011-08-26 23:56:07 +0000220 PPOpts.DetailedRecordIncludesNestedMacroExpansions);
Douglas Gregor94dc8f62010-03-19 16:15:56 +0000221
Douglas Gregor6aa52ec2011-08-26 23:56:07 +0000222 InitializePreprocessor(*PP, PPOpts, getHeaderSearchOpts(), getFrontendOpts());
223
Douglas Gregor6e975c42011-09-13 23:15:45 +0000224 // Set up the module path, including the hash for the
225 // module-creation options.
226 llvm::SmallString<256> SpecificModuleCache(
227 getHeaderSearchOpts().ModuleCachePath);
228 if (!getHeaderSearchOpts().DisableModuleHash)
229 llvm::sys::path::append(SpecificModuleCache,
230 getInvocation().getModuleHash());
Douglas Gregorfba18aa2011-09-15 22:00:41 +0000231 PP->getHeaderSearchInfo().configureModules(SpecificModuleCache,
232 getPreprocessorOpts().ModuleBuildPath.empty()
233 ? std::string()
234 : getPreprocessorOpts().ModuleBuildPath.back());
Douglas Gregor6e975c42011-09-13 23:15:45 +0000235
Daniel Dunbar22dacfa2009-11-13 05:52:11 +0000236 // Handle generating dependencies, if requested.
Douglas Gregor6aa52ec2011-08-26 23:56:07 +0000237 const DependencyOutputOptions &DepOpts = getDependencyOutputOpts();
Daniel Dunbar22dacfa2009-11-13 05:52:11 +0000238 if (!DepOpts.OutputFile.empty())
239 AttachDependencyFileGen(*PP, DepOpts);
Douglas Gregor6aa52ec2011-08-26 23:56:07 +0000240
Daniel Dunbareef63e02011-02-02 15:41:17 +0000241 // Handle generating header include information, if requested.
242 if (DepOpts.ShowHeaderIncludes)
243 AttachHeaderIncludeGen(*PP);
Daniel Dunbarb34d69b2011-02-02 21:11:31 +0000244 if (!DepOpts.HeaderIncludeOutputFile.empty()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000245 StringRef OutputPath = DepOpts.HeaderIncludeOutputFile;
Daniel Dunbarb34d69b2011-02-02 21:11:31 +0000246 if (OutputPath == "-")
247 OutputPath = "";
Daniel Dunbarda608852011-03-21 19:37:38 +0000248 AttachHeaderIncludeGen(*PP, /*ShowAllHeaders=*/true, OutputPath,
249 /*ShowDepth=*/false);
Daniel Dunbarb34d69b2011-02-02 21:11:31 +0000250 }
Daniel Dunbar22dacfa2009-11-13 05:52:11 +0000251}
Daniel Dunbar5eb81002009-11-13 08:20:47 +0000252
253// ASTContext
254
255void CompilerInstance::createASTContext() {
256 Preprocessor &PP = getPreprocessor();
Ted Kremenek4f327862011-03-21 18:40:17 +0000257 Context = new ASTContext(getLangOpts(), PP.getSourceManager(),
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000258 &getTarget(), PP.getIdentifierTable(),
Ted Kremenek4f327862011-03-21 18:40:17 +0000259 PP.getSelectorTable(), PP.getBuiltinInfo(),
260 /*size_reserve=*/ 0);
Daniel Dunbar5eb81002009-11-13 08:20:47 +0000261}
Daniel Dunbar0f800392009-11-13 08:21:10 +0000262
263// ExternalASTSource
264
Chris Lattner5f9e2722011-07-23 10:55:15 +0000265void CompilerInstance::createPCHExternalASTSource(StringRef Path,
Sebastian Redlffaab3e2010-07-30 00:29:29 +0000266 bool DisablePCHValidation,
Douglas Gregor8ef6c8c2011-02-05 19:42:43 +0000267 bool DisableStatCache,
Sebastian Redlffaab3e2010-07-30 00:29:29 +0000268 void *DeserializationListener){
Daniel Dunbar0f800392009-11-13 08:21:10 +0000269 llvm::OwningPtr<ExternalASTSource> Source;
Sebastian Redl1d9f1fe2010-10-05 16:15:19 +0000270 bool Preamble = getPreprocessorOpts().PrecompiledPreambleBytes.first != 0;
Daniel Dunbar0f800392009-11-13 08:21:10 +0000271 Source.reset(createPCHExternalASTSource(Path, getHeaderSearchOpts().Sysroot,
Douglas Gregor8ef6c8c2011-02-05 19:42:43 +0000272 DisablePCHValidation,
273 DisableStatCache,
Sebastian Redlffaab3e2010-07-30 00:29:29 +0000274 getPreprocessor(), getASTContext(),
Sebastian Redl1d9f1fe2010-10-05 16:15:19 +0000275 DeserializationListener,
276 Preamble));
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000277 ModuleManager = static_cast<ASTReader*>(Source.get());
Daniel Dunbar0f800392009-11-13 08:21:10 +0000278 getASTContext().setExternalSource(Source);
279}
280
281ExternalASTSource *
Chris Lattner5f9e2722011-07-23 10:55:15 +0000282CompilerInstance::createPCHExternalASTSource(StringRef Path,
Daniel Dunbar0f800392009-11-13 08:21:10 +0000283 const std::string &Sysroot,
Douglas Gregorfae3b2f2010-07-27 00:27:13 +0000284 bool DisablePCHValidation,
Douglas Gregor8ef6c8c2011-02-05 19:42:43 +0000285 bool DisableStatCache,
Daniel Dunbar0f800392009-11-13 08:21:10 +0000286 Preprocessor &PP,
Sebastian Redlffaab3e2010-07-30 00:29:29 +0000287 ASTContext &Context,
Sebastian Redl1d9f1fe2010-10-05 16:15:19 +0000288 void *DeserializationListener,
289 bool Preamble) {
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000290 llvm::OwningPtr<ASTReader> Reader;
Douglas Gregorf8a1e512011-09-02 00:26:20 +0000291 Reader.reset(new ASTReader(PP, Context,
Douglas Gregor832d6202011-07-22 16:35:34 +0000292 Sysroot.empty() ? "" : Sysroot.c_str(),
Douglas Gregor8ef6c8c2011-02-05 19:42:43 +0000293 DisablePCHValidation, DisableStatCache));
Daniel Dunbar0f800392009-11-13 08:21:10 +0000294
Sebastian Redlffaab3e2010-07-30 00:29:29 +0000295 Reader->setDeserializationListener(
Sebastian Redl571db7f2010-08-18 23:56:56 +0000296 static_cast<ASTDeserializationListener *>(DeserializationListener));
Douglas Gregor72a9ae12011-07-22 16:00:58 +0000297 switch (Reader->ReadAST(Path,
298 Preamble ? serialization::MK_Preamble
299 : serialization::MK_PCH)) {
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000300 case ASTReader::Success:
Daniel Dunbar0f800392009-11-13 08:21:10 +0000301 // Set the predefines buffer as suggested by the PCH reader. Typically, the
302 // predefines buffer will be empty.
303 PP.setPredefines(Reader->getSuggestedPredefines());
304 return Reader.take();
305
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000306 case ASTReader::Failure:
Daniel Dunbar0f800392009-11-13 08:21:10 +0000307 // Unrecoverable failure: don't even try to process the input file.
308 break;
309
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000310 case ASTReader::IgnorePCH:
Daniel Dunbar0f800392009-11-13 08:21:10 +0000311 // No suitable PCH file could be found. Return an error.
312 break;
313 }
314
315 return 0;
316}
Daniel Dunbarc2f484f2009-11-13 09:36:05 +0000317
318// Code Completion
319
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000320static bool EnableCodeCompletion(Preprocessor &PP,
321 const std::string &Filename,
322 unsigned Line,
323 unsigned Column) {
324 // Tell the source manager to chop off the given file at a specific
325 // line and column.
Chris Lattner39b49bc2010-11-23 08:35:12 +0000326 const FileEntry *Entry = PP.getFileManager().getFile(Filename);
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000327 if (!Entry) {
328 PP.getDiagnostics().Report(diag::err_fe_invalid_code_complete_file)
329 << Filename;
330 return true;
331 }
332
333 // Truncate the named file at the given line/column.
334 PP.SetCodeCompletionPoint(Entry, Line, Column);
335 return false;
336}
337
Daniel Dunbarc2f484f2009-11-13 09:36:05 +0000338void CompilerInstance::createCodeCompletionConsumer() {
339 const ParsedSourceLocation &Loc = getFrontendOpts().CodeCompletionAt;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000340 if (!CompletionConsumer) {
341 CompletionConsumer.reset(
342 createCodeCompletionConsumer(getPreprocessor(),
343 Loc.FileName, Loc.Line, Loc.Column,
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000344 getFrontendOpts().ShowMacrosInCodeCompletion,
Douglas Gregord8e8a582010-05-25 21:41:55 +0000345 getFrontendOpts().ShowCodePatternsInCodeCompletion,
Douglas Gregor8071e422010-08-15 06:18:01 +0000346 getFrontendOpts().ShowGlobalSymbolsInCodeCompletion,
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000347 llvm::outs()));
348 if (!CompletionConsumer)
349 return;
350 } else if (EnableCodeCompletion(getPreprocessor(), Loc.FileName,
351 Loc.Line, Loc.Column)) {
352 CompletionConsumer.reset();
Douglas Gregorc3d43b72010-03-16 06:04:47 +0000353 return;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000354 }
Douglas Gregor2b4074f2009-12-01 05:55:20 +0000355
356 if (CompletionConsumer->isOutputBinary() &&
357 llvm::sys::Program::ChangeStdoutToBinary()) {
358 getPreprocessor().getDiagnostics().Report(diag::err_fe_stdout_binary);
359 CompletionConsumer.reset();
360 }
Daniel Dunbarc2f484f2009-11-13 09:36:05 +0000361}
362
Kovarththanan Rajaratnamf79bafa2009-11-29 09:57:35 +0000363void CompilerInstance::createFrontendTimer() {
364 FrontendTimer.reset(new llvm::Timer("Clang front-end timer"));
365}
366
Daniel Dunbarc2f484f2009-11-13 09:36:05 +0000367CodeCompleteConsumer *
368CompilerInstance::createCodeCompletionConsumer(Preprocessor &PP,
369 const std::string &Filename,
370 unsigned Line,
371 unsigned Column,
Daniel Dunbarc2f484f2009-11-13 09:36:05 +0000372 bool ShowMacros,
Douglas Gregord8e8a582010-05-25 21:41:55 +0000373 bool ShowCodePatterns,
Douglas Gregor8071e422010-08-15 06:18:01 +0000374 bool ShowGlobals,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000375 raw_ostream &OS) {
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000376 if (EnableCodeCompletion(PP, Filename, Line, Column))
Daniel Dunbarc2f484f2009-11-13 09:36:05 +0000377 return 0;
Daniel Dunbarc2f484f2009-11-13 09:36:05 +0000378
379 // Set up the creation routine for code-completion.
Douglas Gregora9f4f622010-10-11 22:12:15 +0000380 return new PrintingCodeCompleteConsumer(ShowMacros, ShowCodePatterns,
Douglas Gregor8071e422010-08-15 06:18:01 +0000381 ShowGlobals, OS);
Daniel Dunbarc2f484f2009-11-13 09:36:05 +0000382}
Daniel Dunbara9204832009-11-13 10:37:48 +0000383
Douglas Gregor467dc882011-08-25 22:30:56 +0000384void CompilerInstance::createSema(TranslationUnitKind TUKind,
Douglas Gregorf18d0d82010-08-12 23:31:19 +0000385 CodeCompleteConsumer *CompletionConsumer) {
386 TheSema.reset(new Sema(getPreprocessor(), getASTContext(), getASTConsumer(),
Douglas Gregor467dc882011-08-25 22:30:56 +0000387 TUKind, CompletionConsumer));
Douglas Gregorf18d0d82010-08-12 23:31:19 +0000388}
389
Daniel Dunbara9204832009-11-13 10:37:48 +0000390// Output Files
391
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000392void CompilerInstance::addOutputFile(const OutputFile &OutFile) {
393 assert(OutFile.OS && "Attempt to add empty stream to output list!");
394 OutputFiles.push_back(OutFile);
Daniel Dunbara9204832009-11-13 10:37:48 +0000395}
396
Kovarththanan Rajaratname51dd7b2010-03-06 12:07:48 +0000397void CompilerInstance::clearOutputFiles(bool EraseFiles) {
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000398 for (std::list<OutputFile>::iterator
Daniel Dunbara9204832009-11-13 10:37:48 +0000399 it = OutputFiles.begin(), ie = OutputFiles.end(); it != ie; ++it) {
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000400 delete it->OS;
401 if (!it->TempFilename.empty()) {
Anders Carlssonaf036a62011-03-06 22:25:35 +0000402 if (EraseFiles) {
403 bool existed;
404 llvm::sys::fs::remove(it->TempFilename, existed);
405 } else {
406 llvm::SmallString<128> NewOutFile(it->Filename);
407
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +0000408 // If '-working-directory' was passed, the output filename should be
409 // relative to that.
Anders Carlsson2e2468e2011-03-14 01:13:54 +0000410 FileMgr->FixupRelativePath(NewOutFile);
Anders Carlssonaf036a62011-03-06 22:25:35 +0000411 if (llvm::error_code ec = llvm::sys::fs::rename(it->TempFilename,
412 NewOutFile.str())) {
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000413 getDiagnostics().Report(diag::err_fe_unable_to_rename_temp)
Anders Carlssonaf036a62011-03-06 22:25:35 +0000414 << it->TempFilename << it->Filename << ec.message();
415
416 bool existed;
417 llvm::sys::fs::remove(it->TempFilename, existed);
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000418 }
419 }
420 } else if (!it->Filename.empty() && EraseFiles)
421 llvm::sys::Path(it->Filename).eraseFromDisk();
422
Daniel Dunbara9204832009-11-13 10:37:48 +0000423 }
424 OutputFiles.clear();
425}
426
Daniel Dunbarf482d592009-11-13 18:32:08 +0000427llvm::raw_fd_ostream *
428CompilerInstance::createDefaultOutputFile(bool Binary,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000429 StringRef InFile,
430 StringRef Extension) {
Daniel Dunbarf482d592009-11-13 18:32:08 +0000431 return createOutputFile(getFrontendOpts().OutputFile, Binary,
Daniel Dunbarff9cd962011-01-31 22:00:42 +0000432 /*RemoveFileOnSignal=*/true, InFile, Extension);
Daniel Dunbarf482d592009-11-13 18:32:08 +0000433}
434
435llvm::raw_fd_ostream *
Chris Lattner5f9e2722011-07-23 10:55:15 +0000436CompilerInstance::createOutputFile(StringRef OutputPath,
Daniel Dunbarff9cd962011-01-31 22:00:42 +0000437 bool Binary, bool RemoveFileOnSignal,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000438 StringRef InFile,
Argyrios Kyrtzidis7e909852011-07-28 00:45:10 +0000439 StringRef Extension,
440 bool UseTemporary) {
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000441 std::string Error, OutputPathName, TempPathName;
Daniel Dunbarf482d592009-11-13 18:32:08 +0000442 llvm::raw_fd_ostream *OS = createOutputFile(OutputPath, Error, Binary,
Daniel Dunbarff9cd962011-01-31 22:00:42 +0000443 RemoveFileOnSignal,
Daniel Dunbarf482d592009-11-13 18:32:08 +0000444 InFile, Extension,
Argyrios Kyrtzidis7e909852011-07-28 00:45:10 +0000445 UseTemporary,
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000446 &OutputPathName,
447 &TempPathName);
Daniel Dunbarf482d592009-11-13 18:32:08 +0000448 if (!OS) {
Daniel Dunbar36043592009-12-03 09:13:30 +0000449 getDiagnostics().Report(diag::err_fe_unable_to_open_output)
450 << OutputPath << Error;
451 return 0;
Daniel Dunbarf482d592009-11-13 18:32:08 +0000452 }
453
454 // Add the output file -- but don't try to remove "-", since this means we are
455 // using stdin.
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000456 addOutputFile(OutputFile((OutputPathName != "-") ? OutputPathName : "",
457 TempPathName, OS));
Daniel Dunbarf482d592009-11-13 18:32:08 +0000458
459 return OS;
460}
461
462llvm::raw_fd_ostream *
Chris Lattner5f9e2722011-07-23 10:55:15 +0000463CompilerInstance::createOutputFile(StringRef OutputPath,
Daniel Dunbarf482d592009-11-13 18:32:08 +0000464 std::string &Error,
465 bool Binary,
Daniel Dunbarff9cd962011-01-31 22:00:42 +0000466 bool RemoveFileOnSignal,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000467 StringRef InFile,
468 StringRef Extension,
Argyrios Kyrtzidis7e909852011-07-28 00:45:10 +0000469 bool UseTemporary,
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000470 std::string *ResultPathName,
471 std::string *TempPathName) {
472 std::string OutFile, TempFile;
Daniel Dunbarf482d592009-11-13 18:32:08 +0000473 if (!OutputPath.empty()) {
474 OutFile = OutputPath;
475 } else if (InFile == "-") {
476 OutFile = "-";
477 } else if (!Extension.empty()) {
478 llvm::sys::Path Path(InFile);
479 Path.eraseSuffix();
480 Path.appendSuffix(Extension);
481 OutFile = Path.str();
482 } else {
483 OutFile = "-";
484 }
Argyrios Kyrtzidis7e909852011-07-28 00:45:10 +0000485
486 llvm::OwningPtr<llvm::raw_fd_ostream> OS;
487 std::string OSFile;
488
489 if (UseTemporary && OutFile != "-") {
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000490 llvm::sys::Path OutPath(OutFile);
491 // Only create the temporary if we can actually write to OutPath, otherwise
492 // we want to fail early.
Michael J. Spencer32bef4e2011-01-10 02:34:13 +0000493 bool Exists;
494 if ((llvm::sys::fs::exists(OutPath.str(), Exists) || !Exists) ||
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000495 (OutPath.isRegularFile() && OutPath.canWrite())) {
496 // Create a temporary file.
Argyrios Kyrtzidis7e909852011-07-28 00:45:10 +0000497 llvm::SmallString<128> TempPath;
498 TempPath = OutFile;
499 TempPath += "-%%%%%%%%";
500 int fd;
501 if (llvm::sys::fs::unique_file(TempPath.str(), fd, TempPath,
502 /*makeAbsolute=*/false) == llvm::errc::success) {
503 OS.reset(new llvm::raw_fd_ostream(fd, /*shouldClose=*/true));
504 OSFile = TempFile = TempPath.str();
505 }
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000506 }
507 }
508
Argyrios Kyrtzidis7e909852011-07-28 00:45:10 +0000509 if (!OS) {
510 OSFile = OutFile;
511 OS.reset(
512 new llvm::raw_fd_ostream(OSFile.c_str(), Error,
513 (Binary ? llvm::raw_fd_ostream::F_Binary : 0)));
514 if (!Error.empty())
515 return 0;
516 }
Daniel Dunbarf482d592009-11-13 18:32:08 +0000517
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000518 // Make sure the out stream file gets removed if we crash.
Daniel Dunbarff9cd962011-01-31 22:00:42 +0000519 if (RemoveFileOnSignal)
520 llvm::sys::RemoveFileOnSignal(llvm::sys::Path(OSFile));
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000521
Daniel Dunbarf482d592009-11-13 18:32:08 +0000522 if (ResultPathName)
523 *ResultPathName = OutFile;
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000524 if (TempPathName)
525 *TempPathName = TempFile;
Daniel Dunbarf482d592009-11-13 18:32:08 +0000526
Daniel Dunbarfc971022009-11-20 22:32:38 +0000527 return OS.take();
Daniel Dunbarf482d592009-11-13 18:32:08 +0000528}
Daniel Dunbarccb6cb62009-11-14 07:53:04 +0000529
530// Initialization Utilities
531
Chris Lattner5f9e2722011-07-23 10:55:15 +0000532bool CompilerInstance::InitializeSourceManager(StringRef InputFile) {
Daniel Dunbarccb6cb62009-11-14 07:53:04 +0000533 return InitializeSourceManager(InputFile, getDiagnostics(), getFileManager(),
534 getSourceManager(), getFrontendOpts());
535}
536
Chris Lattner5f9e2722011-07-23 10:55:15 +0000537bool CompilerInstance::InitializeSourceManager(StringRef InputFile,
Daniel Dunbarccb6cb62009-11-14 07:53:04 +0000538 Diagnostic &Diags,
539 FileManager &FileMgr,
540 SourceManager &SourceMgr,
541 const FrontendOptions &Opts) {
Douglas Gregor414cb642010-11-30 05:23:00 +0000542 // Figure out where to get and map in the main file, unless it's already
543 // been created (e.g., by a precompiled preamble).
544 if (!SourceMgr.getMainFileID().isInvalid()) {
545 // Do nothing: the main file has already been set.
546 } else if (InputFile != "-") {
Chris Lattner39b49bc2010-11-23 08:35:12 +0000547 const FileEntry *File = FileMgr.getFile(InputFile);
Dan Gohman694137c2010-10-26 21:13:51 +0000548 if (!File) {
Daniel Dunbarccb6cb62009-11-14 07:53:04 +0000549 Diags.Report(diag::err_fe_error_reading) << InputFile;
550 return false;
551 }
Dan Gohman694137c2010-10-26 21:13:51 +0000552 SourceMgr.createMainFileID(File);
Daniel Dunbarccb6cb62009-11-14 07:53:04 +0000553 } else {
Michael J. Spencer4eeebc42010-12-16 03:28:14 +0000554 llvm::OwningPtr<llvm::MemoryBuffer> SB;
555 if (llvm::MemoryBuffer::getSTDIN(SB)) {
Michael J. Spencer3a321e22010-12-09 17:36:38 +0000556 // FIXME: Give ec.message() in this diag.
Daniel Dunbarccb6cb62009-11-14 07:53:04 +0000557 Diags.Report(diag::err_fe_error_reading_stdin);
558 return false;
559 }
Dan Gohman90d90812010-10-26 23:21:25 +0000560 const FileEntry *File = FileMgr.getVirtualFile(SB->getBufferIdentifier(),
Chris Lattner39b49bc2010-11-23 08:35:12 +0000561 SB->getBufferSize(), 0);
Dan Gohman90d90812010-10-26 23:21:25 +0000562 SourceMgr.createMainFileID(File);
Michael J. Spencer4eeebc42010-12-16 03:28:14 +0000563 SourceMgr.overrideFileContents(File, SB.take());
Daniel Dunbarccb6cb62009-11-14 07:53:04 +0000564 }
565
Dan Gohman694137c2010-10-26 21:13:51 +0000566 assert(!SourceMgr.getMainFileID().isInvalid() &&
567 "Couldn't establish MainFileID!");
Daniel Dunbarccb6cb62009-11-14 07:53:04 +0000568 return true;
569}
Daniel Dunbar0397af22010-01-13 00:48:06 +0000570
571// High-Level Operations
572
573bool CompilerInstance::ExecuteAction(FrontendAction &Act) {
574 assert(hasDiagnostics() && "Diagnostics engine is not initialized!");
575 assert(!getFrontendOpts().ShowHelp && "Client must handle '-help'!");
576 assert(!getFrontendOpts().ShowVersion && "Client must handle '-version'!");
577
578 // FIXME: Take this as an argument, once all the APIs we used have moved to
579 // taking it as an input instead of hard-coding llvm::errs.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000580 raw_ostream &OS = llvm::errs();
Daniel Dunbar0397af22010-01-13 00:48:06 +0000581
582 // Create the target instance.
583 setTarget(TargetInfo::CreateTargetInfo(getDiagnostics(), getTargetOpts()));
584 if (!hasTarget())
585 return false;
586
587 // Inform the target of the language options.
588 //
589 // FIXME: We shouldn't need to do this, the target should be immutable once
590 // created. This complexity should be lifted elsewhere.
591 getTarget().setForcedLangOptions(getLangOpts());
592
593 // Validate/process some options.
594 if (getHeaderSearchOpts().Verbose)
595 OS << "clang -cc1 version " CLANG_VERSION_STRING
596 << " based upon " << PACKAGE_STRING
597 << " hosted on " << llvm::sys::getHostTriple() << "\n";
598
599 if (getFrontendOpts().ShowTimers)
600 createFrontendTimer();
601
Douglas Gregor95dd5582010-03-30 17:33:59 +0000602 if (getFrontendOpts().ShowStats)
603 llvm::EnableStatistics();
604
Daniel Dunbar0397af22010-01-13 00:48:06 +0000605 for (unsigned i = 0, e = getFrontendOpts().Inputs.size(); i != e; ++i) {
606 const std::string &InFile = getFrontendOpts().Inputs[i].second;
607
Daniel Dunbar20560482010-06-07 23:23:50 +0000608 // Reset the ID tables if we are reusing the SourceManager.
609 if (hasSourceManager())
610 getSourceManager().clearIDTables();
Daniel Dunbar0397af22010-01-13 00:48:06 +0000611
Daniel Dunbard3598a62010-06-07 23:23:06 +0000612 if (Act.BeginSourceFile(*this, InFile, getFrontendOpts().Inputs[i].first)) {
Daniel Dunbar0397af22010-01-13 00:48:06 +0000613 Act.Execute();
614 Act.EndSourceFile();
615 }
616 }
617
Chris Lattner53eee7b2010-04-07 18:47:42 +0000618 if (getDiagnosticOpts().ShowCarets) {
Argyrios Kyrtzidisf2224d82010-11-18 20:06:46 +0000619 // We can have multiple diagnostics sharing one diagnostic client.
620 // Get the total number of warnings/errors from the client.
621 unsigned NumWarnings = getDiagnostics().getClient()->getNumWarnings();
622 unsigned NumErrors = getDiagnostics().getClient()->getNumErrors();
Chris Lattner53eee7b2010-04-07 18:47:42 +0000623
624 if (NumWarnings)
625 OS << NumWarnings << " warning" << (NumWarnings == 1 ? "" : "s");
626 if (NumWarnings && NumErrors)
627 OS << " and ";
628 if (NumErrors)
629 OS << NumErrors << " error" << (NumErrors == 1 ? "" : "s");
630 if (NumWarnings || NumErrors)
631 OS << " generated.\n";
632 }
Daniel Dunbar0397af22010-01-13 00:48:06 +0000633
Daniel Dunbar20560482010-06-07 23:23:50 +0000634 if (getFrontendOpts().ShowStats && hasFileManager()) {
Daniel Dunbar0397af22010-01-13 00:48:06 +0000635 getFileManager().PrintStats();
636 OS << "\n";
637 }
638
Argyrios Kyrtzidisab41b972010-11-18 21:13:57 +0000639 return !getDiagnostics().getClient()->getNumErrors();
Daniel Dunbar0397af22010-01-13 00:48:06 +0000640}
641
Douglas Gregor21cae202011-09-12 23:31:24 +0000642/// \brief Determine the appropriate source input kind based on language
643/// options.
644static InputKind getSourceInputKindFromOptions(const LangOptions &LangOpts) {
645 if (LangOpts.OpenCL)
646 return IK_OpenCL;
647 if (LangOpts.CUDA)
648 return IK_CUDA;
649 if (LangOpts.ObjC1)
650 return LangOpts.CPlusPlus? IK_ObjCXX : IK_ObjC;
651 return LangOpts.CPlusPlus? IK_CXX : IK_C;
652}
653
654/// \brief Compile a module file for the given module name with the given
655/// umbrella header, using the options provided by the importing compiler
656/// instance.
657static void compileModule(CompilerInstance &ImportingInstance,
658 StringRef ModuleName,
Douglas Gregor6e975c42011-09-13 23:15:45 +0000659 StringRef ModuleFileName,
Douglas Gregor21cae202011-09-12 23:31:24 +0000660 StringRef UmbrellaHeader) {
Douglas Gregor21cae202011-09-12 23:31:24 +0000661 // Construct a compiler invocation for creating this module.
662 llvm::IntrusiveRefCntPtr<CompilerInvocation> Invocation
663 (new CompilerInvocation(ImportingInstance.getInvocation()));
Douglas Gregorb2d39c22011-09-15 20:53:28 +0000664
665 // For any options that aren't intended to affect how a module is built,
666 // reset them to their default values.
Douglas Gregor1c7e0472011-09-13 20:44:41 +0000667 Invocation->getLangOpts().resetNonModularOptions();
668 Invocation->getPreprocessorOpts().resetNonModularOptions();
Douglas Gregorb2d39c22011-09-15 20:53:28 +0000669
670 // Note that this module is part of the module build path, so that we
671 // can detect cycles in the module graph.
Douglas Gregor4ebd45f2011-09-15 20:40:10 +0000672 Invocation->getPreprocessorOpts().ModuleBuildPath.push_back(ModuleName);
Douglas Gregor1c7e0472011-09-13 20:44:41 +0000673
Douglas Gregorb2d39c22011-09-15 20:53:28 +0000674 // Set up the inputs/outputs so that we build the module from its umbrella
675 // header.
Douglas Gregor21cae202011-09-12 23:31:24 +0000676 FrontendOptions &FrontendOpts = Invocation->getFrontendOpts();
Douglas Gregor6e975c42011-09-13 23:15:45 +0000677 FrontendOpts.OutputFile = ModuleFileName.str();
Douglas Gregor21cae202011-09-12 23:31:24 +0000678 FrontendOpts.DisableFree = false;
679 FrontendOpts.Inputs.clear();
680 FrontendOpts.Inputs.push_back(
681 std::make_pair(getSourceInputKindFromOptions(Invocation->getLangOpts()),
682 UmbrellaHeader));
Douglas Gregor78243652011-09-13 01:26:44 +0000683
684 Invocation->getDiagnosticOpts().VerifyDiagnostics = 0;
685
Douglas Gregor4ebd45f2011-09-15 20:40:10 +0000686
Douglas Gregor76d991e2011-09-13 23:20:27 +0000687 assert(ImportingInstance.getInvocation().getModuleHash() ==
688 Invocation->getModuleHash() && "Module hash mismatch!");
Douglas Gregor21cae202011-09-12 23:31:24 +0000689
690 // Construct a compiler instance that will be used to actually create the
691 // module.
692 CompilerInstance Instance;
693 Instance.setInvocation(&*Invocation);
Douglas Gregor78243652011-09-13 01:26:44 +0000694 Instance.createDiagnostics(/*argc=*/0, /*argv=*/0,
695 &ImportingInstance.getDiagnosticClient(),
696 /*ShouldOwnClient=*/false);
Douglas Gregor21cae202011-09-12 23:31:24 +0000697
698 // Construct a module-generating action.
699 GeneratePCHAction CreateModuleAction(true);
700
701 // Execute the action to actually build the module in-place.
702 // FIXME: Need to synchronize when multiple processes do this.
703 Instance.ExecuteAction(CreateModuleAction);
704
Douglas Gregor78243652011-09-13 01:26:44 +0000705 // Tell the diagnostic client that it's (re-)starting to process a source
706 // file.
Douglas Gregor4ebd45f2011-09-15 20:40:10 +0000707 // FIXME: This is a hack. We probably want to clone the diagnostic client.
Douglas Gregor78243652011-09-13 01:26:44 +0000708 ImportingInstance.getDiagnosticClient()
709 .BeginSourceFile(ImportingInstance.getLangOpts(),
710 &ImportingInstance.getPreprocessor());
711}
Douglas Gregor21cae202011-09-12 23:31:24 +0000712
Douglas Gregor6aa52ec2011-08-26 23:56:07 +0000713ModuleKey CompilerInstance::loadModule(SourceLocation ImportLoc,
714 IdentifierInfo &ModuleName,
715 SourceLocation ModuleNameLoc) {
716 // Determine what file we're searching from.
717 SourceManager &SourceMgr = getSourceManager();
718 SourceLocation ExpandedImportLoc = SourceMgr.getExpansionLoc(ImportLoc);
719 const FileEntry *CurFile
720 = SourceMgr.getFileEntryForID(SourceMgr.getFileID(ExpandedImportLoc));
721 if (!CurFile)
722 CurFile = SourceMgr.getFileEntryForID(SourceMgr.getMainFileID());
723
724 // Search for a module with the given name.
Douglas Gregor21cae202011-09-12 23:31:24 +0000725 std::string UmbrellaHeader;
Douglas Gregor6e975c42011-09-13 23:15:45 +0000726 std::string ModuleFileName;
Douglas Gregor6aa52ec2011-08-26 23:56:07 +0000727 const FileEntry *ModuleFile
Douglas Gregor21cae202011-09-12 23:31:24 +0000728 = PP->getHeaderSearchInfo().lookupModule(ModuleName.getName(),
Douglas Gregor6e975c42011-09-13 23:15:45 +0000729 &ModuleFileName,
Douglas Gregor21cae202011-09-12 23:31:24 +0000730 &UmbrellaHeader);
731
732 bool BuildingModule = false;
733 if (!ModuleFile && !UmbrellaHeader.empty()) {
734 // We didn't find the module, but there is an umbrella header that
735 // can be used to create the module file. Create a separate compilation
736 // module to do so.
Douglas Gregor4ebd45f2011-09-15 20:40:10 +0000737
738 // Check whether there is a cycle in the module graph.
739 SmallVectorImpl<std::string> &ModuleBuildPath
740 = getPreprocessorOpts().ModuleBuildPath;
741 SmallVectorImpl<std::string>::iterator Pos
742 = std::find(ModuleBuildPath.begin(), ModuleBuildPath.end(),
743 ModuleName.getName());
744 if (Pos != ModuleBuildPath.end()) {
745 llvm::SmallString<256> CyclePath;
746 for (; Pos != ModuleBuildPath.end(); ++Pos) {
747 CyclePath += *Pos;
748 CyclePath += " -> ";
749 }
750 CyclePath += ModuleName.getName();
751
752 getDiagnostics().Report(ModuleNameLoc, diag::err_module_cycle)
753 << ModuleName.getName() << CyclePath;
754 return 0;
755 }
756
Douglas Gregor21cae202011-09-12 23:31:24 +0000757 BuildingModule = true;
Douglas Gregor6e975c42011-09-13 23:15:45 +0000758 compileModule(*this, ModuleName.getName(), ModuleFileName, UmbrellaHeader);
Douglas Gregor21cae202011-09-12 23:31:24 +0000759 ModuleFile = PP->getHeaderSearchInfo().lookupModule(ModuleName.getName());
760 }
761
Douglas Gregor6aa52ec2011-08-26 23:56:07 +0000762 if (!ModuleFile) {
Douglas Gregor21cae202011-09-12 23:31:24 +0000763 getDiagnostics().Report(ModuleNameLoc,
764 BuildingModule? diag::err_module_not_built
765 : diag::err_module_not_found)
Douglas Gregor6aa52ec2011-08-26 23:56:07 +0000766 << ModuleName.getName()
767 << SourceRange(ImportLoc, ModuleNameLoc);
768 return 0;
769 }
770
771 // If we don't already have an ASTReader, create one now.
772 if (!ModuleManager) {
Douglas Gregorde8a9052011-09-14 23:13:09 +0000773 if (!hasASTContext())
774 createASTContext();
775
Douglas Gregor6aa52ec2011-08-26 23:56:07 +0000776 std::string Sysroot = getHeaderSearchOpts().Sysroot;
777 const PreprocessorOptions &PPOpts = getPreprocessorOpts();
Douglas Gregorf8a1e512011-09-02 00:26:20 +0000778 ModuleManager = new ASTReader(getPreprocessor(), *Context,
Douglas Gregor6aa52ec2011-08-26 23:56:07 +0000779 Sysroot.empty() ? "" : Sysroot.c_str(),
780 PPOpts.DisablePCHValidation,
781 PPOpts.DisableStatCache);
Douglas Gregorde8a9052011-09-14 23:13:09 +0000782 if (hasASTConsumer()) {
783 ModuleManager->setDeserializationListener(
784 getASTConsumer().GetASTDeserializationListener());
785 getASTContext().setASTMutationListener(
786 getASTConsumer().GetASTMutationListener());
787 }
Douglas Gregor6aa52ec2011-08-26 23:56:07 +0000788 llvm::OwningPtr<ExternalASTSource> Source;
789 Source.reset(ModuleManager);
790 getASTContext().setExternalSource(Source);
Douglas Gregorde8a9052011-09-14 23:13:09 +0000791 if (hasSema())
792 ModuleManager->InitializeSema(getSema());
Douglas Gregor1a995dd2011-09-15 18:47:32 +0000793 if (hasASTConsumer())
794 ModuleManager->StartTranslationUnit(&getASTConsumer());
Douglas Gregor6aa52ec2011-08-26 23:56:07 +0000795 }
796
797 // Try to load the module we found.
798 switch (ModuleManager->ReadAST(ModuleFile->getName(),
799 serialization::MK_Module)) {
800 case ASTReader::Success:
801 break;
802
803 case ASTReader::IgnorePCH:
804 // FIXME: The ASTReader will already have complained, but can we showhorn
805 // that diagnostic information into a more useful form?
806 return 0;
807
808 case ASTReader::Failure:
809 // Already complained.
810 return 0;
811 }
812
813 // FIXME: The module file's FileEntry makes a poor key indeed!
814 return (ModuleKey)ModuleFile;
815}
Daniel Dunbar0397af22010-01-13 00:48:06 +0000816