clang  19.0.0git
ParseAST.cpp
Go to the documentation of this file.
1 //===--- ParseAST.cpp - Provide the clang::ParseAST method ----------------===//
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 the clang::ParseAST method.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "clang/Parse/ParseAST.h"
14 #include "clang/AST/ASTConsumer.h"
15 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/Stmt.h"
19 #include "clang/Parse/Parser.h"
22 #include "clang/Sema/Sema.h"
24 #include "clang/Sema/SemaSYCL.h"
26 #include "llvm/Support/CrashRecoveryContext.h"
27 #include "llvm/Support/TimeProfiler.h"
28 #include <cstdio>
29 #include <memory>
30 
31 using namespace clang;
32 
33 namespace {
34 
35 /// Resets LLVM's pretty stack state so that stack traces are printed correctly
36 /// when there are nested CrashRecoveryContexts and the inner one recovers from
37 /// a crash.
38 class ResetStackCleanup
39  : public llvm::CrashRecoveryContextCleanupBase<ResetStackCleanup,
40  const void> {
41 public:
42  ResetStackCleanup(llvm::CrashRecoveryContext *Context, const void *Top)
43  : llvm::CrashRecoveryContextCleanupBase<ResetStackCleanup, const void>(
44  Context, Top) {}
45  void recoverResources() override {
46  llvm::RestorePrettyStackState(resource);
47  }
48 };
49 
50 /// If a crash happens while the parser is active, an entry is printed for it.
51 class PrettyStackTraceParserEntry : public llvm::PrettyStackTraceEntry {
52  const Parser &P;
53 public:
54  PrettyStackTraceParserEntry(const Parser &p) : P(p) {}
55  void print(raw_ostream &OS) const override;
56 };
57 
58 /// If a crash happens while the parser is active, print out a line indicating
59 /// what the current token is.
60 void PrettyStackTraceParserEntry::print(raw_ostream &OS) const {
61  const Token &Tok = P.getCurToken();
62  if (Tok.is(tok::eof)) {
63  OS << "<eof> parser at end of file\n";
64  return;
65  }
66 
67  if (Tok.getLocation().isInvalid()) {
68  OS << "<unknown> parser at unknown location\n";
69  return;
70  }
71 
72  const Preprocessor &PP = P.getPreprocessor();
73  Tok.getLocation().print(OS, PP.getSourceManager());
74  if (Tok.isAnnotation()) {
75  OS << ": at annotation token\n";
76  } else {
77  // Do the equivalent of PP.getSpelling(Tok) except for the parts that would
78  // allocate memory.
79  bool Invalid = false;
80  const SourceManager &SM = P.getPreprocessor().getSourceManager();
81  unsigned Length = Tok.getLength();
82  const char *Spelling = SM.getCharacterData(Tok.getLocation(), &Invalid);
83  if (Invalid) {
84  OS << ": unknown current parser token\n";
85  return;
86  }
87  OS << ": current parser token '" << StringRef(Spelling, Length) << "'\n";
88  }
89 }
90 
91 } // namespace
92 
93 //===----------------------------------------------------------------------===//
94 // Public interface to the file
95 //===----------------------------------------------------------------------===//
96 
97 /// ParseAST - Parse the entire file specified, notifying the ASTConsumer as
98 /// the file is parsed. This inserts the parsed decls into the translation unit
99 /// held by Ctx.
100 ///
102  ASTContext &Ctx, bool PrintStats,
103  TranslationUnitKind TUKind,
104  CodeCompleteConsumer *CompletionConsumer,
105  bool SkipFunctionBodies) {
106 
107  std::unique_ptr<Sema> S(
108  new Sema(PP, Ctx, *Consumer, TUKind, CompletionConsumer));
109 
110  // Recover resources if we crash before exiting this method.
111  llvm::CrashRecoveryContextCleanupRegistrar<Sema> CleanupSema(S.get());
112 
113  ParseAST(*S.get(), PrintStats, SkipFunctionBodies);
114 }
115 
116 void clang::ParseAST(Sema &S, bool PrintStats, bool SkipFunctionBodies) {
117  // Collect global stats on Decls/Stmts (until we have a module streamer).
118  if (PrintStats) {
121  }
122 
123  // Also turn on collection of stats inside of the Sema object.
124  bool OldCollectStats = PrintStats;
125  std::swap(OldCollectStats, S.CollectStats);
126 
127  // Initialize the template instantiation observer chain.
128  // FIXME: See note on "finalize" below.
130 
131  ASTConsumer *Consumer = &S.getASTConsumer();
132 
133  std::unique_ptr<Parser> ParseOP(
134  new Parser(S.getPreprocessor(), S, SkipFunctionBodies));
135  Parser &P = *ParseOP.get();
136 
137  llvm::CrashRecoveryContextCleanupRegistrar<const void, ResetStackCleanup>
138  CleanupPrettyStack(llvm::SavePrettyStackState());
139  PrettyStackTraceParserEntry CrashInfo(P);
140 
141  // Recover resources if we crash before exiting this method.
142  llvm::CrashRecoveryContextCleanupRegistrar<Parser>
143  CleanupParser(ParseOP.get());
144 
147  if (External)
148  External->StartTranslationUnit(Consumer);
149 
150  // If a PCH through header is specified that does not have an include in
151  // the source, or a PCH is being created with #pragma hdrstop with nothing
152  // after the pragma, there won't be any tokens or a Lexer.
153  bool HaveLexer = S.getPreprocessor().getCurrentLexer();
154 
155  if (HaveLexer) {
156  llvm::TimeTraceScope TimeScope("Frontend");
157  P.Initialize();
159  Sema::ModuleImportState ImportState;
160  EnterExpressionEvaluationContext PotentiallyEvaluated(
162 
163  for (bool AtEOF = P.ParseFirstTopLevelDecl(ADecl, ImportState); !AtEOF;
164  AtEOF = P.ParseTopLevelDecl(ADecl, ImportState)) {
165  // If we got a null return and something *was* parsed, ignore it. This
166  // is due to a top-level semicolon, an action override, or a parse error
167  // skipping something.
168  if (ADecl && !Consumer->HandleTopLevelDecl(ADecl.get()))
169  return;
170  }
171  }
172 
173  // Process any TopLevelDecls generated by #pragma weak.
174  for (Decl *D : S.WeakTopLevelDecls())
175  Consumer->HandleTopLevelDecl(DeclGroupRef(D));
176 
177  if (S.getLangOpts().SYCLIsDevice) {
178  for (Decl *D : S.SYCL().syclDeviceDecls()) {
179  Consumer->HandleTopLevelDecl(DeclGroupRef(D));
180  }
181  }
182  Consumer->HandleTranslationUnit(S.getASTContext());
183 
184  // Finalize the template instantiation observer chain.
185  // FIXME: This (and init.) should be done in the Sema class, but because
186  // Sema does not have a reliable "Finalize" function (it has a
187  // destructor, but it is not guaranteed to be called ("-disable-free")).
188  // So, do the initialization above and do the finalization here:
190 
191  std::swap(OldCollectStats, S.CollectStats);
192  if (PrintStats) {
193  llvm::errs() << "\nSTATISTICS:\n";
194  if (HaveLexer) P.getActions().PrintStats();
198  Consumer->PrintStats();
199  }
200 }
Defines the clang::ASTContext interface.
StringRef P
#define SM(sm)
Definition: Cuda.cpp:83
void print(llvm::raw_ostream &OS, const Pointer &P, ASTContext &Ctx, QualType Ty)
This file declares semantic analysis for SYCL constructs.
ASTConsumer - This is an abstract interface that should be implemented by clients that read ASTs.
Definition: ASTConsumer.h:33
virtual void HandleTranslationUnit(ASTContext &Ctx)
HandleTranslationUnit - This method is called when the ASTs for entire translation unit have been par...
Definition: ASTConsumer.h:66
virtual bool HandleTopLevelDecl(DeclGroupRef D)
HandleTopLevelDecl - Handle the specified top-level declaration.
Definition: ASTConsumer.cpp:18
virtual void PrintStats()
PrintStats - If desired, print any statistics.
Definition: ASTConsumer.h:137
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:185
void PrintStats() const
Definition: ASTContext.cpp:951
ExternalASTSource * getExternalSource() const
Retrieve a pointer to the external AST source associated with this AST context, if any.
Definition: ASTContext.h:1203
Abstract interface for a consumer of code-completion information.
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:86
static void EnableStatistics()
Definition: DeclBase.cpp:174
static void PrintStats()
Definition: DeclBase.cpp:178
RAII object that enters a new expression evaluation context.
Abstract interface for external sources of AST nodes.
Wrapper for void* pointer.
Definition: Ownership.h:50
PtrTy get() const
Definition: Ownership.h:80
Parser - This implements a parser for the C family of languages.
Definition: Parser.h:58
Engages in a tight little dance with the lexer to efficiently preprocess tokens.
Definition: Preprocessor.h:128
SourceManager & getSourceManager() const
void EnterMainSourceFile()
Enter the specified FileID as the main source file, which implicitly adds the builtin defines etc.
PreprocessorLexer * getCurrentLexer() const
Return the current lexer being lexed from.
llvm::SetVector< Decl * > & syclDeviceDecls()
Definition: SemaSYCL.h:276
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:462
Preprocessor & getPreprocessor() const
Definition: Sema.h:525
const LangOptions & getLangOpts() const
Definition: Sema.h:519
bool CollectStats
Flag indicating whether or not to collect detailed statistics.
Definition: Sema.h:800
std::vector< std::unique_ptr< TemplateInstantiationCallback > > TemplateInstCallbacks
The template instantiation callbacks to trace or track instantiations (objects can be chained).
Definition: Sema.h:10411
SmallVectorImpl< Decl * > & WeakTopLevelDecls()
WeakTopLevelDeclDecls - access to #pragma weak-generated Decls.
Definition: Sema.h:3569
SemaSYCL & SYCL()
Definition: Sema.h:1037
ASTContext & getASTContext() const
Definition: Sema.h:526
ModuleImportState
An enumeration to represent the transition of states in parsing module fragments and imports.
Definition: Sema.h:7888
@ PotentiallyEvaluated
The current expression is potentially evaluated at run time, which means that code may be generated t...
ASTConsumer & getASTConsumer() const
Definition: Sema.h:527
void print(raw_ostream &OS, const SourceManager &SM) const
This class handles loading and caching of source files into memory.
static void EnableStatistics()
Definition: Stmt.cpp:131
static void PrintStats()
Definition: Stmt.cpp:101
Token - This structure provides full information about a lexed token.
Definition: Token.h:36
SourceLocation getLocation() const
Return a source location identifier for the specified offset in the current file.
Definition: Token.h:132
unsigned getLength() const
Definition: Token.h:135
bool is(tok::TokenKind K) const
is/isNot - Predicates to check if this token is a specific kind, as in "if (Tok.is(tok::l_brace)) {....
Definition: Token.h:99
bool isAnnotation() const
Return true if this is any of tok::annot_* kind tokens.
Definition: Token.h:121
The JSON file list parser is used to communicate input to InstallAPI.
void ParseAST(Preprocessor &pp, ASTConsumer *C, ASTContext &Ctx, bool PrintStats=false, TranslationUnitKind TUKind=TU_Complete, CodeCompleteConsumer *CompletionConsumer=nullptr, bool SkipFunctionBodies=false)
Parse the entire file specified, notifying the ASTConsumer as the file is parsed.
Definition: ParseAST.cpp:101
void initialize(TemplateInstantiationCallbackPtrs &Callbacks, const Sema &TheSema)
@ External
External linkage, which indicates that the entity can be referred to from other translation units.
TranslationUnitKind
Describes the kind of translation unit being processed.
Definition: LangOptions.h:1074
void finalize(TemplateInstantiationCallbackPtrs &Callbacks, const Sema &TheSema)
Diagnostic wrappers for TextAPI types for error reporting.
Definition: Dominators.h:30