Coverage Report

Created: 2020-09-19 12:23

/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/lib/Lex/PPLexerChange.cpp
Line
Count
Source (jump to first uncovered line)
1
//===--- PPLexerChange.cpp - Handle changing lexers in the preprocessor ---===//
2
//
3
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4
// See https://llvm.org/LICENSE.txt for license information.
5
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6
//
7
//===----------------------------------------------------------------------===//
8
//
9
// This file implements pieces of the Preprocessor interface that manage the
10
// current lexer stack.
11
//
12
//===----------------------------------------------------------------------===//
13
14
#include "clang/Lex/Preprocessor.h"
15
#include "clang/Lex/PreprocessorOptions.h"
16
#include "clang/Basic/FileManager.h"
17
#include "clang/Basic/SourceManager.h"
18
#include "clang/Lex/HeaderSearch.h"
19
#include "clang/Lex/LexDiagnostic.h"
20
#include "clang/Lex/MacroInfo.h"
21
#include "llvm/ADT/StringSwitch.h"
22
#include "llvm/Support/FileSystem.h"
23
#include "llvm/Support/MemoryBuffer.h"
24
#include "llvm/Support/Path.h"
25
using namespace clang;
26
27
//===----------------------------------------------------------------------===//
28
// Miscellaneous Methods.
29
//===----------------------------------------------------------------------===//
30
31
/// isInPrimaryFile - Return true if we're in the top-level file, not in a
32
/// \#include.  This looks through macro expansions and active _Pragma lexers.
33
95.7k
bool Preprocessor::isInPrimaryFile() const {
34
95.7k
  if (IsFileLexer())
35
95.7k
    return IncludeMacroStack.empty();
36
1
37
  // If there are any stacked lexers, we're in a #include.
38
1
  assert(IsFileLexer(IncludeMacroStack[0]) &&
39
1
         "Top level include stack isn't our primary lexer?");
40
1
  return std::none_of(
41
1
      IncludeMacroStack.begin() + 1, IncludeMacroStack.end(),
42
0
      [&](const IncludeStackInfo &ISI) -> bool { return IsFileLexer(ISI); });
43
1
}
44
45
/// getCurrentLexer - Return the current file lexer being lexed from.  Note
46
/// that this ignores any potentially active macro expansions and _Pragma
47
/// expansions going on at the time.
48
2.38M
PreprocessorLexer *Preprocessor::getCurrentFileLexer() const {
49
2.38M
  if (IsFileLexer())
50
2.38M
    return CurPPLexer;
51
13
52
  // Look for a stacked lexer.
53
14
  
for (const IncludeStackInfo &ISI : llvm::reverse(IncludeMacroStack))13
{
54
14
    if (IsFileLexer(ISI))
55
13
      return ISI.ThePPLexer;
56
14
  }
57
0
  return nullptr;
58
13
}
59
60
61
//===----------------------------------------------------------------------===//
62
// Methods for Entering and Callbacks for leaving various contexts
63
//===----------------------------------------------------------------------===//
64
65
/// EnterSourceFile - Add a source file to the top of the include stack and
66
/// start lexing tokens from it instead of the current buffer.
67
bool Preprocessor::EnterSourceFile(FileID FID, const DirectoryLookup *CurDir,
68
1.07M
                                   SourceLocation Loc) {
69
1.07M
  assert(!CurTokenLexer && "Cannot #include a file inside a macro!");
70
1.07M
  ++NumEnteredSourceFiles;
71
1.07M
72
1.07M
  if (MaxIncludeStackDepth < IncludeMacroStack.size())
73
38.9k
    MaxIncludeStackDepth = IncludeMacroStack.size();
74
1.07M
75
  // Get the MemoryBuffer for this FID, if it fails, we fail.
76
1.07M
  bool Invalid = false;
77
1.07M
  const llvm::MemoryBuffer *InputFile =
78
1.07M
    getSourceManager().getBuffer(FID, Loc, &Invalid);
79
1.07M
  if (Invalid) {
80
2
    SourceLocation FileStart = SourceMgr.getLocForStartOfFile(FID);
81
2
    Diag(Loc, diag::err_pp_error_opening_file)
82
2
        << std::string(SourceMgr.getBufferName(FileStart)) << "";
83
2
    return true;
84
2
  }
85
1.07M
86
1.07M
  if (isCodeCompletionEnabled() &&
87
2.49k
      SourceMgr.getFileEntryForID(FID) == CodeCompletionFile) {
88
1.22k
    CodeCompletionFileLoc = SourceMgr.getLocForStartOfFile(FID);
89
1.22k
    CodeCompletionLoc =
90
1.22k
        CodeCompletionFileLoc.getLocWithOffset(CodeCompletionOffset);
91
1.22k
  }
92
1.07M
93
1.07M
  EnterSourceFileWithLexer(new Lexer(FID, InputFile, *this), CurDir);
94
1.07M
  return false;
95
1.07M
}
96
97
/// EnterSourceFileWithLexer - Add a source file to the top of the include stack
98
///  and start lexing tokens from it instead of the current buffer.
99
void Preprocessor::EnterSourceFileWithLexer(Lexer *TheLexer,
100
1.69M
                                            const DirectoryLookup *CurDir) {
101
1.69M
102
  // Add the current lexer to the include stack.
103
1.69M
  if (CurPPLexer || 
CurTokenLexer694k
)
104
1.61M
    PushIncludeMacroStack();
105
1.69M
106
1.69M
  CurLexer.reset(TheLexer);
107
1.69M
  CurPPLexer = TheLexer;
108
1.69M
  CurDirLookup = CurDir;
109
1.69M
  CurLexerSubmodule = nullptr;
110
1.69M
  if (CurLexerKind != CLK_LexAfterModuleImport)
111
1.69M
    CurLexerKind = CLK_Lexer;
112
1.69M
113
  // Notify the client, if desired, that we are in a new source file.
114
1.69M
  if (Callbacks && 
!CurLexer->Is_PragmaLexer1.69M
) {
115
1.07M
    SrcMgr::CharacteristicKind FileType =
116
1.07M
       SourceMgr.getFileCharacteristic(CurLexer->getFileLoc());
117
1.07M
118
1.07M
    Callbacks->FileChanged(CurLexer->getFileLoc(),
119
1.07M
                           PPCallbacks::EnterFile, FileType);
120
1.07M
  }
121
1.69M
}
122
123
/// EnterMacro - Add a Macro to the top of the include stack and start lexing
124
/// tokens from it instead of the current buffer.
125
void Preprocessor::EnterMacro(Token &Tok, SourceLocation ILEnd,
126
76.0M
                              MacroInfo *Macro, MacroArgs *Args) {
127
76.0M
  std::unique_ptr<TokenLexer> TokLexer;
128
76.0M
  if (NumCachedTokenLexers == 0) {
129
38.7k
    TokLexer = std::make_unique<TokenLexer>(Tok, ILEnd, Macro, Args, *this);
130
75.9M
  } else {
131
75.9M
    TokLexer = std::move(TokenLexerCache[--NumCachedTokenLexers]);
132
75.9M
    TokLexer->Init(Tok, ILEnd, Macro, Args);
133
75.9M
  }
134
76.0M
135
76.0M
  PushIncludeMacroStack();
136
76.0M
  CurDirLookup = nullptr;
137
76.0M
  CurTokenLexer = std::move(TokLexer);
138
76.0M
  if (CurLexerKind != CLK_LexAfterModuleImport)
139
76.0M
    CurLexerKind = CLK_TokenLexer;
140
76.0M
}
141
142
/// EnterTokenStream - Add a "macro" context to the top of the include stack,
143
/// which will cause the lexer to start returning the specified tokens.
144
///
145
/// If DisableMacroExpansion is true, tokens lexed from the token stream will
146
/// not be subject to further macro expansion.  Otherwise, these tokens will
147
/// be re-macro-expanded when/if expansion is enabled.
148
///
149
/// If OwnsTokens is false, this method assumes that the specified stream of
150
/// tokens has a permanent owner somewhere, so they do not need to be copied.
151
/// If it is true, it assumes the array of tokens is allocated with new[] and
152
/// must be freed.
153
///
154
void Preprocessor::EnterTokenStream(const Token *Toks, unsigned NumToks,
155
                                    bool DisableMacroExpansion, bool OwnsTokens,
156
8.11M
                                    bool IsReinject) {
157
8.11M
  if (CurLexerKind == CLK_CachingLexer) {
158
2.76k
    if (CachedLexPos < CachedTokens.size()) {
159
2.38k
      assert(IsReinject && "new tokens in the middle of cached stream");
160
      // We're entering tokens into the middle of our cached token stream. We
161
      // can't represent that, so just insert the tokens into the buffer.
162
2.38k
      CachedTokens.insert(CachedTokens.begin() + CachedLexPos,
163
2.38k
                          Toks, Toks + NumToks);
164
2.38k
      if (OwnsTokens)
165
0
        delete [] Toks;
166
2.38k
      return;
167
2.38k
    }
168
375
169
    // New tokens are at the end of the cached token sequnece; insert the
170
    // token stream underneath the caching lexer.
171
375
    ExitCachingLexMode();
172
375
    EnterTokenStream(Toks, NumToks, DisableMacroExpansion, OwnsTokens,
173
375
                     IsReinject);
174
375
    EnterCachingLexMode();
175
375
    return;
176
375
  }
177
8.11M
178
  // Create a macro expander to expand from the specified token stream.
179
8.11M
  std::unique_ptr<TokenLexer> TokLexer;
180
8.11M
  if (NumCachedTokenLexers == 0) {
181
311k
    TokLexer = std::make_unique<TokenLexer>(
182
311k
        Toks, NumToks, DisableMacroExpansion, OwnsTokens, IsReinject, *this);
183
7.80M
  } else {
184
7.80M
    TokLexer = std::move(TokenLexerCache[--NumCachedTokenLexers]);
185
7.80M
    TokLexer->Init(Toks, NumToks, DisableMacroExpansion, OwnsTokens,
186
7.80M
                   IsReinject);
187
7.80M
  }
188
8.11M
189
  // Save our current state.
190
8.11M
  PushIncludeMacroStack();
191
8.11M
  CurDirLookup = nullptr;
192
8.11M
  CurTokenLexer = std::move(TokLexer);
193
8.11M
  if (CurLexerKind != CLK_LexAfterModuleImport)
194
8.11M
    CurLexerKind = CLK_TokenLexer;
195
8.11M
}
196
197
/// Compute the relative path that names the given file relative to
198
/// the given directory.
199
static void computeRelativePath(FileManager &FM, const DirectoryEntry *Dir,
200
                                const FileEntry *File,
201
52
                                SmallString<128> &Result) {
202
52
  Result.clear();
203
52
204
52
  StringRef FilePath = File->getDir()->getName();
205
52
  StringRef Path = FilePath;
206
52
  while (!Path.empty()) {
207
52
    if (auto CurDir = FM.getDirectory(Path)) {
208
52
      if (*CurDir == Dir) {
209
52
        Result = FilePath.substr(Path.size());
210
52
        llvm::sys::path::append(Result,
211
52
                                llvm::sys::path::filename(File->getName()));
212
52
        return;
213
52
      }
214
0
    }
215
0
216
0
    Path = llvm::sys::path::parent_path(Path);
217
0
  }
218
52
219
0
  Result = File->getName();
220
0
}
221
222
80.5M
void Preprocessor::PropagateLineStartLeadingSpaceInfo(Token &Result) {
223
80.5M
  if (CurTokenLexer) {
224
53.0M
    CurTokenLexer->PropagateLineStartLeadingSpaceInfo(Result);
225
53.0M
    return;
226
53.0M
  }
227
27.4M
  if (CurLexer) {
228
27.4M
    CurLexer->PropagateLineStartLeadingSpaceInfo(Result);
229
27.4M
    return;
230
27.4M
  }
231
  // FIXME: Handle other kinds of lexers?  It generally shouldn't matter,
232
  // but it might if they're empty?
233
27.4M
}
234
235
/// Determine the location to use as the end of the buffer for a lexer.
236
///
237
/// If the file ends with a newline, form the EOF token on the newline itself,
238
/// rather than "on the line following it", which doesn't exist.  This makes
239
/// diagnostics relating to the end of file include the last file that the user
240
/// actually typed, which is goodness.
241
142k
const char *Preprocessor::getCurLexerEndPos() {
242
142k
  const char *EndPos = CurLexer->BufferEnd;
243
142k
  if (EndPos != CurLexer->BufferStart &&
244
139k
      (EndPos[-1] == '\n' || 
EndPos[-1] == '\r'23.9k
)) {
245
115k
    --EndPos;
246
115k
247
    // Handle \n\r and \r\n:
248
115k
    if (EndPos != CurLexer->BufferStart &&
249
115k
        (EndPos[-1] == '\n' || 
EndPos[-1] == '\r'104k
) &&
250
11.0k
        EndPos[-1] != EndPos[0])
251
54
      --EndPos;
252
115k
  }
253
142k
254
142k
  return EndPos;
255
142k
}
256
257
static void collectAllSubModulesWithUmbrellaHeader(
258
21.4k
    const Module &Mod, SmallVectorImpl<const Module *> &SubMods) {
259
21.4k
  if (Mod.getUmbrellaHeader())
260
526
    SubMods.push_back(&Mod);
261
21.4k
  for (auto *M : Mod.submodules())
262
19.4k
    collectAllSubModulesWithUmbrellaHeader(*M, SubMods);
263
21.4k
}
264
265
526
void Preprocessor::diagnoseMissingHeaderInUmbrellaDir(const Module &Mod) {
266
526
  const Module::Header &UmbrellaHeader = Mod.getUmbrellaHeader();
267
526
  assert(UmbrellaHeader.Entry && "Module must use umbrella header");
268
526
  const FileID &File = SourceMgr.translateFile(UmbrellaHeader.Entry);
269
526
  SourceLocation ExpectedHeadersLoc = SourceMgr.getLocForEndOfFile(File);
270
526
  if (getDiagnostics().isIgnored(diag::warn_uncovered_module_header,
271
526
                                 ExpectedHeadersLoc))
272
292
    return;
273
234
274
234
  ModuleMap &ModMap = getHeaderSearchInfo().getModuleMap();
275
234
  const DirectoryEntry *Dir = Mod.getUmbrellaDir().Entry;
276
234
  llvm::vfs::FileSystem &FS = FileMgr.getVirtualFileSystem();
277
234
  std::error_code EC;
278
234
  for (llvm::vfs::recursive_directory_iterator Entry(FS, Dir->getName(), EC),
279
234
       End;
280
938
       Entry != End && 
!EC704
;
Entry.increment(EC)704
) {
281
704
    using llvm::StringSwitch;
282
704
283
    // Check whether this entry has an extension typically associated with
284
    // headers.
285
704
    if (!StringSwitch<bool>(llvm::sys::path::extension(Entry->path()))
286
704
             .Cases(".h", ".H", ".hh", ".hpp", true)
287
704
             .Default(false))
288
50
      continue;
289
654
290
654
    if (auto Header = getFileManager().getFile(Entry->path()))
291
654
      if (!getSourceManager().hasFileInfo(*Header)) {
292
133
        if (!ModMap.isHeaderInUnavailableModule(*Header)) {
293
          // Find the relative path that would access this header.
294
52
          SmallString<128> RelativePath;
295
52
          computeRelativePath(FileMgr, Dir, *Header, RelativePath);
296
52
          Diag(ExpectedHeadersLoc, diag::warn_uncovered_module_header)
297
52
              << Mod.getFullModuleName() << RelativePath;
298
52
        }
299
133
      }
300
654
  }
301
234
}
302
303
/// HandleEndOfFile - This callback is invoked when the lexer hits the end of
304
/// the current file.  This either returns the EOF token or pops a level off
305
/// the include stack and keeps going.
306
79.0M
bool Preprocessor::HandleEndOfFile(Token &Result, bool isEndOfMacro) {
307
79.0M
  assert(!CurTokenLexer &&
308
79.0M
         "Ending a file when currently in a macro!");
309
79.0M
310
  // If we have an unclosed module region from a pragma at the end of a
311
  // module, complain and close it now.
312
79.0M
  const bool LeavingSubmodule = CurLexer && 
CurLexerSubmodule1.69M
;
313
79.0M
  if ((LeavingSubmodule || 
IncludeMacroStack.empty()79.0M
) &&
314
142k
      !BuildingSubmoduleStack.empty() &&
315
61.3k
      BuildingSubmoduleStack.back().IsPragma) {
316
2
    Diag(BuildingSubmoduleStack.back().ImportLoc,
317
2
         diag::err_pp_module_begin_without_module_end);
318
2
    Module *M = LeaveSubmodule(/*ForPragma*/true);
319
2
320
2
    Result.startToken();
321
2
    const char *EndPos = getCurLexerEndPos();
322
2
    CurLexer->BufferPtr = EndPos;
323
2
    CurLexer->FormTokenWithChars(Result, EndPos, tok::annot_module_end);
324
2
    Result.setAnnotationEndLoc(Result.getLocation());
325
2
    Result.setAnnotationValue(M);
326
2
    return true;
327
2
  }
328
79.0M
329
  // See if this file had a controlling macro.
330
79.0M
  if (CurPPLexer) {  // Not ending a macro, ignore it.
331
1.69M
    if (const IdentifierInfo *ControllingMacro =
332
618k
          CurPPLexer->MIOpt.GetControllingMacroAtEndOfFile()) {
333
      // Okay, this has a controlling macro, remember in HeaderFileInfo.
334
618k
      if (const FileEntry *FE = CurPPLexer->getFileEntry()) {
335
618k
        HeaderInfo.SetFileControllingMacro(FE, ControllingMacro);
336
618k
        if (MacroInfo *MI =
337
616k
              getMacroInfo(const_cast<IdentifierInfo*>(ControllingMacro)))
338
616k
          MI->setUsedForHeaderGuard(true);
339
618k
        if (const IdentifierInfo *DefinedMacro =
340
545k
              CurPPLexer->MIOpt.GetDefinedMacro()) {
341
545k
          if (!isMacroDefined(ControllingMacro) &&
342
14
              DefinedMacro != ControllingMacro &&
343
14
              HeaderInfo.FirstTimeLexingFile(FE)) {
344
8
345
            // If the edit distance between the two macros is more than 50%,
346
            // DefinedMacro may not be header guard, or can be header guard of
347
            // another header file. Therefore, it maybe defining something
348
            // completely different. This can be observed in the wild when
349
            // handling feature macros or header guards in different files.
350
8
351
8
            const StringRef ControllingMacroName = ControllingMacro->getName();
352
8
            const StringRef DefinedMacroName = DefinedMacro->getName();
353
8
            const size_t MaxHalfLength = std::max(ControllingMacroName.size(),
354
8
                                                  DefinedMacroName.size()) / 2;
355
8
            const unsigned ED = ControllingMacroName.edit_distance(
356
8
                DefinedMacroName, true, MaxHalfLength);
357
8
            if (ED <= MaxHalfLength) {
358
              // Emit a warning for a bad header guard.
359
6
              Diag(CurPPLexer->MIOpt.GetMacroLocation(),
360
6
                   diag::warn_header_guard)
361
6
                  << CurPPLexer->MIOpt.GetMacroLocation() << ControllingMacro;
362
6
              Diag(CurPPLexer->MIOpt.GetDefinedLocation(),
363
6
                   diag::note_header_guard)
364
6
                  << CurPPLexer->MIOpt.GetDefinedLocation() << DefinedMacro
365
6
                  << ControllingMacro
366
6
                  << FixItHint::CreateReplacement(
367
6
                         CurPPLexer->MIOpt.GetDefinedLocation(),
368
6
                         ControllingMacro->getName());
369
6
            }
370
8
          }
371
545k
        }
372
618k
      }
373
618k
    }
374
1.69M
  }
375
79.0M
376
  // Complain about reaching a true EOF within arc_cf_code_audited.
377
  // We don't want to complain about reaching the end of a macro
378
  // instantiation or a _Pragma.
379
79.0M
  if (PragmaARCCFCodeAuditedInfo.second.isValid() && 
!isEndOfMacro22.3M
&&
380
2
      !(CurLexer && CurLexer->Is_PragmaLexer)) {
381
2
    Diag(PragmaARCCFCodeAuditedInfo.second,
382
2
         diag::err_pp_eof_in_arc_cf_code_audited);
383
2
384
    // Recover by leaving immediately.
385
2
    PragmaARCCFCodeAuditedInfo = {nullptr, SourceLocation()};
386
2
  }
387
79.0M
388
  // Complain about reaching a true EOF within assume_nonnull.
389
  // We don't want to complain about reaching the end of a macro
390
  // instantiation or a _Pragma.
391
79.0M
  if (PragmaAssumeNonNullLoc.isValid() &&
392
38.1M
      !isEndOfMacro && 
!(1
CurLexer1
&&
CurLexer->Is_PragmaLexer1
)) {
393
1
    Diag(PragmaAssumeNonNullLoc, diag::err_pp_eof_in_assume_nonnull);
394
1
395
    // Recover by leaving immediately.
396
1
    PragmaAssumeNonNullLoc = SourceLocation();
397
1
  }
398
79.0M
399
79.0M
  bool LeavingPCHThroughHeader = false;
400
79.0M
401
  // If this is a #include'd file, pop it off the include stack and continue
402
  // lexing the #includer file.
403
79.0M
  if (!IncludeMacroStack.empty()) {
404
79.0M
405
    // If we lexed the code-completion file, act as if we reached EOF.
406
79.0M
    if (isCodeCompletionEnabled() && 
CurPPLexer2.10k
&&
407
1.26k
        SourceMgr.getLocForStartOfFile(CurPPLexer->getFileID()) ==
408
1
            CodeCompletionFileLoc) {
409
1
      assert(CurLexer && "Got EOF but no current lexer set!");
410
1
      Result.startToken();
411
1
      CurLexer->FormTokenWithChars(Result, CurLexer->BufferEnd, tok::eof);
412
1
      CurLexer.reset();
413
1
414
1
      CurPPLexer = nullptr;
415
1
      recomputeCurLexerKind();
416
1
      return true;
417
1
    }
418
79.0M
419
79.0M
    if (!isEndOfMacro && 
CurPPLexer998k
&&
420
998k
        (SourceMgr.getIncludeLoc(CurPPLexer->getFileID()).isValid() ||
421
         // Predefines file doesn't have a valid include location.
422
80.6k
         (PredefinesFileID.isValid() &&
423
998k
          
CurPPLexer->getFileID() == PredefinesFileID80.6k
))) {
424
      // Notify SourceManager to record the number of FileIDs that were created
425
      // during lexing of the #include'd file.
426
998k
      unsigned NumFIDs =
427
998k
          SourceMgr.local_sloc_entry_size() -
428
998k
          CurPPLexer->getInitialNumSLocEntries() + 1/*#include'd file*/;
429
998k
      SourceMgr.setNumCreatedFIDsForFileID(CurPPLexer->getFileID(), NumFIDs);
430
998k
    }
431
79.0M
432
79.0M
    bool ExitedFromPredefinesFile = false;
433
79.0M
    FileID ExitedFID;
434
79.0M
    if (!isEndOfMacro && 
CurPPLexer998k
) {
435
998k
      ExitedFID = CurPPLexer->getFileID();
436
998k
437
998k
      assert(PredefinesFileID.isValid() &&
438
998k
             "HandleEndOfFile is called before PredefinesFileId is set");
439
998k
      ExitedFromPredefinesFile = (PredefinesFileID == ExitedFID);
440
998k
    }
441
79.0M
442
79.0M
    if (LeavingSubmodule) {
443
      // We're done with this submodule.
444
61.3k
      Module *M = LeaveSubmodule(/*ForPragma*/false);
445
61.3k
446
      // Notify the parser that we've left the module.
447
61.3k
      const char *EndPos = getCurLexerEndPos();
448
61.3k
      Result.startToken();
449
61.3k
      CurLexer->BufferPtr = EndPos;
450
61.3k
      CurLexer->FormTokenWithChars(Result, EndPos, tok::annot_module_end);
451
61.3k
      Result.setAnnotationEndLoc(Result.getLocation());
452
61.3k
      Result.setAnnotationValue(M);
453
61.3k
    }
454
79.0M
455
79.0M
    bool FoundPCHThroughHeader = false;
456
79.0M
    if (CurPPLexer && 
creatingPCHWithThroughHeader()1.61M
&&
457
23
        isPCHThroughHeader(
458
23
            SourceMgr.getFileEntryForID(CurPPLexer->getFileID())))
459
12
      FoundPCHThroughHeader = true;
460
79.0M
461
    // We're done with the #included file.
462
79.0M
    RemoveTopOfLexerStack();
463
79.0M
464
    // Propagate info about start-of-line/leading white-space/etc.
465
79.0M
    PropagateLineStartLeadingSpaceInfo(Result);
466
79.0M
467
    // Notify the client, if desired, that we are in a new source file.
468
79.0M
    if (Callbacks && 
!isEndOfMacro79.0M
&&
CurPPLexer997k
) {
469
997k
      SrcMgr::CharacteristicKind FileType =
470
997k
        SourceMgr.getFileCharacteristic(CurPPLexer->getSourceLocation());
471
997k
      Callbacks->FileChanged(CurPPLexer->getSourceLocation(),
472
997k
                             PPCallbacks::ExitFile, FileType, ExitedFID);
473
997k
    }
474
79.0M
475
    // Restore conditional stack from the preamble right after exiting from the
476
    // predefines file.
477
79.0M
    if (ExitedFromPredefinesFile)
478
80.6k
      replayPreambleConditionalStack();
479
79.0M
480
79.0M
    if (!isEndOfMacro && 
CurPPLexer998k
&&
FoundPCHThroughHeader998k
&&
481
12
        (isInPrimaryFile() ||
482
12
         
CurPPLexer->getFileID() == getPredefinesFileID()7
)) {
483
      // Leaving the through header. Continue directly to end of main file
484
      // processing.
485
12
      LeavingPCHThroughHeader = true;
486
79.0M
    } else {
487
      // Client should lex another token unless we generated an EOM.
488
79.0M
      return LeavingSubmodule;
489
79.0M
    }
490
80.7k
  }
491
80.7k
492
  // If this is the end of the main file, form an EOF token.
493
80.7k
  assert(CurLexer && "Got EOF but no current lexer set!");
494
80.7k
  const char *EndPos = getCurLexerEndPos();
495
80.7k
  Result.startToken();
496
80.7k
  CurLexer->BufferPtr = EndPos;
497
80.7k
  CurLexer->FormTokenWithChars(Result, EndPos, tok::eof);
498
80.7k
499
80.7k
  if (isCodeCompletionEnabled()) {
500
    // Inserting the code-completion point increases the source buffer by 1,
501
    // but the main FileID was created before inserting the point.
502
    // Compensate by reducing the EOF location by 1, otherwise the location
503
    // will point to the next FileID.
504
    // FIXME: This is hacky, the code-completion point should probably be
505
    // inserted before the main FileID is created.
506
109
    if (CurLexer->getFileLoc() == CodeCompletionFileLoc)
507
109
      Result.setLocation(Result.getLocation().getLocWithOffset(-1));
508
109
  }
509
80.7k
510
80.7k
  if (creatingPCHWithThroughHeader() && 
!LeavingPCHThroughHeader13
) {
511
    // Reached the end of the compilation without finding the through header.
512
1
    Diag(CurLexer->getFileLoc(), diag::err_pp_through_header_not_seen)
513
1
        << PPOpts->PCHThroughHeader << 0;
514
1
  }
515
80.7k
516
80.7k
  if (!isIncrementalProcessingEnabled())
517
    // We're done with lexing.
518
78.2k
    CurLexer.reset();
519
80.7k
520
80.7k
  if (!isIncrementalProcessingEnabled())
521
78.2k
    CurPPLexer = nullptr;
522
80.7k
523
80.7k
  if (TUKind == TU_Complete) {
524
    // This is the end of the top-level file. 'WarnUnusedMacroLocs' has
525
    // collected all macro locations that we need to warn because they are not
526
    // used.
527
75.5k
    for (WarnUnusedMacroLocsTy::iterator
528
75.5k
           I=WarnUnusedMacroLocs.begin(), E=WarnUnusedMacroLocs.end();
529
75.5k
           I!=E; 
++I8
)
530
8
      Diag(*I, diag::pp_macro_not_used);
531
75.5k
  }
532
80.7k
533
  // If we are building a module that has an umbrella header, make sure that
534
  // each of the headers within the directory, including all submodules, is
535
  // covered by the umbrella header was actually included by the umbrella
536
  // header.
537
80.7k
  if (Module *Mod = getCurrentModule()) {
538
1.93k
    llvm::SmallVector<const Module *, 4> AllMods;
539
1.93k
    collectAllSubModulesWithUmbrellaHeader(*Mod, AllMods);
540
1.93k
    for (auto *M : AllMods)
541
526
      diagnoseMissingHeaderInUmbrellaDir(*M);
542
1.93k
  }
543
80.7k
544
80.7k
  return true;
545
80.7k
}
546
547
/// HandleEndOfTokenLexer - This callback is invoked when the current TokenLexer
548
/// hits the end of its token stream.
549
77.3M
bool Preprocessor::HandleEndOfTokenLexer(Token &Result) {
550
77.3M
  assert(CurTokenLexer && !CurPPLexer &&
551
77.3M
         "Ending a macro when currently in a #include file!");
552
77.3M
553
77.3M
  if (!MacroExpandingLexersStack.empty() &&
554
52.4M
      MacroExpandingLexersStack.back().first == CurTokenLexer.get())
555
47.0M
    removeCachedMacroExpandedTokensOfLastLexer();
556
77.3M
557
  // Delete or cache the now-dead macro expander.
558
77.3M
  if (NumCachedTokenLexers == TokenLexerCacheSize)
559
266k
    CurTokenLexer.reset();
560
77.1M
  else
561
77.1M
    TokenLexerCache[NumCachedTokenLexers++] = std::move(CurTokenLexer);
562
77.3M
563
  // Handle this like a #include file being popped off the stack.
564
77.3M
  return HandleEndOfFile(Result, true);
565
77.3M
}
566
567
/// RemoveTopOfLexerStack - Pop the current lexer/macro exp off the top of the
568
/// lexer stack.  This should only be used in situations where the current
569
/// state of the top-of-stack lexer is unknown.
570
151M
void Preprocessor::RemoveTopOfLexerStack() {
571
151M
  assert(!IncludeMacroStack.empty() && "Ran out of stack entries to load");
572
151M
573
151M
  if (CurTokenLexer) {
574
    // Delete or cache the now-dead macro expander.
575
6.74M
    if (NumCachedTokenLexers == TokenLexerCacheSize)
576
10
      CurTokenLexer.reset();
577
6.74M
    else
578
6.74M
      TokenLexerCache[NumCachedTokenLexers++] = std::move(CurTokenLexer);
579
6.74M
  }
580
151M
581
151M
  PopIncludeMacroStack();
582
151M
}
583
584
/// HandleMicrosoftCommentPaste - When the macro expander pastes together a
585
/// comment (/##/) in microsoft mode, this method handles updating the current
586
/// state, returning the token on the next source line.
587
4
void Preprocessor::HandleMicrosoftCommentPaste(Token &Tok) {
588
4
  assert(CurTokenLexer && !CurPPLexer &&
589
4
         "Pasted comment can only be formed from macro");
590
  // We handle this by scanning for the closest real lexer, switching it to
591
  // raw mode and preprocessor mode.  This will cause it to return \n as an
592
  // explicit EOD token.
593
4
  PreprocessorLexer *FoundLexer = nullptr;
594
4
  bool LexerWasInPPMode = false;
595
6
  for (const IncludeStackInfo &ISI : llvm::reverse(IncludeMacroStack)) {
596
6
    if (ISI.ThePPLexer == nullptr) 
continue2
; // Scan for a real lexer.
597
4
598
    // Once we find a real lexer, mark it as raw mode (disabling macro
599
    // expansions) and preprocessor mode (return EOD).  We know that the lexer
600
    // was *not* in raw mode before, because the macro that the comment came
601
    // from was expanded.  However, it could have already been in preprocessor
602
    // mode (#if COMMENT) in which case we have to return it to that mode and
603
    // return EOD.
604
4
    FoundLexer = ISI.ThePPLexer;
605
4
    FoundLexer->LexingRawMode = true;
606
4
    LexerWasInPPMode = FoundLexer->ParsingPreprocessorDirective;
607
4
    FoundLexer->ParsingPreprocessorDirective = true;
608
4
    break;
609
4
  }
610
4
611
  // Okay, we either found and switched over the lexer, or we didn't find a
612
  // lexer.  In either case, finish off the macro the comment came from, getting
613
  // the next token.
614
4
  if (!HandleEndOfTokenLexer(Tok)) Lex(Tok);
615
4
616
  // Discarding comments as long as we don't have EOF or EOD.  This 'comments
617
  // out' the rest of the line, including any tokens that came from other macros
618
  // that were active, as in:
619
  //  #define submacro a COMMENT b
620
  //    submacro c
621
  // which should lex to 'a' only: 'b' and 'c' should be removed.
622
30
  while (Tok.isNot(tok::eod) && 
Tok.isNot(tok::eof)26
)
623
26
    Lex(Tok);
624
4
625
  // If we got an eod token, then we successfully found the end of the line.
626
4
  if (Tok.is(tok::eod)) {
627
4
    assert(FoundLexer && "Can't get end of line without an active lexer");
628
    // Restore the lexer back to normal mode instead of raw mode.
629
4
    FoundLexer->LexingRawMode = false;
630
4
631
    // If the lexer was already in preprocessor mode, just return the EOD token
632
    // to finish the preprocessor line.
633
4
    if (LexerWasInPPMode) 
return0
;
634
4
635
    // Otherwise, switch out of PP mode and return the next lexed token.
636
4
    FoundLexer->ParsingPreprocessorDirective = false;
637
4
    return Lex(Tok);
638
4
  }
639
0
640
  // If we got an EOF token, then we reached the end of the token stream but
641
  // didn't find an explicit \n.  This can only happen if there was no lexer
642
  // active (an active lexer would return EOD at EOF if there was no \n in
643
  // preprocessor directive mode), so just return EOF as our token.
644
0
  assert(!FoundLexer && "Lexer should return EOD before EOF in PP mode");
645
0
}
646
647
void Preprocessor::EnterSubmodule(Module *M, SourceLocation ImportLoc,
648
61.5k
                                  bool ForPragma) {
649
61.5k
  if (!getLangOpts().ModulesLocalVisibility) {
650
    // Just track that we entered this submodule.
651
61.2k
    BuildingSubmoduleStack.push_back(
652
61.2k
        BuildingSubmoduleInfo(M, ImportLoc, ForPragma, CurSubmoduleState,
653
61.2k
                              PendingModuleMacroNames.size()));
654
61.2k
    if (Callbacks)
655
61.2k
      Callbacks->EnteredSubmodule(M, ImportLoc, ForPragma);
656
61.2k
    return;
657
61.2k
  }
658
301
659
  // Resolve as much of the module definition as we can now, before we enter
660
  // one of its headers.
661
  // FIXME: Can we enable Complain here?
662
  // FIXME: Can we do this when local visibility is disabled?
663
301
  ModuleMap &ModMap = getHeaderSearchInfo().getModuleMap();
664
301
  ModMap.resolveExports(M, /*Complain=*/false);
665
301
  ModMap.resolveUses(M, /*Complain=*/false);
666
301
  ModMap.resolveConflicts(M, /*Complain=*/false);
667
301
668
  // If this is the first time we've entered this module, set up its state.
669
301
  auto R = Submodules.insert(std::make_pair(M, SubmoduleState()));
670
301
  auto &State = R.first->second;
671
301
  bool FirstTime = R.second;
672
301
  if (FirstTime) {
673
    // Determine the set of starting macros for this submodule; take these
674
    // from the "null" module (the predefines buffer).
675
    //
676
    // FIXME: If we have local visibility but not modules enabled, the
677
    // NullSubmoduleState is polluted by #defines in the top-level source
678
    // file.
679
268
    auto &StartingMacros = NullSubmoduleState.Macros;
680
268
681
    // Restore to the starting state.
682
    // FIXME: Do this lazily, when each macro name is first referenced.
683
102k
    for (auto &Macro : StartingMacros) {
684
      // Skip uninteresting macros.
685
102k
      if (!Macro.second.getLatest() &&
686
1
          Macro.second.getOverriddenMacros().empty())
687
1
        continue;
688
102k
689
102k
      MacroState MS(Macro.second.getLatest());
690
102k
      MS.setOverriddenMacros(*this, Macro.second.getOverriddenMacros());
691
102k
      State.Macros.insert(std::make_pair(Macro.first, std::move(MS)));
692
102k
    }
693
268
  }
694
301
695
  // Track that we entered this module.
696
301
  BuildingSubmoduleStack.push_back(
697
301
      BuildingSubmoduleInfo(M, ImportLoc, ForPragma, CurSubmoduleState,
698
301
                            PendingModuleMacroNames.size()));
699
301
700
301
  if (Callbacks)
701
302
    Callbacks->EnteredSubmodule(M, ImportLoc, ForPragma);
702
301
703
  // Switch to this submodule as the current submodule.
704
301
  CurSubmoduleState = &State;
705
301
706
  // This module is visible to itself.
707
301
  if (FirstTime)
708
268
    makeModuleVisible(M, ImportLoc);
709
301
}
710
711
51.3M
bool Preprocessor::needModuleMacros() const {
712
  // If we're not within a submodule, we never need to create ModuleMacros.
713
51.3M
  if (BuildingSubmoduleStack.empty())
714
50.9M
    return false;
715
  // If we are tracking module macro visibility even for textually-included
716
  // headers, we need ModuleMacros.
717
398k
  if (getLangOpts().ModulesLocalVisibility)
718
689
    return true;
719
  // Otherwise, we only need module macros if we're actually compiling a module
720
  // interface.
721
397k
  return getLangOpts().isCompilingModule();
722
397k
}
723
724
61.5k
Module *Preprocessor::LeaveSubmodule(bool ForPragma) {
725
61.5k
  if (BuildingSubmoduleStack.empty() ||
726
61.5k
      BuildingSubmoduleStack.back().IsPragma != ForPragma) {
727
3
    assert(ForPragma && "non-pragma module enter/leave mismatch");
728
3
    return nullptr;
729
3
  }
730
61.5k
731
61.5k
  auto &Info = BuildingSubmoduleStack.back();
732
61.5k
733
61.5k
  Module *LeavingMod = Info.M;
734
61.5k
  SourceLocation ImportLoc = Info.ImportLoc;
735
61.5k
736
61.5k
  if (!needModuleMacros() ||
737
61.4k
      (!getLangOpts().ModulesLocalVisibility &&
738
61.1k
       LeavingMod->getTopLevelModuleName() != getLangOpts().CurrentModule)) {
739
    // If we don't need module macros, or this is not a module for which we
740
    // are tracking macro visibility, don't build any, and preserve the list
741
    // of pending names for the surrounding submodule.
742
88
    BuildingSubmoduleStack.pop_back();
743
88
744
88
    if (Callbacks)
745
86
      Callbacks->LeftSubmodule(LeavingMod, ImportLoc, ForPragma);
746
88
747
88
    makeModuleVisible(LeavingMod, ImportLoc);
748
88
    return LeavingMod;
749
88
  }
750
61.4k
751
  // Create ModuleMacros for any macros defined in this submodule.
752
61.4k
  llvm::SmallPtrSet<const IdentifierInfo*, 8> VisitedMacros;
753
61.4k
  for (unsigned I = Info.OuterPendingModuleMacroNames;
754
398k
       I != PendingModuleMacroNames.size(); 
++I336k
) {
755
336k
    auto *II = const_cast<IdentifierInfo*>(PendingModuleMacroNames[I]);
756
336k
    if (!VisitedMacros.insert(II).second)
757
7.35k
      continue;
758
329k
759
329k
    auto MacroIt = CurSubmoduleState->Macros.find(II);
760
329k
    if (MacroIt == CurSubmoduleState->Macros.end())
761
0
      continue;
762
329k
    auto &Macro = MacroIt->second;
763
329k
764
    // Find the starting point for the MacroDirective chain in this submodule.
765
329k
    MacroDirective *OldMD = nullptr;
766
329k
    auto *OldState = Info.OuterSubmoduleState;
767
329k
    if (getLangOpts().ModulesLocalVisibility)
768
322
      OldState = &NullSubmoduleState;
769
329k
    if (OldState && OldState != CurSubmoduleState) {
770
      // FIXME: It'd be better to start at the state from when we most recently
771
      // entered this submodule, but it doesn't really matter.
772
322
      auto &OldMacros = OldState->Macros;
773
322
      auto OldMacroIt = OldMacros.find(II);
774
322
      if (OldMacroIt == OldMacros.end())
775
322
        OldMD = nullptr;
776
0
      else
777
0
        OldMD = OldMacroIt->second.getLatest();
778
322
    }
779
329k
780
    // This module may have exported a new macro. If so, create a ModuleMacro
781
    // representing that fact.
782
329k
    bool ExplicitlyPublic = false;
783
329k
    for (auto *MD = Macro.getLatest(); MD != OldMD; 
MD = MD->getPrevious()7
) {
784
329k
      assert(MD && "broken macro directive chain");
785
329k
786
329k
      if (auto *VisMD = dyn_cast<VisibilityMacroDirective>(MD)) {
787
        // The latest visibility directive for a name in a submodule affects
788
        // all the directives that come before it.
789
169
        if (VisMD->isPublic())
790
7
          ExplicitlyPublic = true;
791
162
        else if (!ExplicitlyPublic)
792
          // Private with no following public directive: not exported.
793
162
          break;
794
329k
      } else {
795
329k
        MacroInfo *Def = nullptr;
796
329k
        if (DefMacroDirective *DefMD = dyn_cast<DefMacroDirective>(MD))
797
327k
          Def = DefMD->getInfo();
798
329k
799
        // FIXME: Issue a warning if multiple headers for the same submodule
800
        // define a macro, rather than silently ignoring all but the first.
801
329k
        bool IsNew;
802
        // Don't bother creating a module macro if it would represent a #undef
803
        // that doesn't override anything.
804
329k
        if (Def || 
!Macro.getOverriddenMacros().empty()2.01k
)
805
327k
          addModuleMacro(LeavingMod, II, Def,
806
327k
                         Macro.getOverriddenMacros(), IsNew);
807
329k
808
329k
        if (!getLangOpts().ModulesLocalVisibility) {
809
          // This macro is exposed to the rest of this compilation as a
810
          // ModuleMacro; we don't need to track its MacroDirective any more.
811
329k
          Macro.setLatest(nullptr);
812
329k
          Macro.setOverriddenMacros(*this, {});
813
329k
        }
814
329k
        break;
815
329k
      }
816
329k
    }
817
329k
  }
818
61.4k
  PendingModuleMacroNames.resize(Info.OuterPendingModuleMacroNames);
819
61.4k
820
  // FIXME: Before we leave this submodule, we should parse all the other
821
  // headers within it. Otherwise, we're left with an inconsistent state
822
  // where we've made the module visible but don't yet have its complete
823
  // contents.
824
61.4k
825
  // Put back the outer module's state, if we're tracking it.
826
61.4k
  if (getLangOpts().ModulesLocalVisibility)
827
302
    CurSubmoduleState = Info.OuterSubmoduleState;
828
61.4k
829
61.4k
  BuildingSubmoduleStack.pop_back();
830
61.4k
831
61.4k
  if (Callbacks)
832
61.4k
    Callbacks->LeftSubmodule(LeavingMod, ImportLoc, ForPragma);
833
61.4k
834
  // A nested #include makes the included submodule visible.
835
61.4k
  makeModuleVisible(LeavingMod, ImportLoc);
836
61.4k
  return LeavingMod;
837
61.4k
}