Coverage Report

Created: 2019-07-24 05:18

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