blob: a97a32ba0676d70d1de3a1efa2efbd88cc390a10 [file] [log] [blame]
Daniel Dunbar8305d012009-11-14 10:42:46 +00001//===--- FrontendActions.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/FrontendActions.h"
11#include "clang/AST/ASTConsumer.h"
Douglas Gregordb1cde72011-11-16 00:09:06 +000012#include "clang/Lex/HeaderSearch.h"
Daniel Dunbarc72cc502010-06-11 20:10:12 +000013#include "clang/Lex/Pragma.h"
Daniel Dunbar5f3b9972009-11-14 10:42:57 +000014#include "clang/Lex/Preprocessor.h"
15#include "clang/Parse/Parser.h"
Daniel Dunbar8305d012009-11-14 10:42:46 +000016#include "clang/Basic/FileManager.h"
Daniel Dunbar8305d012009-11-14 10:42:46 +000017#include "clang/Frontend/ASTConsumers.h"
18#include "clang/Frontend/ASTUnit.h"
19#include "clang/Frontend/CompilerInstance.h"
Daniel Dunbar8305d012009-11-14 10:42:46 +000020#include "clang/Frontend/FrontendDiagnostic.h"
21#include "clang/Frontend/Utils.h"
Sebastian Redl7faa2ec2010-08-18 23:56:37 +000022#include "clang/Serialization/ASTWriter.h"
Nick Lewyckyba5f6ec2010-04-24 01:30:46 +000023#include "llvm/ADT/OwningPtr.h"
Douglas Gregor77d029f2011-12-08 19:11:24 +000024#include "llvm/Support/FileSystem.h"
Douglas Gregorf033f1d2010-07-20 20:18:03 +000025#include "llvm/Support/MemoryBuffer.h"
Daniel Dunbar8305d012009-11-14 10:42:46 +000026#include "llvm/Support/raw_ostream.h"
Douglas Gregor10efbaf2011-09-23 23:43:36 +000027#include "llvm/Support/system_error.h"
28
Daniel Dunbar8305d012009-11-14 10:42:46 +000029using namespace clang;
30
Daniel Dunbar5f3b9972009-11-14 10:42:57 +000031//===----------------------------------------------------------------------===//
Daniel Dunbar27585952010-03-19 19:44:04 +000032// Custom Actions
33//===----------------------------------------------------------------------===//
34
35ASTConsumer *InitOnlyAction::CreateASTConsumer(CompilerInstance &CI,
Chris Lattner5f9e2722011-07-23 10:55:15 +000036 StringRef InFile) {
Daniel Dunbar27585952010-03-19 19:44:04 +000037 return new ASTConsumer();
38}
39
40void InitOnlyAction::ExecuteAction() {
41}
42
43//===----------------------------------------------------------------------===//
Daniel Dunbar5f3b9972009-11-14 10:42:57 +000044// AST Consumer Actions
45//===----------------------------------------------------------------------===//
46
Daniel Dunbar8305d012009-11-14 10:42:46 +000047ASTConsumer *ASTPrintAction::CreateASTConsumer(CompilerInstance &CI,
Chris Lattner5f9e2722011-07-23 10:55:15 +000048 StringRef InFile) {
49 if (raw_ostream *OS = CI.createDefaultOutputFile(false, InFile))
Daniel Dunbar36043592009-12-03 09:13:30 +000050 return CreateASTPrinter(OS);
51 return 0;
Daniel Dunbar8305d012009-11-14 10:42:46 +000052}
53
Daniel Dunbar8305d012009-11-14 10:42:46 +000054ASTConsumer *ASTDumpAction::CreateASTConsumer(CompilerInstance &CI,
Chris Lattner5f9e2722011-07-23 10:55:15 +000055 StringRef InFile) {
Daniel Dunbar8305d012009-11-14 10:42:46 +000056 return CreateASTDumper();
57}
58
John McCallf3514242010-11-24 11:21:45 +000059ASTConsumer *ASTDumpXMLAction::CreateASTConsumer(CompilerInstance &CI,
Chris Lattner5f9e2722011-07-23 10:55:15 +000060 StringRef InFile) {
61 raw_ostream *OS;
John McCallf3514242010-11-24 11:21:45 +000062 if (CI.getFrontendOpts().OutputFile.empty())
63 OS = &llvm::outs();
64 else
65 OS = CI.createDefaultOutputFile(false, InFile);
66 if (!OS) return 0;
67 return CreateASTDumperXML(*OS);
68}
69
Daniel Dunbar8305d012009-11-14 10:42:46 +000070ASTConsumer *ASTViewAction::CreateASTConsumer(CompilerInstance &CI,
Chris Lattner5f9e2722011-07-23 10:55:15 +000071 StringRef InFile) {
Daniel Dunbar8305d012009-11-14 10:42:46 +000072 return CreateASTViewer();
73}
74
75ASTConsumer *DeclContextPrintAction::CreateASTConsumer(CompilerInstance &CI,
Chris Lattner5f9e2722011-07-23 10:55:15 +000076 StringRef InFile) {
Daniel Dunbar8305d012009-11-14 10:42:46 +000077 return CreateDeclContextPrinter();
78}
79
Daniel Dunbar8305d012009-11-14 10:42:46 +000080ASTConsumer *GeneratePCHAction::CreateASTConsumer(CompilerInstance &CI,
Chris Lattner5f9e2722011-07-23 10:55:15 +000081 StringRef InFile) {
Douglas Gregor1d715ac2010-08-03 08:14:03 +000082 std::string Sysroot;
Argyrios Kyrtzidis8e3df4d2011-02-15 17:54:22 +000083 std::string OutputFile;
Chris Lattner5f9e2722011-07-23 10:55:15 +000084 raw_ostream *OS = 0;
Douglas Gregor9293ba82011-08-25 22:35:51 +000085 if (ComputeASTConsumerArguments(CI, InFile, Sysroot, OutputFile, OS))
Daniel Dunbar8305d012009-11-14 10:42:46 +000086 return 0;
Douglas Gregor1d715ac2010-08-03 08:14:03 +000087
Douglas Gregor832d6202011-07-22 16:35:34 +000088 if (!CI.getFrontendOpts().RelocatablePCH)
89 Sysroot.clear();
Douglas Gregora8cc6ce2011-11-30 04:39:39 +000090 return new PCHGenerator(CI.getPreprocessor(), OutputFile, 0, Sysroot, OS);
Douglas Gregor1d715ac2010-08-03 08:14:03 +000091}
92
93bool GeneratePCHAction::ComputeASTConsumerArguments(CompilerInstance &CI,
Chris Lattner5f9e2722011-07-23 10:55:15 +000094 StringRef InFile,
Douglas Gregor1d715ac2010-08-03 08:14:03 +000095 std::string &Sysroot,
Argyrios Kyrtzidis8e3df4d2011-02-15 17:54:22 +000096 std::string &OutputFile,
Douglas Gregor9293ba82011-08-25 22:35:51 +000097 raw_ostream *&OS) {
Douglas Gregor1d715ac2010-08-03 08:14:03 +000098 Sysroot = CI.getHeaderSearchOpts().Sysroot;
99 if (CI.getFrontendOpts().RelocatablePCH && Sysroot.empty()) {
Sebastian Redl11c3dc42010-08-17 17:55:38 +0000100 CI.getDiagnostics().Report(diag::err_relocatable_without_isysroot);
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000101 return true;
Daniel Dunbar8305d012009-11-14 10:42:46 +0000102 }
103
Daniel Dunbarc7a9cda2011-01-31 22:00:44 +0000104 // We use createOutputFile here because this is exposed via libclang, and we
105 // must disable the RemoveFileOnSignal behavior.
Argyrios Kyrtzidis7e909852011-07-28 00:45:10 +0000106 // We use a temporary to avoid race conditions.
Daniel Dunbarc7a9cda2011-01-31 22:00:44 +0000107 OS = CI.createOutputFile(CI.getFrontendOpts().OutputFile, /*Binary=*/true,
Argyrios Kyrtzidis7e909852011-07-28 00:45:10 +0000108 /*RemoveFileOnSignal=*/false, InFile,
109 /*Extension=*/"", /*useTemporary=*/true);
Daniel Dunbar36043592009-12-03 09:13:30 +0000110 if (!OS)
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000111 return true;
Daniel Dunbar36043592009-12-03 09:13:30 +0000112
Argyrios Kyrtzidis8e3df4d2011-02-15 17:54:22 +0000113 OutputFile = CI.getFrontendOpts().OutputFile;
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000114 return false;
Daniel Dunbar8305d012009-11-14 10:42:46 +0000115}
116
Douglas Gregordb1cde72011-11-16 00:09:06 +0000117ASTConsumer *GenerateModuleAction::CreateASTConsumer(CompilerInstance &CI,
118 StringRef InFile) {
119 std::string Sysroot;
120 std::string OutputFile;
121 raw_ostream *OS = 0;
122 if (ComputeASTConsumerArguments(CI, InFile, Sysroot, OutputFile, OS))
123 return 0;
124
Douglas Gregora8cc6ce2011-11-30 04:39:39 +0000125 return new PCHGenerator(CI.getPreprocessor(), OutputFile, Module,
Douglas Gregordb1cde72011-11-16 00:09:06 +0000126 Sysroot, OS);
127}
128
Douglas Gregor261e75b2011-11-16 17:04:00 +0000129/// \brief Collect the set of header includes needed to construct the given
130/// module.
131///
132/// \param Module The module we're collecting includes from.
Douglas Gregor8075ce62011-12-06 17:15:11 +0000133///
134/// \param Includes Will be augmented with the set of #includes or #imports
135/// needed to load all of the named headers.
Douglas Gregor261e75b2011-11-16 17:04:00 +0000136static void collectModuleHeaderIncludes(const LangOptions &LangOpts,
Douglas Gregor1a4761e2011-11-30 23:21:26 +0000137 clang::Module *Module,
Douglas Gregor261e75b2011-11-16 17:04:00 +0000138 llvm::SmallString<256> &Includes) {
Douglas Gregor8075ce62011-12-06 17:15:11 +0000139 // Add includes for each of these headers.
140 for (unsigned I = 0, N = Module->Headers.size(); I != N; ++I) {
141 if (LangOpts.ObjC1)
142 Includes += "#import \"";
143 else
144 Includes += "#include \"";
145 Includes += Module->Headers[I]->getName();
146 Includes += "\"\n";
147 }
148
Douglas Gregor10694ce2011-12-08 17:39:04 +0000149 if (const FileEntry *UmbrellaHeader = Module->getUmbrellaHeader()) {
150 if (Module->Parent) {
151 // Include the umbrella header for submodules.
152 if (LangOpts.ObjC1)
153 Includes += "#import \"";
154 else
155 Includes += "#include \"";
156 Includes += UmbrellaHeader->getName();
157 Includes += "\"\n";
158 }
Douglas Gregor77d029f2011-12-08 19:11:24 +0000159 } else if (const DirectoryEntry *UmbrellaDir = Module->getUmbrellaDir()) {
160 // Add all of the headers we find in this subdirectory (FIXME: recursively!).
161 llvm::error_code EC;
162 llvm::SmallString<128> DirNative;
163 llvm::sys::path::native(UmbrellaDir->getName(), DirNative);
Douglas Gregor3b29bb92011-12-12 19:13:53 +0000164 for (llvm::sys::fs::recursive_directory_iterator Dir(DirNative.str(), EC),
165 DirEnd;
Douglas Gregor77d029f2011-12-08 19:11:24 +0000166 Dir != DirEnd && !EC; Dir.increment(EC)) {
167 // Check whether this entry has an extension typically associated with
168 // headers.
169 if (!llvm::StringSwitch<bool>(llvm::sys::path::extension(Dir->path()))
170 .Cases(".h", ".H", ".hh", ".hpp", true)
171 .Default(false))
172 continue;
173
174 // Include this header umbrella header for submodules.
175 if (LangOpts.ObjC1)
176 Includes += "#import \"";
177 else
178 Includes += "#include \"";
179 Includes += Dir->path();
180 Includes += "\"\n";
181 }
Douglas Gregor261e75b2011-11-16 17:04:00 +0000182 }
183
184 // Recurse into submodules.
Douglas Gregor1a4761e2011-11-30 23:21:26 +0000185 for (llvm::StringMap<clang::Module *>::iterator
Douglas Gregor261e75b2011-11-16 17:04:00 +0000186 Sub = Module->SubModules.begin(),
187 SubEnd = Module->SubModules.end();
Douglas Gregor8075ce62011-12-06 17:15:11 +0000188 Sub != SubEnd; ++Sub)
189 collectModuleHeaderIncludes(LangOpts, Sub->getValue(), Includes);
Douglas Gregor261e75b2011-11-16 17:04:00 +0000190}
191
Douglas Gregordb1cde72011-11-16 00:09:06 +0000192bool GenerateModuleAction::BeginSourceFileAction(CompilerInstance &CI,
193 StringRef Filename) {
194 // Find the module map file.
195 const FileEntry *ModuleMap = CI.getFileManager().getFile(Filename);
196 if (!ModuleMap) {
197 CI.getDiagnostics().Report(diag::err_module_map_not_found)
198 << Filename;
199 return false;
200 }
201
202 // Parse the module map file.
203 HeaderSearch &HS = CI.getPreprocessor().getHeaderSearchInfo();
204 if (HS.loadModuleMapFile(ModuleMap))
205 return false;
206
207 if (CI.getLangOpts().CurrentModule.empty()) {
208 CI.getDiagnostics().Report(diag::err_missing_module_name);
209
210 // FIXME: Eventually, we could consider asking whether there was just
211 // a single module described in the module map, and use that as a
212 // default. Then it would be fairly trivial to just "compile" a module
213 // map with a single module (the common case).
214 return false;
215 }
216
217 // Dig out the module definition.
Douglas Gregora8cc6ce2011-11-30 04:39:39 +0000218 Module = HS.getModule(CI.getLangOpts().CurrentModule, /*AllowSearch=*/false);
Douglas Gregordb1cde72011-11-16 00:09:06 +0000219 if (!Module) {
220 CI.getDiagnostics().Report(diag::err_missing_module)
221 << CI.getLangOpts().CurrentModule << Filename;
222
223 return false;
224 }
225
Douglas Gregor10694ce2011-12-08 17:39:04 +0000226 // Do we have an umbrella header for this module?
227 const FileEntry *UmbrellaHeader = Module->getUmbrellaHeader();
228
Douglas Gregor261e75b2011-11-16 17:04:00 +0000229 // Collect the set of #includes we need to build the module.
230 llvm::SmallString<256> HeaderContents;
Douglas Gregor8075ce62011-12-06 17:15:11 +0000231 collectModuleHeaderIncludes(CI.getLangOpts(), Module, HeaderContents);
Douglas Gregor10694ce2011-12-08 17:39:04 +0000232 if (UmbrellaHeader && HeaderContents.empty()) {
Douglas Gregor261e75b2011-11-16 17:04:00 +0000233 // Simple case: we have an umbrella header and there are no additional
234 // includes, we can just parse the umbrella header directly.
Douglas Gregor10694ce2011-12-08 17:39:04 +0000235 setCurrentFile(UmbrellaHeader->getName(), getCurrentFileKind());
Douglas Gregor261e75b2011-11-16 17:04:00 +0000236 return true;
Douglas Gregordb1cde72011-11-16 00:09:06 +0000237 }
238
Douglas Gregor261e75b2011-11-16 17:04:00 +0000239 FileManager &FileMgr = CI.getFileManager();
240 llvm::SmallString<128> HeaderName;
241 time_t ModTime;
Douglas Gregor10694ce2011-12-08 17:39:04 +0000242 if (UmbrellaHeader) {
Douglas Gregor261e75b2011-11-16 17:04:00 +0000243 // Read in the umbrella header.
244 // FIXME: Go through the source manager; the umbrella header may have
245 // been overridden.
246 std::string ErrorStr;
247 llvm::MemoryBuffer *UmbrellaContents
Douglas Gregor10694ce2011-12-08 17:39:04 +0000248 = FileMgr.getBufferForFile(UmbrellaHeader, &ErrorStr);
Douglas Gregor261e75b2011-11-16 17:04:00 +0000249 if (!UmbrellaContents) {
250 CI.getDiagnostics().Report(diag::err_missing_umbrella_header)
Douglas Gregor10694ce2011-12-08 17:39:04 +0000251 << UmbrellaHeader->getName() << ErrorStr;
Douglas Gregor261e75b2011-11-16 17:04:00 +0000252 return false;
253 }
254
255 // Combine the contents of the umbrella header with the automatically-
256 // generated includes.
257 llvm::SmallString<256> OldContents = HeaderContents;
258 HeaderContents = UmbrellaContents->getBuffer();
259 HeaderContents += "\n\n";
260 HeaderContents += "/* Module includes */\n";
261 HeaderContents += OldContents;
262
263 // Pretend that we're parsing the umbrella header.
Douglas Gregor10694ce2011-12-08 17:39:04 +0000264 HeaderName = UmbrellaHeader->getName();
265 ModTime = UmbrellaHeader->getModificationTime();
Douglas Gregor261e75b2011-11-16 17:04:00 +0000266
267 delete UmbrellaContents;
268 } else {
269 // Pick an innocuous-sounding name for the umbrella header.
270 HeaderName = Module->Name + ".h";
271 if (FileMgr.getFile(HeaderName, /*OpenFile=*/false,
272 /*CacheFailure=*/false)) {
273 // Try again!
274 HeaderName = Module->Name + "-module.h";
275 if (FileMgr.getFile(HeaderName, /*OpenFile=*/false,
276 /*CacheFailure=*/false)) {
277 // Pick something ridiculous and go with it.
278 HeaderName = Module->Name + "-module.hmod";
279 }
280 }
281 ModTime = time(0);
282 }
283
284 // Remap the contents of the header name we're using to our synthesized
285 // buffer.
286 const FileEntry *HeaderFile = FileMgr.getVirtualFile(HeaderName,
287 HeaderContents.size(),
288 ModTime);
289 llvm::MemoryBuffer *HeaderContentsBuf
290 = llvm::MemoryBuffer::getMemBufferCopy(HeaderContents);
291 CI.getSourceManager().overrideFileContents(HeaderFile, HeaderContentsBuf);
292
293 setCurrentFile(HeaderName, getCurrentFileKind());
Douglas Gregordb1cde72011-11-16 00:09:06 +0000294 return true;
295}
296
297bool GenerateModuleAction::ComputeASTConsumerArguments(CompilerInstance &CI,
298 StringRef InFile,
299 std::string &Sysroot,
300 std::string &OutputFile,
301 raw_ostream *&OS) {
302 // If no output file was provided, figure out where this module would go
303 // in the module cache.
304 if (CI.getFrontendOpts().OutputFile.empty()) {
305 HeaderSearch &HS = CI.getPreprocessor().getHeaderSearchInfo();
306 llvm::SmallString<256> ModuleFileName(HS.getModuleCachePath());
307 llvm::sys::path::append(ModuleFileName,
308 CI.getLangOpts().CurrentModule + ".pcm");
309 CI.getFrontendOpts().OutputFile = ModuleFileName.str();
310 }
311
312 // We use createOutputFile here because this is exposed via libclang, and we
313 // must disable the RemoveFileOnSignal behavior.
314 // We use a temporary to avoid race conditions.
315 OS = CI.createOutputFile(CI.getFrontendOpts().OutputFile, /*Binary=*/true,
316 /*RemoveFileOnSignal=*/false, InFile,
317 /*Extension=*/"", /*useTemporary=*/true);
318 if (!OS)
319 return true;
320
321 OutputFile = CI.getFrontendOpts().OutputFile;
322 return false;
323}
324
Daniel Dunbar8305d012009-11-14 10:42:46 +0000325ASTConsumer *SyntaxOnlyAction::CreateASTConsumer(CompilerInstance &CI,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000326 StringRef InFile) {
Daniel Dunbar8305d012009-11-14 10:42:46 +0000327 return new ASTConsumer();
328}
329
Daniel Dunbar5f3b9972009-11-14 10:42:57 +0000330//===----------------------------------------------------------------------===//
331// Preprocessor Actions
332//===----------------------------------------------------------------------===//
333
334void DumpRawTokensAction::ExecuteAction() {
335 Preprocessor &PP = getCompilerInstance().getPreprocessor();
336 SourceManager &SM = PP.getSourceManager();
337
338 // Start lexing the specified input file.
Chris Lattner6e290142009-11-30 04:18:44 +0000339 const llvm::MemoryBuffer *FromFile = SM.getBuffer(SM.getMainFileID());
340 Lexer RawLex(SM.getMainFileID(), FromFile, SM, PP.getLangOptions());
Daniel Dunbar5f3b9972009-11-14 10:42:57 +0000341 RawLex.SetKeepWhitespaceMode(true);
342
343 Token RawTok;
344 RawLex.LexFromRawLexer(RawTok);
345 while (RawTok.isNot(tok::eof)) {
346 PP.DumpToken(RawTok, true);
Daniel Dunbar33f57f82009-11-25 10:27:48 +0000347 llvm::errs() << "\n";
Daniel Dunbar5f3b9972009-11-14 10:42:57 +0000348 RawLex.LexFromRawLexer(RawTok);
349 }
350}
351
352void DumpTokensAction::ExecuteAction() {
353 Preprocessor &PP = getCompilerInstance().getPreprocessor();
354 // Start preprocessing the specified input file.
355 Token Tok;
Chris Lattnere127a0d2010-04-20 20:35:58 +0000356 PP.EnterMainSourceFile();
Daniel Dunbar5f3b9972009-11-14 10:42:57 +0000357 do {
358 PP.Lex(Tok);
359 PP.DumpToken(Tok, true);
Daniel Dunbar33f57f82009-11-25 10:27:48 +0000360 llvm::errs() << "\n";
Daniel Dunbar5f3b9972009-11-14 10:42:57 +0000361 } while (Tok.isNot(tok::eof));
362}
363
364void GeneratePTHAction::ExecuteAction() {
365 CompilerInstance &CI = getCompilerInstance();
366 if (CI.getFrontendOpts().OutputFile.empty() ||
367 CI.getFrontendOpts().OutputFile == "-") {
368 // FIXME: Don't fail this way.
369 // FIXME: Verify that we can actually seek in the given file.
Chris Lattner83e7a782010-04-07 22:58:06 +0000370 llvm::report_fatal_error("PTH requires a seekable file for output!");
Daniel Dunbar5f3b9972009-11-14 10:42:57 +0000371 }
372 llvm::raw_fd_ostream *OS =
373 CI.createDefaultOutputFile(true, getCurrentFile());
Daniel Dunbar36043592009-12-03 09:13:30 +0000374 if (!OS) return;
375
Daniel Dunbar5f3b9972009-11-14 10:42:57 +0000376 CacheTokens(CI.getPreprocessor(), OS);
377}
378
Daniel Dunbar5f3b9972009-11-14 10:42:57 +0000379void PreprocessOnlyAction::ExecuteAction() {
380 Preprocessor &PP = getCompilerInstance().getPreprocessor();
381
Daniel Dunbarc72cc502010-06-11 20:10:12 +0000382 // Ignore unknown pragmas.
Argyrios Kyrtzidis9b36c3f2010-07-13 09:07:17 +0000383 PP.AddPragmaHandler(new EmptyPragmaHandler());
Daniel Dunbarc72cc502010-06-11 20:10:12 +0000384
Daniel Dunbar5f3b9972009-11-14 10:42:57 +0000385 Token Tok;
386 // Start parsing the specified input file.
Chris Lattnere127a0d2010-04-20 20:35:58 +0000387 PP.EnterMainSourceFile();
Daniel Dunbar5f3b9972009-11-14 10:42:57 +0000388 do {
389 PP.Lex(Tok);
390 } while (Tok.isNot(tok::eof));
391}
392
Daniel Dunbar5f3b9972009-11-14 10:42:57 +0000393void PrintPreprocessedAction::ExecuteAction() {
394 CompilerInstance &CI = getCompilerInstance();
Douglas Gregor10efbaf2011-09-23 23:43:36 +0000395 // Output file may need to be set to 'Binary', to avoid converting Unix style
Steve Naroffd57d7c02010-01-05 17:33:23 +0000396 // line feeds (<LF>) to Microsoft style line feeds (<CR><LF>).
Douglas Gregor10efbaf2011-09-23 23:43:36 +0000397 //
398 // Look to see what type of line endings the file uses. If there's a
399 // CRLF, then we won't open the file up in binary mode. If there is
400 // just an LF or CR, then we will open the file up in binary mode.
401 // In this fashion, the output format should match the input format, unless
402 // the input format has inconsistent line endings.
403 //
404 // This should be a relatively fast operation since most files won't have
405 // all of their source code on a single line. However, that is still a
406 // concern, so if we scan for too long, we'll just assume the file should
407 // be opened in binary mode.
408 bool BinaryMode = true;
409 bool InvalidFile = false;
410 const SourceManager& SM = CI.getSourceManager();
411 const llvm::MemoryBuffer *Buffer = SM.getBuffer(SM.getMainFileID(),
412 &InvalidFile);
413 if (!InvalidFile) {
414 const char *cur = Buffer->getBufferStart();
415 const char *end = Buffer->getBufferEnd();
416 const char *next = (cur != end) ? cur + 1 : end;
417
418 // Limit ourselves to only scanning 256 characters into the source
419 // file. This is mostly a sanity check in case the file has no
420 // newlines whatsoever.
421 if (end - cur > 256) end = cur + 256;
422
423 while (next < end) {
424 if (*cur == 0x0D) { // CR
425 if (*next == 0x0A) // CRLF
426 BinaryMode = false;
427
428 break;
429 } else if (*cur == 0x0A) // LF
430 break;
431
432 ++cur, ++next;
433 }
434 }
435
436 raw_ostream *OS = CI.createDefaultOutputFile(BinaryMode, getCurrentFile());
Daniel Dunbar36043592009-12-03 09:13:30 +0000437 if (!OS) return;
438
Daniel Dunbar5f3b9972009-11-14 10:42:57 +0000439 DoPrintPreprocessedInput(CI.getPreprocessor(), OS,
440 CI.getPreprocessorOutputOpts());
441}
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000442
443void PrintPreambleAction::ExecuteAction() {
444 switch (getCurrentFileKind()) {
445 case IK_C:
446 case IK_CXX:
447 case IK_ObjC:
448 case IK_ObjCXX:
449 case IK_OpenCL:
Peter Collingbourne895fcca2010-12-01 03:15:20 +0000450 case IK_CUDA:
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000451 break;
452
453 case IK_None:
454 case IK_Asm:
455 case IK_PreprocessedC:
456 case IK_PreprocessedCXX:
457 case IK_PreprocessedObjC:
458 case IK_PreprocessedObjCXX:
459 case IK_AST:
460 case IK_LLVM_IR:
461 // We can't do anything with these.
462 return;
463 }
464
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +0000465 CompilerInstance &CI = getCompilerInstance();
466 llvm::MemoryBuffer *Buffer
Chris Lattner39b49bc2010-11-23 08:35:12 +0000467 = CI.getFileManager().getBufferForFile(getCurrentFile());
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000468 if (Buffer) {
Argyrios Kyrtzidis03c107a2011-08-25 20:39:19 +0000469 unsigned Preamble = Lexer::ComputePreamble(Buffer, CI.getLangOpts()).first;
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000470 llvm::outs().write(Buffer->getBufferStart(), Preamble);
471 delete Buffer;
472 }
473}