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