Coverage Report

Created: 2022-01-18 06:27

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