Unnamed: 0
int64
0
0
repo_id
stringlengths
5
186
file_path
stringlengths
15
223
content
stringlengths
1
32.8M
0
repos/DirectXShaderCompiler/tools/clang/include/clang/StaticAnalyzer
repos/DirectXShaderCompiler/tools/clang/include/clang/StaticAnalyzer/Frontend/AnalysisConsumer.h
//===--- AnalysisConsumer.h - Front-end Analysis Engine Hooks ---*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This header contains the functions necessary for a front-end to run various // analyses. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_STATICANALYZER_FRONTEND_ANALYSISCONSUMER_H #define LLVM_CLANG_STATICANALYZER_FRONTEND_ANALYSISCONSUMER_H #include "clang/AST/ASTConsumer.h" #include "clang/Basic/LLVM.h" #include "clang/StaticAnalyzer/Core/AnalyzerOptions.h" #include "clang/StaticAnalyzer/Core/BugReporter/PathDiagnostic.h" #include <string> namespace clang { class Preprocessor; class DiagnosticsEngine; class CodeInjector; class CompilerInstance; namespace ento { class CheckerManager; class AnalysisASTConsumer : public ASTConsumer { public: virtual void AddDiagnosticConsumer(PathDiagnosticConsumer *Consumer) = 0; }; /// CreateAnalysisConsumer - Creates an ASTConsumer to run various code /// analysis passes. (The set of analyses run is controlled by command-line /// options.) std::unique_ptr<AnalysisASTConsumer> CreateAnalysisConsumer(CompilerInstance &CI); } // end GR namespace } // end clang namespace #endif
0
repos/DirectXShaderCompiler/tools/clang/include/clang/StaticAnalyzer
repos/DirectXShaderCompiler/tools/clang/include/clang/StaticAnalyzer/Frontend/FrontendActions.h
//===-- FrontendActions.h - Useful Frontend Actions -------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_STATICANALYZER_FRONTEND_FRONTENDACTIONS_H #define LLVM_CLANG_STATICANALYZER_FRONTEND_FRONTENDACTIONS_H #include "clang/Frontend/FrontendAction.h" #include "llvm/ADT/StringMap.h" #include "llvm/ADT/StringRef.h" namespace clang { class Stmt; namespace ento { //===----------------------------------------------------------------------===// // AST Consumer Actions // // /////////////////////////////////////////////////////////////////////////////// class AnalysisAction : public ASTFrontendAction { protected: std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &CI, StringRef InFile) override; }; /// \brief Frontend action to parse model files. /// /// This frontend action is responsible for parsing model files. Model files can /// not be parsed on their own, they rely on type information that is available /// in another translation unit. The parsing of model files is done by a /// separate compiler instance that reuses the ASTContext and othen information /// from the main translation unit that is being compiled. After a model file is /// parsed, the function definitions will be collected into a StringMap. class ParseModelFileAction : public ASTFrontendAction { public: ParseModelFileAction(llvm::StringMap<Stmt *> &Bodies); bool isModelParsingAction() const override { return true; } protected: std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &CI, StringRef InFile) override; private: llvm::StringMap<Stmt *> &Bodies; }; void printCheckerHelp(raw_ostream &OS, ArrayRef<std::string> plugins); } // end GR namespace } // end namespace clang #endif
0
repos/DirectXShaderCompiler/tools/clang/include/clang/StaticAnalyzer
repos/DirectXShaderCompiler/tools/clang/include/clang/StaticAnalyzer/Frontend/ModelConsumer.h
//===-- ModelConsumer.h -----------------------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// /// /// \file /// \brief This file implements clang::ento::ModelConsumer which is an /// ASTConsumer for model files. /// //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_GR_MODELCONSUMER_H #define LLVM_CLANG_GR_MODELCONSUMER_H #include "clang/AST/ASTConsumer.h" #include "llvm/ADT/StringMap.h" namespace clang { class Stmt; namespace ento { /// \brief ASTConsumer to consume model files' AST. /// /// This consumer collects the bodies of function definitions into a StringMap /// from a model file. class ModelConsumer : public ASTConsumer { public: ModelConsumer(llvm::StringMap<Stmt *> &Bodies); bool HandleTopLevelDecl(DeclGroupRef D) override; private: llvm::StringMap<Stmt *> &Bodies; }; } } #endif
0
repos/DirectXShaderCompiler/tools/clang/include/clang/StaticAnalyzer
repos/DirectXShaderCompiler/tools/clang/include/clang/StaticAnalyzer/Frontend/CheckerRegistration.h
//===-- CheckerRegistration.h - Checker Registration Function ---*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_STATICANALYZER_FRONTEND_CHECKERREGISTRATION_H #define LLVM_CLANG_STATICANALYZER_FRONTEND_CHECKERREGISTRATION_H #include "clang/Basic/LLVM.h" #include <memory> #include <string> namespace clang { class AnalyzerOptions; class LangOptions; class DiagnosticsEngine; namespace ento { class CheckerManager; std::unique_ptr<CheckerManager> createCheckerManager(AnalyzerOptions &opts, const LangOptions &langOpts, ArrayRef<std::string> plugins, DiagnosticsEngine &diags); } // end ento namespace } // end namespace clang #endif
0
repos/DirectXShaderCompiler/tools/clang/include/clang/StaticAnalyzer
repos/DirectXShaderCompiler/tools/clang/include/clang/StaticAnalyzer/Checkers/LocalCheckers.h
//==- LocalCheckers.h - Intra-Procedural+Flow-Sensitive Checkers -*- C++ -*-==// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines the interface to call a set of intra-procedural (local) // checkers that use flow/path-sensitive analyses to find bugs. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_STATICANALYZER_CHECKERS_LOCALCHECKERS_H #define LLVM_CLANG_STATICANALYZER_CHECKERS_LOCALCHECKERS_H namespace clang { namespace ento { class ExprEngine; void RegisterCallInliner(ExprEngine &Eng); } // end namespace ento } // end namespace clang #endif
0
repos/DirectXShaderCompiler/tools/clang/include/clang/StaticAnalyzer
repos/DirectXShaderCompiler/tools/clang/include/clang/StaticAnalyzer/Checkers/ClangCheckers.h
//===--- ClangCheckers.h - Provides builtin checkers ------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_STATICANALYZER_CHECKERS_CLANGCHECKERS_H #define LLVM_CLANG_STATICANALYZER_CHECKERS_CLANGCHECKERS_H namespace clang { namespace ento { class CheckerRegistry; void registerBuiltinCheckers(CheckerRegistry &registry); } // end namespace ento } // end namespace clang #endif
0
repos/DirectXShaderCompiler/tools/clang/include/clang/StaticAnalyzer
repos/DirectXShaderCompiler/tools/clang/include/clang/StaticAnalyzer/Checkers/ObjCRetainCount.h
//==-- ObjCRetainCount.h - Retain count summaries for Cocoa -------*- C++ -*--// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines the core data structures for retain count "summaries" // for Objective-C and Core Foundation APIs. These summaries are used // by the static analyzer to summarize the retain/release effects of // function and method calls. This drives a path-sensitive typestate // analysis in the static analyzer, but can also potentially be used by // other clients. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_STATICANALYZER_CHECKERS_OBJCRETAINCOUNT_H #define LLVM_CLANG_STATICANALYZER_CHECKERS_OBJCRETAINCOUNT_H #include "clang/Basic/LLVM.h" #include "llvm/ADT/ArrayRef.h" #include "llvm/ADT/SmallVector.h" namespace clang { class FunctionDecl; class ObjCMethodDecl; namespace ento { namespace objc_retain { /// An ArgEffect summarizes the retain count behavior on an argument or receiver /// to a function or method. enum ArgEffect { /// There is no effect. DoNothing, /// The argument is treated as if an -autorelease message had been sent to /// the referenced object. Autorelease, /// The argument is treated as if an -dealloc message had been sent to /// the referenced object. Dealloc, /// The argument has its reference count decreased by 1. This is as /// if CFRelease has been called on the argument. DecRef, /// The argument has its reference count decreased by 1. This is as /// if a -release message has been sent to the argument. This differs /// in behavior from DecRef when GC is enabled. DecRefMsg, /// The argument has its reference count decreased by 1 to model /// a transferred bridge cast under ARC. DecRefBridgedTransferred, /// The argument has its reference count increased by 1. This is as /// if a -retain message has been sent to the argument. This differs /// in behavior from IncRef when GC is enabled. IncRefMsg, /// The argument has its reference count increased by 1. This is as /// if CFRetain has been called on the argument. IncRef, /// The argument acts as if has been passed to CFMakeCollectable, which /// transfers the object to the Garbage Collector under GC. MakeCollectable, /// The argument is a pointer to a retain-counted object; on exit, the new /// value of the pointer is a +0 value or NULL. UnretainedOutParameter, /// The argument is a pointer to a retain-counted object; on exit, the new /// value of the pointer is a +1 value or NULL. RetainedOutParameter, /// The argument is treated as potentially escaping, meaning that /// even when its reference count hits 0 it should be treated as still /// possibly being alive as someone else *may* be holding onto the object. MayEscape, /// All typestate tracking of the object ceases. This is usually employed /// when the effect of the call is completely unknown. StopTracking, /// All typestate tracking of the object ceases. Unlike StopTracking, /// this is also enforced when the method body is inlined. /// /// In some cases, we obtain a better summary for this checker /// by looking at the call site than by inlining the function. /// Signifies that we should stop tracking the symbol even if /// the function is inlined. StopTrackingHard, /// Performs the combined functionality of DecRef and StopTrackingHard. /// /// The models the effect that the called function decrements the reference /// count of the argument and all typestate tracking on that argument /// should cease. DecRefAndStopTrackingHard, /// Performs the combined functionality of DecRefMsg and StopTrackingHard. /// /// The models the effect that the called function decrements the reference /// count of the argument and all typestate tracking on that argument /// should cease. DecRefMsgAndStopTrackingHard }; /// RetEffect summarizes a call's retain/release behavior with respect /// to its return value. class RetEffect { public: enum Kind { /// Indicates that no retain count information is tracked for /// the return value. NoRet, /// Indicates that the returned value is an owned (+1) symbol. OwnedSymbol, /// Indicates that the returned value is an owned (+1) symbol and /// that it should be treated as freshly allocated. OwnedAllocatedSymbol, /// Indicates that the returned value is an object with retain count /// semantics but that it is not owned (+0). This is the default /// for getters, etc. NotOwnedSymbol, /// Indicates that the object is not owned and controlled by the /// Garbage collector. GCNotOwnedSymbol, /// Indicates that the return value is an owned object when the /// receiver is also a tracked object. OwnedWhenTrackedReceiver, // Treat this function as returning a non-tracked symbol even if // the function has been inlined. This is used where the call // site summary is more presise than the summary indirectly produced // by inlining the function NoRetHard }; /// Determines the object kind of a tracked object. enum ObjKind { /// Indicates that the tracked object is a CF object. This is /// important between GC and non-GC code. CF, /// Indicates that the tracked object is an Objective-C object. ObjC, /// Indicates that the tracked object could be a CF or Objective-C object. AnyObj }; private: Kind K; ObjKind O; RetEffect(Kind k, ObjKind o = AnyObj) : K(k), O(o) {} public: Kind getKind() const { return K; } ObjKind getObjKind() const { return O; } bool isOwned() const { return K == OwnedSymbol || K == OwnedAllocatedSymbol || K == OwnedWhenTrackedReceiver; } bool notOwned() const { return K == NotOwnedSymbol; } bool operator==(const RetEffect &Other) const { return K == Other.K && O == Other.O; } static RetEffect MakeOwnedWhenTrackedReceiver() { return RetEffect(OwnedWhenTrackedReceiver, ObjC); } static RetEffect MakeOwned(ObjKind o, bool isAllocated = false) { return RetEffect(isAllocated ? OwnedAllocatedSymbol : OwnedSymbol, o); } static RetEffect MakeNotOwned(ObjKind o) { return RetEffect(NotOwnedSymbol, o); } static RetEffect MakeGCNotOwned() { return RetEffect(GCNotOwnedSymbol, ObjC); } static RetEffect MakeNoRet() { return RetEffect(NoRet); } static RetEffect MakeNoRetHard() { return RetEffect(NoRetHard); } }; /// Encapsulates the retain count semantics on the arguments, return value, /// and receiver (if any) of a function/method call. /// /// Note that construction of these objects is not highly efficient. That /// is okay for clients where creating these objects isn't really a bottleneck. /// The purpose of the API is to provide something simple. The actual /// static analyzer checker that implements retain/release typestate /// tracking uses something more efficient. class CallEffects { llvm::SmallVector<ArgEffect, 10> Args; RetEffect Ret; ArgEffect Receiver; CallEffects(const RetEffect &R) : Ret(R) {} public: /// Returns the argument effects for a call. ArrayRef<ArgEffect> getArgs() const { return Args; } /// Returns the effects on the receiver. ArgEffect getReceiver() const { return Receiver; } /// Returns the effect on the return value. RetEffect getReturnValue() const { return Ret; } /// Return the CallEfect for a given Objective-C method. static CallEffects getEffect(const ObjCMethodDecl *MD); /// Return the CallEfect for a given C/C++ function. static CallEffects getEffect(const FunctionDecl *FD); }; }}} #endif
0
repos/DirectXShaderCompiler/tools/clang/include/clang/StaticAnalyzer
repos/DirectXShaderCompiler/tools/clang/include/clang/StaticAnalyzer/Core/AnalyzerOptions.h
//===--- AnalyzerOptions.h - Analysis Engine Options ------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This header defines various options for the static analyzer that are set // by the frontend and are consulted throughout the analyzer. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_STATICANALYZER_CORE_ANALYZEROPTIONS_H #define LLVM_CLANG_STATICANALYZER_CORE_ANALYZEROPTIONS_H #include "clang/Basic/LLVM.h" #include "llvm/ADT/IntrusiveRefCntPtr.h" #include "llvm/ADT/Optional.h" #include "llvm/ADT/StringMap.h" #include <string> #include <vector> namespace clang { class ASTConsumer; class DiagnosticsEngine; class Preprocessor; class LangOptions; namespace ento { class CheckerBase; } /// Analysis - Set of available source code analyses. enum Analyses { #define ANALYSIS(NAME, CMDFLAG, DESC, SCOPE) NAME, #include "clang/StaticAnalyzer/Core/Analyses.def" NumAnalyses }; /// AnalysisStores - Set of available analysis store models. enum AnalysisStores { #define ANALYSIS_STORE(NAME, CMDFLAG, DESC, CREATFN) NAME##Model, #include "clang/StaticAnalyzer/Core/Analyses.def" NumStores }; /// AnalysisConstraints - Set of available constraint models. enum AnalysisConstraints { #define ANALYSIS_CONSTRAINTS(NAME, CMDFLAG, DESC, CREATFN) NAME##Model, #include "clang/StaticAnalyzer/Core/Analyses.def" NumConstraints }; /// AnalysisDiagClients - Set of available diagnostic clients for rendering /// analysis results. enum AnalysisDiagClients { #define ANALYSIS_DIAGNOSTICS(NAME, CMDFLAG, DESC, CREATFN) PD_##NAME, #include "clang/StaticAnalyzer/Core/Analyses.def" PD_NONE, NUM_ANALYSIS_DIAG_CLIENTS }; /// AnalysisPurgeModes - Set of available strategies for dead symbol removal. enum AnalysisPurgeMode { #define ANALYSIS_PURGE(NAME, CMDFLAG, DESC) NAME, #include "clang/StaticAnalyzer/Core/Analyses.def" NumPurgeModes }; /// AnalysisInlineFunctionSelection - Set of inlining function selection heuristics. enum AnalysisInliningMode { #define ANALYSIS_INLINING_MODE(NAME, CMDFLAG, DESC) NAME, #include "clang/StaticAnalyzer/Core/Analyses.def" NumInliningModes }; /// \brief Describes the different kinds of C++ member functions which can be /// considered for inlining by the analyzer. /// /// These options are cumulative; enabling one kind of member function will /// enable all kinds with lower enum values. enum CXXInlineableMemberKind { // Uninitialized = 0, /// A dummy mode in which no C++ inlining is enabled. CIMK_None = 1, /// Refers to regular member function and operator calls. CIMK_MemberFunctions, /// Refers to constructors (implicit or explicit). /// /// Note that a constructor will not be inlined if the corresponding /// destructor is non-trivial. CIMK_Constructors, /// Refers to destructors (implicit or explicit). CIMK_Destructors }; /// \brief Describes the different modes of inter-procedural analysis. enum IPAKind { IPAK_NotSet = 0, /// Perform only intra-procedural analysis. IPAK_None = 1, /// Inline C functions and blocks when their definitions are available. IPAK_BasicInlining = 2, /// Inline callees(C, C++, ObjC) when their definitions are available. IPAK_Inlining = 3, /// Enable inlining of dynamically dispatched methods. IPAK_DynamicDispatch = 4, /// Enable inlining of dynamically dispatched methods, bifurcate paths when /// exact type info is unavailable. IPAK_DynamicDispatchBifurcate = 5 }; class AnalyzerOptions : public RefCountedBase<AnalyzerOptions> { public: typedef llvm::StringMap<std::string> ConfigTable; /// \brief Pair of checker name and enable/disable. std::vector<std::pair<std::string, bool> > CheckersControlList; /// \brief A key-value table of use-specified configuration values. ConfigTable Config; AnalysisStores AnalysisStoreOpt; AnalysisConstraints AnalysisConstraintsOpt; AnalysisDiagClients AnalysisDiagOpt; AnalysisPurgeMode AnalysisPurgeOpt; std::string AnalyzeSpecificFunction; /// \brief The maximum number of times the analyzer visits a block. unsigned maxBlockVisitOnPath; /// \brief Disable all analyzer checks. /// /// This flag allows one to disable analyzer checks on the code processed by /// the given analysis consumer. Note, the code will get parsed and the /// command-line options will get checked. unsigned DisableAllChecks : 1; unsigned ShowCheckerHelp : 1; unsigned AnalyzeAll : 1; unsigned AnalyzerDisplayProgress : 1; unsigned AnalyzeNestedBlocks : 1; /// \brief The flag regulates if we should eagerly assume evaluations of /// conditionals, thus, bifurcating the path. /// /// This flag indicates how the engine should handle expressions such as: 'x = /// (y != 0)'. When this flag is true then the subexpression 'y != 0' will be /// eagerly assumed to be true or false, thus evaluating it to the integers 0 /// or 1 respectively. The upside is that this can increase analysis /// precision until we have a better way to lazily evaluate such logic. The /// downside is that it eagerly bifurcates paths. unsigned eagerlyAssumeBinOpBifurcation : 1; unsigned TrimGraph : 1; unsigned visualizeExplodedGraphWithGraphViz : 1; unsigned visualizeExplodedGraphWithUbiGraph : 1; unsigned UnoptimizedCFG : 1; unsigned PrintStats : 1; /// \brief Do not re-analyze paths leading to exhausted nodes with a different /// strategy. We get better code coverage when retry is enabled. unsigned NoRetryExhausted : 1; /// \brief The inlining stack depth limit. unsigned InlineMaxStackDepth; /// \brief The mode of function selection used during inlining. AnalysisInliningMode InliningMode; private: /// \brief Describes the kinds for high-level analyzer mode. enum UserModeKind { UMK_NotSet = 0, /// Perform shallow but fast analyzes. UMK_Shallow = 1, /// Perform deep analyzes. UMK_Deep = 2 }; /// Controls the high-level analyzer mode, which influences the default /// settings for some of the lower-level config options (such as IPAMode). /// \sa getUserMode UserModeKind UserMode; /// Controls the mode of inter-procedural analysis. IPAKind IPAMode; /// Controls which C++ member functions will be considered for inlining. CXXInlineableMemberKind CXXMemberInliningMode; /// \sa includeTemporaryDtorsInCFG Optional<bool> IncludeTemporaryDtorsInCFG; /// \sa mayInlineCXXStandardLibrary Optional<bool> InlineCXXStandardLibrary; /// \sa mayInlineTemplateFunctions Optional<bool> InlineTemplateFunctions; /// \sa mayInlineCXXAllocator Optional<bool> InlineCXXAllocator; /// \sa mayInlineCXXContainerMethods Optional<bool> InlineCXXContainerMethods; /// \sa mayInlineCXXSharedPtrDtor Optional<bool> InlineCXXSharedPtrDtor; /// \sa mayInlineObjCMethod Optional<bool> ObjCInliningMode; // Cache of the "ipa-always-inline-size" setting. // \sa getAlwaysInlineSize Optional<unsigned> AlwaysInlineSize; /// \sa shouldSuppressNullReturnPaths Optional<bool> SuppressNullReturnPaths; // \sa getMaxInlinableSize Optional<unsigned> MaxInlinableSize; /// \sa shouldAvoidSuppressingNullArgumentPaths Optional<bool> AvoidSuppressingNullArgumentPaths; /// \sa shouldSuppressInlinedDefensiveChecks Optional<bool> SuppressInlinedDefensiveChecks; /// \sa shouldSuppressFromCXXStandardLibrary Optional<bool> SuppressFromCXXStandardLibrary; /// \sa reportIssuesInMainSourceFile Optional<bool> ReportIssuesInMainSourceFile; /// \sa StableReportFilename Optional<bool> StableReportFilename; /// \sa getGraphTrimInterval Optional<unsigned> GraphTrimInterval; /// \sa getMaxTimesInlineLarge Optional<unsigned> MaxTimesInlineLarge; /// \sa getMaxNodesPerTopLevelFunction Optional<unsigned> MaxNodesPerTopLevelFunction; /// A helper function that retrieves option for a given full-qualified /// checker name. /// Options for checkers can be specified via 'analyzer-config' command-line /// option. /// Example: /// @code-analyzer-config unix.Malloc:OptionName=CheckerOptionValue @endcode /// or @code-analyzer-config unix:OptionName=GroupOptionValue @endcode /// for groups of checkers. /// @param [in] CheckerName Full-qualified checker name, like /// alpha.unix.StreamChecker. /// @param [in] OptionName Name of the option to get. /// @param [in] Default Default value if no option is specified. /// @param [in] SearchInParents If set to true and the searched option was not /// specified for the given checker the options for the parent packages will /// be searched as well. The inner packages take precedence over the outer /// ones. /// @retval CheckerOptionValue An option for a checker if it was specified. /// @retval GroupOptionValue An option for group if it was specified and no /// checker-specific options were found. The closer group to checker, /// the more priority it has. For example, @c coregroup.subgroup has more /// priority than @c coregroup for @c coregroup.subgroup.CheckerName checker. /// @retval Default If nor checker option, nor group option was found. StringRef getCheckerOption(StringRef CheckerName, StringRef OptionName, StringRef Default, bool SearchInParents = false); public: /// Interprets an option's string value as a boolean. The "true" string is /// interpreted as true and the "false" string is interpreted as false. /// /// If an option value is not provided, returns the given \p DefaultVal. /// @param [in] Name Name for option to retrieve. /// @param [in] DefaultVal Default value returned if no such option was /// specified. /// @param [in] C The optional checker parameter that can be used to restrict /// the search to the options of this particular checker (and its parents /// dependening on search mode). /// @param [in] SearchInParents If set to true and the searched option was not /// specified for the given checker the options for the parent packages will /// be searched as well. The inner packages take precedence over the outer /// ones. bool getBooleanOption(StringRef Name, bool DefaultVal, const ento::CheckerBase *C = nullptr, bool SearchInParents = false); /// Variant that accepts a Optional value to cache the result. /// /// @param [in,out] V Return value storage, returned if parameter contains /// an existing valid option, else it is used to store a return value /// @param [in] Name Name for option to retrieve. /// @param [in] DefaultVal Default value returned if no such option was /// specified. /// @param [in] C The optional checker parameter that can be used to restrict /// the search to the options of this particular checker (and its parents /// dependening on search mode). /// @param [in] SearchInParents If set to true and the searched option was not /// specified for the given checker the options for the parent packages will /// be searched as well. The inner packages take precedence over the outer /// ones. bool getBooleanOption(Optional<bool> &V, StringRef Name, bool DefaultVal, const ento::CheckerBase *C = nullptr, bool SearchInParents = false); /// Interprets an option's string value as an integer value. /// /// If an option value is not provided, returns the given \p DefaultVal. /// @param [in] Name Name for option to retrieve. /// @param [in] DefaultVal Default value returned if no such option was /// specified. /// @param [in] C The optional checker parameter that can be used to restrict /// the search to the options of this particular checker (and its parents /// dependening on search mode). /// @param [in] SearchInParents If set to true and the searched option was not /// specified for the given checker the options for the parent packages will /// be searched as well. The inner packages take precedence over the outer /// ones. int getOptionAsInteger(StringRef Name, int DefaultVal, const ento::CheckerBase *C = nullptr, bool SearchInParents = false); /// Query an option's string value. /// /// If an option value is not provided, returns the given \p DefaultVal. /// @param [in] Name Name for option to retrieve. /// @param [in] DefaultVal Default value returned if no such option was /// specified. /// @param [in] C The optional checker parameter that can be used to restrict /// the search to the options of this particular checker (and its parents /// dependening on search mode). /// @param [in] SearchInParents If set to true and the searched option was not /// specified for the given checker the options for the parent packages will /// be searched as well. The inner packages take precedence over the outer /// ones. StringRef getOptionAsString(StringRef Name, StringRef DefaultVal, const ento::CheckerBase *C = nullptr, bool SearchInParents = false); /// \brief Retrieves and sets the UserMode. This is a high-level option, /// which is used to set other low-level options. It is not accessible /// outside of AnalyzerOptions. UserModeKind getUserMode(); /// \brief Returns the inter-procedural analysis mode. IPAKind getIPAMode(); /// Returns the option controlling which C++ member functions will be /// considered for inlining. /// /// This is controlled by the 'c++-inlining' config option. /// /// \sa CXXMemberInliningMode bool mayInlineCXXMemberFunction(CXXInlineableMemberKind K); /// Returns true if ObjectiveC inlining is enabled, false otherwise. bool mayInlineObjCMethod(); /// Returns whether or not the destructors for C++ temporary objects should /// be included in the CFG. /// /// This is controlled by the 'cfg-temporary-dtors' config option, which /// accepts the values "true" and "false". bool includeTemporaryDtorsInCFG(); /// Returns whether or not C++ standard library functions may be considered /// for inlining. /// /// This is controlled by the 'c++-stdlib-inlining' config option, which /// accepts the values "true" and "false". bool mayInlineCXXStandardLibrary(); /// Returns whether or not templated functions may be considered for inlining. /// /// This is controlled by the 'c++-template-inlining' config option, which /// accepts the values "true" and "false". bool mayInlineTemplateFunctions(); /// Returns whether or not allocator call may be considered for inlining. /// /// This is controlled by the 'c++-allocator-inlining' config option, which /// accepts the values "true" and "false". bool mayInlineCXXAllocator(); /// Returns whether or not methods of C++ container objects may be considered /// for inlining. /// /// This is controlled by the 'c++-container-inlining' config option, which /// accepts the values "true" and "false". bool mayInlineCXXContainerMethods(); /// Returns whether or not the destructor of C++ 'shared_ptr' may be /// considered for inlining. /// /// This covers std::shared_ptr, std::tr1::shared_ptr, and boost::shared_ptr, /// and indeed any destructor named "~shared_ptr". /// /// This is controlled by the 'c++-shared_ptr-inlining' config option, which /// accepts the values "true" and "false". bool mayInlineCXXSharedPtrDtor(); /// Returns whether or not paths that go through null returns should be /// suppressed. /// /// This is a heuristic for avoiding bug reports with paths that go through /// inlined functions that are more defensive than their callers. /// /// This is controlled by the 'suppress-null-return-paths' config option, /// which accepts the values "true" and "false". bool shouldSuppressNullReturnPaths(); /// Returns whether a bug report should \em not be suppressed if its path /// includes a call with a null argument, even if that call has a null return. /// /// This option has no effect when #shouldSuppressNullReturnPaths() is false. /// /// This is a counter-heuristic to avoid false negatives. /// /// This is controlled by the 'avoid-suppressing-null-argument-paths' config /// option, which accepts the values "true" and "false". bool shouldAvoidSuppressingNullArgumentPaths(); /// Returns whether or not diagnostics containing inlined defensive NULL /// checks should be suppressed. /// /// This is controlled by the 'suppress-inlined-defensive-checks' config /// option, which accepts the values "true" and "false". bool shouldSuppressInlinedDefensiveChecks(); /// Returns whether or not diagnostics reported within the C++ standard /// library should be suppressed. /// /// This is controlled by the 'suppress-c++-stdlib' config option, /// which accepts the values "true" and "false". bool shouldSuppressFromCXXStandardLibrary(); /// Returns whether or not the diagnostic report should be always reported /// in the main source file and not the headers. /// /// This is controlled by the 'report-in-main-source-file' config option, /// which accepts the values "true" and "false". bool shouldReportIssuesInMainSourceFile(); /// Returns whether or not the report filename should be random or not. /// /// This is controlled by the 'stable-report-filename' config option, /// which accepts the values "true" and "false". Default = false bool shouldWriteStableReportFilename(); /// Returns whether irrelevant parts of a bug report path should be pruned /// out of the final output. /// /// This is controlled by the 'prune-paths' config option, which accepts the /// values "true" and "false". bool shouldPrunePaths(); /// Returns true if 'static' initializers should be in conditional logic /// in the CFG. bool shouldConditionalizeStaticInitializers(); // Returns the size of the functions (in basic blocks), which should be // considered to be small enough to always inline. // // This is controlled by "ipa-always-inline-size" analyzer-config option. unsigned getAlwaysInlineSize(); // Returns the bound on the number of basic blocks in an inlined function // (50 by default). // // This is controlled by "-analyzer-config max-inlinable-size" option. unsigned getMaxInlinableSize(); /// Returns true if the analyzer engine should synthesize fake bodies /// for well-known functions. bool shouldSynthesizeBodies(); /// Returns how often nodes in the ExplodedGraph should be recycled to save /// memory. /// /// This is controlled by the 'graph-trim-interval' config option. To disable /// node reclamation, set the option to "0". unsigned getGraphTrimInterval(); /// Returns the maximum times a large function could be inlined. /// /// This is controlled by the 'max-times-inline-large' config option. unsigned getMaxTimesInlineLarge(); /// Returns the maximum number of nodes the analyzer can generate while /// exploring a top level function (for each exploded graph). /// 150000 is default; 0 means no limit. /// /// This is controlled by the 'max-nodes' config option. unsigned getMaxNodesPerTopLevelFunction(); public: AnalyzerOptions() : AnalysisStoreOpt(RegionStoreModel), AnalysisConstraintsOpt(RangeConstraintsModel), AnalysisDiagOpt(PD_HTML), AnalysisPurgeOpt(PurgeStmt), DisableAllChecks(0), ShowCheckerHelp(0), AnalyzeAll(0), AnalyzerDisplayProgress(0), AnalyzeNestedBlocks(0), eagerlyAssumeBinOpBifurcation(0), TrimGraph(0), visualizeExplodedGraphWithGraphViz(0), visualizeExplodedGraphWithUbiGraph(0), UnoptimizedCFG(0), PrintStats(0), NoRetryExhausted(0), // Cap the stack depth at 4 calls (5 stack frames, base + 4 calls). InlineMaxStackDepth(5), InliningMode(NoRedundancy), UserMode(UMK_NotSet), IPAMode(IPAK_NotSet), CXXMemberInliningMode() {} }; typedef IntrusiveRefCntPtr<AnalyzerOptions> AnalyzerOptionsRef; } #endif
0
repos/DirectXShaderCompiler/tools/clang/include/clang/StaticAnalyzer
repos/DirectXShaderCompiler/tools/clang/include/clang/StaticAnalyzer/Core/Checker.h
//== Checker.h - Registration mechanism for checkers -------------*- C++ -*--=// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines Checker, used to create and register checkers. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_STATICANALYZER_CORE_CHECKER_H #define LLVM_CLANG_STATICANALYZER_CORE_CHECKER_H #include "clang/Analysis/ProgramPoint.h" #include "clang/StaticAnalyzer/Core/CheckerManager.h" #include "clang/StaticAnalyzer/Core/PathSensitive/SVals.h" #include "llvm/Support/Casting.h" namespace clang { namespace ento { class BugReporter; namespace check { template <typename DECL> class ASTDecl { template <typename CHECKER> static void _checkDecl(void *checker, const Decl *D, AnalysisManager& mgr, BugReporter &BR) { ((const CHECKER *)checker)->checkASTDecl(cast<DECL>(D), mgr, BR); } static bool _handlesDecl(const Decl *D) { return isa<DECL>(D); } public: template <typename CHECKER> static void _register(CHECKER *checker, CheckerManager &mgr) { mgr._registerForDecl(CheckerManager::CheckDeclFunc(checker, _checkDecl<CHECKER>), _handlesDecl); } }; class ASTCodeBody { template <typename CHECKER> static void _checkBody(void *checker, const Decl *D, AnalysisManager& mgr, BugReporter &BR) { ((const CHECKER *)checker)->checkASTCodeBody(D, mgr, BR); } public: template <typename CHECKER> static void _register(CHECKER *checker, CheckerManager &mgr) { mgr._registerForBody(CheckerManager::CheckDeclFunc(checker, _checkBody<CHECKER>)); } }; class EndOfTranslationUnit { template <typename CHECKER> static void _checkEndOfTranslationUnit(void *checker, const TranslationUnitDecl *TU, AnalysisManager& mgr, BugReporter &BR) { ((const CHECKER *)checker)->checkEndOfTranslationUnit(TU, mgr, BR); } public: template <typename CHECKER> static void _register(CHECKER *checker, CheckerManager &mgr){ mgr._registerForEndOfTranslationUnit( CheckerManager::CheckEndOfTranslationUnit(checker, _checkEndOfTranslationUnit<CHECKER>)); } }; template <typename STMT> class PreStmt { template <typename CHECKER> static void _checkStmt(void *checker, const Stmt *S, CheckerContext &C) { ((const CHECKER *)checker)->checkPreStmt(cast<STMT>(S), C); } static bool _handlesStmt(const Stmt *S) { return isa<STMT>(S); } public: template <typename CHECKER> static void _register(CHECKER *checker, CheckerManager &mgr) { mgr._registerForPreStmt(CheckerManager::CheckStmtFunc(checker, _checkStmt<CHECKER>), _handlesStmt); } }; template <typename STMT> class PostStmt { template <typename CHECKER> static void _checkStmt(void *checker, const Stmt *S, CheckerContext &C) { ((const CHECKER *)checker)->checkPostStmt(cast<STMT>(S), C); } static bool _handlesStmt(const Stmt *S) { return isa<STMT>(S); } public: template <typename CHECKER> static void _register(CHECKER *checker, CheckerManager &mgr) { mgr._registerForPostStmt(CheckerManager::CheckStmtFunc(checker, _checkStmt<CHECKER>), _handlesStmt); } }; class PreObjCMessage { template <typename CHECKER> static void _checkObjCMessage(void *checker, const ObjCMethodCall &msg, CheckerContext &C) { ((const CHECKER *)checker)->checkPreObjCMessage(msg, C); } public: template <typename CHECKER> static void _register(CHECKER *checker, CheckerManager &mgr) { mgr._registerForPreObjCMessage( CheckerManager::CheckObjCMessageFunc(checker, _checkObjCMessage<CHECKER>)); } }; class PostObjCMessage { template <typename CHECKER> static void _checkObjCMessage(void *checker, const ObjCMethodCall &msg, CheckerContext &C) { ((const CHECKER *)checker)->checkPostObjCMessage(msg, C); } public: template <typename CHECKER> static void _register(CHECKER *checker, CheckerManager &mgr) { mgr._registerForPostObjCMessage( CheckerManager::CheckObjCMessageFunc(checker, _checkObjCMessage<CHECKER>)); } }; class PreCall { template <typename CHECKER> static void _checkCall(void *checker, const CallEvent &msg, CheckerContext &C) { ((const CHECKER *)checker)->checkPreCall(msg, C); } public: template <typename CHECKER> static void _register(CHECKER *checker, CheckerManager &mgr) { mgr._registerForPreCall( CheckerManager::CheckCallFunc(checker, _checkCall<CHECKER>)); } }; class PostCall { template <typename CHECKER> static void _checkCall(void *checker, const CallEvent &msg, CheckerContext &C) { ((const CHECKER *)checker)->checkPostCall(msg, C); } public: template <typename CHECKER> static void _register(CHECKER *checker, CheckerManager &mgr) { mgr._registerForPostCall( CheckerManager::CheckCallFunc(checker, _checkCall<CHECKER>)); } }; class Location { template <typename CHECKER> static void _checkLocation(void *checker, const SVal &location, bool isLoad, const Stmt *S, CheckerContext &C) { ((const CHECKER *)checker)->checkLocation(location, isLoad, S, C); } public: template <typename CHECKER> static void _register(CHECKER *checker, CheckerManager &mgr) { mgr._registerForLocation( CheckerManager::CheckLocationFunc(checker, _checkLocation<CHECKER>)); } }; class Bind { template <typename CHECKER> static void _checkBind(void *checker, const SVal &location, const SVal &val, const Stmt *S, CheckerContext &C) { ((const CHECKER *)checker)->checkBind(location, val, S, C); } public: template <typename CHECKER> static void _register(CHECKER *checker, CheckerManager &mgr) { mgr._registerForBind( CheckerManager::CheckBindFunc(checker, _checkBind<CHECKER>)); } }; class EndAnalysis { template <typename CHECKER> static void _checkEndAnalysis(void *checker, ExplodedGraph &G, BugReporter &BR, ExprEngine &Eng) { ((const CHECKER *)checker)->checkEndAnalysis(G, BR, Eng); } public: template <typename CHECKER> static void _register(CHECKER *checker, CheckerManager &mgr) { mgr._registerForEndAnalysis( CheckerManager::CheckEndAnalysisFunc(checker, _checkEndAnalysis<CHECKER>)); } }; class EndFunction { template <typename CHECKER> static void _checkEndFunction(void *checker, CheckerContext &C) { ((const CHECKER *)checker)->checkEndFunction(C); } public: template <typename CHECKER> static void _register(CHECKER *checker, CheckerManager &mgr) { mgr._registerForEndFunction( CheckerManager::CheckEndFunctionFunc(checker, _checkEndFunction<CHECKER>)); } }; class BranchCondition { template <typename CHECKER> static void _checkBranchCondition(void *checker, const Stmt *Condition, CheckerContext & C) { ((const CHECKER *)checker)->checkBranchCondition(Condition, C); } public: template <typename CHECKER> static void _register(CHECKER *checker, CheckerManager &mgr) { mgr._registerForBranchCondition( CheckerManager::CheckBranchConditionFunc(checker, _checkBranchCondition<CHECKER>)); } }; class LiveSymbols { template <typename CHECKER> static void _checkLiveSymbols(void *checker, ProgramStateRef state, SymbolReaper &SR) { ((const CHECKER *)checker)->checkLiveSymbols(state, SR); } public: template <typename CHECKER> static void _register(CHECKER *checker, CheckerManager &mgr) { mgr._registerForLiveSymbols( CheckerManager::CheckLiveSymbolsFunc(checker, _checkLiveSymbols<CHECKER>)); } }; class DeadSymbols { template <typename CHECKER> static void _checkDeadSymbols(void *checker, SymbolReaper &SR, CheckerContext &C) { ((const CHECKER *)checker)->checkDeadSymbols(SR, C); } public: template <typename CHECKER> static void _register(CHECKER *checker, CheckerManager &mgr) { mgr._registerForDeadSymbols( CheckerManager::CheckDeadSymbolsFunc(checker, _checkDeadSymbols<CHECKER>)); } }; class RegionChanges { template <typename CHECKER> static ProgramStateRef _checkRegionChanges(void *checker, ProgramStateRef state, const InvalidatedSymbols *invalidated, ArrayRef<const MemRegion *> Explicits, ArrayRef<const MemRegion *> Regions, const CallEvent *Call) { return ((const CHECKER *)checker)->checkRegionChanges(state, invalidated, Explicits, Regions, Call); } template <typename CHECKER> static bool _wantsRegionChangeUpdate(void *checker, ProgramStateRef state) { return ((const CHECKER *)checker)->wantsRegionChangeUpdate(state); } public: template <typename CHECKER> static void _register(CHECKER *checker, CheckerManager &mgr) { mgr._registerForRegionChanges( CheckerManager::CheckRegionChangesFunc(checker, _checkRegionChanges<CHECKER>), CheckerManager::WantsRegionChangeUpdateFunc(checker, _wantsRegionChangeUpdate<CHECKER>)); } }; class PointerEscape { template <typename CHECKER> static ProgramStateRef _checkPointerEscape(void *Checker, ProgramStateRef State, const InvalidatedSymbols &Escaped, const CallEvent *Call, PointerEscapeKind Kind, RegionAndSymbolInvalidationTraits *ETraits) { if (!ETraits) return ((const CHECKER *)Checker)->checkPointerEscape(State, Escaped, Call, Kind); InvalidatedSymbols RegularEscape; for (InvalidatedSymbols::const_iterator I = Escaped.begin(), E = Escaped.end(); I != E; ++I) if (!ETraits->hasTrait(*I, RegionAndSymbolInvalidationTraits::TK_PreserveContents) && !ETraits->hasTrait(*I, RegionAndSymbolInvalidationTraits::TK_SuppressEscape)) RegularEscape.insert(*I); if (RegularEscape.empty()) return State; return ((const CHECKER *)Checker)->checkPointerEscape(State, RegularEscape, Call, Kind); } public: template <typename CHECKER> static void _register(CHECKER *checker, CheckerManager &mgr) { mgr._registerForPointerEscape( CheckerManager::CheckPointerEscapeFunc(checker, _checkPointerEscape<CHECKER>)); } }; class ConstPointerEscape { template <typename CHECKER> static ProgramStateRef _checkConstPointerEscape(void *Checker, ProgramStateRef State, const InvalidatedSymbols &Escaped, const CallEvent *Call, PointerEscapeKind Kind, RegionAndSymbolInvalidationTraits *ETraits) { if (!ETraits) return State; InvalidatedSymbols ConstEscape; for (InvalidatedSymbols::const_iterator I = Escaped.begin(), E = Escaped.end(); I != E; ++I) if (ETraits->hasTrait(*I, RegionAndSymbolInvalidationTraits::TK_PreserveContents) && !ETraits->hasTrait(*I, RegionAndSymbolInvalidationTraits::TK_SuppressEscape)) ConstEscape.insert(*I); if (ConstEscape.empty()) return State; return ((const CHECKER *)Checker)->checkConstPointerEscape(State, ConstEscape, Call, Kind); } public: template <typename CHECKER> static void _register(CHECKER *checker, CheckerManager &mgr) { mgr._registerForPointerEscape( CheckerManager::CheckPointerEscapeFunc(checker, _checkConstPointerEscape<CHECKER>)); } }; template <typename EVENT> class Event { template <typename CHECKER> static void _checkEvent(void *checker, const void *event) { ((const CHECKER *)checker)->checkEvent(*(const EVENT *)event); } public: template <typename CHECKER> static void _register(CHECKER *checker, CheckerManager &mgr) { mgr._registerListenerForEvent<EVENT>( CheckerManager::CheckEventFunc(checker, _checkEvent<CHECKER>)); } }; } // end check namespace namespace eval { class Assume { template <typename CHECKER> static ProgramStateRef _evalAssume(void *checker, ProgramStateRef state, const SVal &cond, bool assumption) { return ((const CHECKER *)checker)->evalAssume(state, cond, assumption); } public: template <typename CHECKER> static void _register(CHECKER *checker, CheckerManager &mgr) { mgr._registerForEvalAssume( CheckerManager::EvalAssumeFunc(checker, _evalAssume<CHECKER>)); } }; class Call { template <typename CHECKER> static bool _evalCall(void *checker, const CallExpr *CE, CheckerContext &C) { return ((const CHECKER *)checker)->evalCall(CE, C); } public: template <typename CHECKER> static void _register(CHECKER *checker, CheckerManager &mgr) { mgr._registerForEvalCall( CheckerManager::EvalCallFunc(checker, _evalCall<CHECKER>)); } }; } // end eval namespace class CheckerBase : public ProgramPointTag { CheckName Name; friend class ::clang::ento::CheckerManager; public: StringRef getTagDescription() const override; CheckName getCheckName() const; /// See CheckerManager::runCheckersForPrintState. virtual void printState(raw_ostream &Out, ProgramStateRef State, const char *NL, const char *Sep) const { } }; /// Dump checker name to stream. raw_ostream& operator<<(raw_ostream &Out, const CheckerBase &Checker); /// Tag that can use a checker name as a message provider /// (see SimpleProgramPointTag). class CheckerProgramPointTag : public SimpleProgramPointTag { public: CheckerProgramPointTag(StringRef CheckerName, StringRef Msg); CheckerProgramPointTag(const CheckerBase *Checker, StringRef Msg); }; template <typename CHECK1, typename... CHECKs> class Checker : public CHECK1, public CHECKs..., public CheckerBase { public: template <typename CHECKER> static void _register(CHECKER *checker, CheckerManager &mgr) { CHECK1::_register(checker, mgr); Checker<CHECKs...>::_register(checker, mgr); } }; template <typename CHECK1> class Checker<CHECK1> : public CHECK1, public CheckerBase { public: template <typename CHECKER> static void _register(CHECKER *checker, CheckerManager &mgr) { CHECK1::_register(checker, mgr); } }; template <typename EVENT> class EventDispatcher { CheckerManager *Mgr; public: EventDispatcher() : Mgr(nullptr) { } template <typename CHECKER> static void _register(CHECKER *checker, CheckerManager &mgr) { mgr._registerDispatcherForEvent<EVENT>(); static_cast<EventDispatcher<EVENT> *>(checker)->Mgr = &mgr; } void dispatchEvent(const EVENT &event) const { Mgr->_dispatchEvent(event); } }; /// \brief We dereferenced a location that may be null. struct ImplicitNullDerefEvent { SVal Location; bool IsLoad; ExplodedNode *SinkNode; BugReporter *BR; }; /// \brief A helper class which wraps a boolean value set to false by default. /// /// This class should behave exactly like 'bool' except that it doesn't need to /// be explicitly initialized. struct DefaultBool { bool val; DefaultBool() : val(false) {} /*implicit*/ operator bool&() { return val; } /*implicit*/ operator const bool&() const { return val; } DefaultBool &operator=(bool b) { val = b; return *this; } }; } // end ento namespace } // end clang namespace #endif
0
repos/DirectXShaderCompiler/tools/clang/include/clang/StaticAnalyzer
repos/DirectXShaderCompiler/tools/clang/include/clang/StaticAnalyzer/Core/PathDiagnosticConsumers.h
//===--- PathDiagnosticClients.h - Path Diagnostic Clients ------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines the interface to create different path diagostic clients. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_STATICANALYZER_CORE_PATHDIAGNOSTICCONSUMERS_H #define LLVM_CLANG_STATICANALYZER_CORE_PATHDIAGNOSTICCONSUMERS_H #include <string> #include <vector> namespace clang { class AnalyzerOptions; class Preprocessor; namespace ento { class PathDiagnosticConsumer; typedef std::vector<PathDiagnosticConsumer*> PathDiagnosticConsumers; #define ANALYSIS_DIAGNOSTICS(NAME, CMDFLAG, DESC, CREATEFN)\ void CREATEFN(AnalyzerOptions &AnalyzerOpts,\ PathDiagnosticConsumers &C,\ const std::string &Prefix,\ const Preprocessor &PP); #include "clang/StaticAnalyzer/Core/Analyses.def" } // end 'ento' namespace } // end 'clang' namespace #endif
0
repos/DirectXShaderCompiler/tools/clang/include/clang/StaticAnalyzer
repos/DirectXShaderCompiler/tools/clang/include/clang/StaticAnalyzer/Core/CheckerOptInfo.h
//===--- CheckerOptInfo.h - Specifies which checkers to use -----*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_STATICANALYZER_CORE_CHECKEROPTINFO_H #define LLVM_CLANG_STATICANALYZER_CORE_CHECKEROPTINFO_H #include "clang/Basic/LLVM.h" #include "llvm/ADT/StringRef.h" namespace clang { namespace ento { /// Represents a request to include or exclude a checker or package from a /// specific analysis run. /// /// \sa CheckerRegistry::initializeManager class CheckerOptInfo { StringRef Name; bool Enable; bool Claimed; public: CheckerOptInfo(StringRef name, bool enable) : Name(name), Enable(enable), Claimed(false) { } StringRef getName() const { return Name; } bool isEnabled() const { return Enable; } bool isDisabled() const { return !isEnabled(); } bool isClaimed() const { return Claimed; } bool isUnclaimed() const { return !isClaimed(); } void claim() { Claimed = true; } }; } // end namespace ento } // end namespace clang #endif
0
repos/DirectXShaderCompiler/tools/clang/include/clang/StaticAnalyzer
repos/DirectXShaderCompiler/tools/clang/include/clang/StaticAnalyzer/Core/CheckerManager.h
//===--- CheckerManager.h - Static Analyzer Checker Manager -----*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // Defines the Static Analyzer Checker Manager. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_STATICANALYZER_CORE_CHECKERMANAGER_H #define LLVM_CLANG_STATICANALYZER_CORE_CHECKERMANAGER_H #include "clang/Analysis/ProgramPoint.h" #include "clang/Basic/LangOptions.h" #include "clang/StaticAnalyzer/Core/AnalyzerOptions.h" #include "clang/StaticAnalyzer/Core/PathSensitive/Store.h" #include "llvm/ADT/DenseMap.h" #include "llvm/ADT/SmallVector.h" #include <vector> namespace clang { class Decl; class Stmt; class CallExpr; namespace ento { class CheckerBase; class CheckerRegistry; class ExprEngine; class AnalysisManager; class BugReporter; class CheckerContext; class ObjCMethodCall; class SVal; class ExplodedNode; class ExplodedNodeSet; class ExplodedGraph; class ProgramState; class NodeBuilder; struct NodeBuilderContext; class MemRegion; class SymbolReaper; template <typename T> class CheckerFn; template <typename RET, typename... Ps> class CheckerFn<RET(Ps...)> { typedef RET (*Func)(void *, Ps...); Func Fn; public: CheckerBase *Checker; CheckerFn(CheckerBase *checker, Func fn) : Fn(fn), Checker(checker) { } RET operator()(Ps... ps) const { return Fn(Checker, ps...); } }; /// \brief Describes the different reasons a pointer escapes /// during analysis. enum PointerEscapeKind { /// A pointer escapes due to binding its value to a location /// that the analyzer cannot track. PSK_EscapeOnBind, /// The pointer has been passed to a function call directly. PSK_DirectEscapeOnCall, /// The pointer has been passed to a function indirectly. /// For example, the pointer is accessible through an /// argument to a function. PSK_IndirectEscapeOnCall, /// The reason for pointer escape is unknown. For example, /// a region containing this pointer is invalidated. PSK_EscapeOther }; // This wrapper is used to ensure that only StringRefs originating from the // CheckerRegistry are used as check names. We want to make sure all check // name strings have a lifetime that keeps them alive at least until the path // diagnostics have been processed. class CheckName { StringRef Name; friend class ::clang::ento::CheckerRegistry; explicit CheckName(StringRef Name) : Name(Name) {} public: CheckName() {} CheckName(const CheckName &Other) : Name(Other.Name) {} StringRef getName() const { return Name; } }; class CheckerManager { const LangOptions LangOpts; AnalyzerOptionsRef AOptions; CheckName CurrentCheckName; public: CheckerManager(const LangOptions &langOpts, AnalyzerOptionsRef AOptions) : LangOpts(langOpts), AOptions(AOptions) {} ~CheckerManager(); void setCurrentCheckName(CheckName name) { CurrentCheckName = name; } CheckName getCurrentCheckName() const { return CurrentCheckName; } bool hasPathSensitiveCheckers() const; void finishedCheckerRegistration(); const LangOptions &getLangOpts() const { return LangOpts; } AnalyzerOptions &getAnalyzerOptions() { return *AOptions; } typedef CheckerBase *CheckerRef; typedef const void *CheckerTag; typedef CheckerFn<void ()> CheckerDtor; //===----------------------------------------------------------------------===// // registerChecker //===----------------------------------------------------------------------===// /// \brief Used to register checkers. /// /// \returns a pointer to the checker object. template <typename CHECKER> CHECKER *registerChecker() { CheckerTag tag = getTag<CHECKER>(); CheckerRef &ref = CheckerTags[tag]; if (ref) return static_cast<CHECKER *>(ref); // already registered. CHECKER *checker = new CHECKER(); checker->Name = CurrentCheckName; CheckerDtors.push_back(CheckerDtor(checker, destruct<CHECKER>)); CHECKER::_register(checker, *this); ref = checker; return checker; } template <typename CHECKER> CHECKER *registerChecker(AnalyzerOptions &AOpts) { CheckerTag tag = getTag<CHECKER>(); CheckerRef &ref = CheckerTags[tag]; if (ref) return static_cast<CHECKER *>(ref); // already registered. CHECKER *checker = new CHECKER(AOpts); checker->Name = CurrentCheckName; CheckerDtors.push_back(CheckerDtor(checker, destruct<CHECKER>)); CHECKER::_register(checker, *this); ref = checker; return checker; } //===----------------------------------------------------------------------===// // Functions for running checkers for AST traversing.. //===----------------------------------------------------------------------===// /// \brief Run checkers handling Decls. void runCheckersOnASTDecl(const Decl *D, AnalysisManager& mgr, BugReporter &BR); /// \brief Run checkers handling Decls containing a Stmt body. void runCheckersOnASTBody(const Decl *D, AnalysisManager& mgr, BugReporter &BR); //===----------------------------------------------------------------------===// // Functions for running checkers for path-sensitive checking. //===----------------------------------------------------------------------===// /// \brief Run checkers for pre-visiting Stmts. /// /// The notification is performed for every explored CFGElement, which does /// not include the control flow statements such as IfStmt. /// /// \sa runCheckersForBranchCondition, runCheckersForPostStmt void runCheckersForPreStmt(ExplodedNodeSet &Dst, const ExplodedNodeSet &Src, const Stmt *S, ExprEngine &Eng) { runCheckersForStmt(/*isPreVisit=*/true, Dst, Src, S, Eng); } /// \brief Run checkers for post-visiting Stmts. /// /// The notification is performed for every explored CFGElement, which does /// not include the control flow statements such as IfStmt. /// /// \sa runCheckersForBranchCondition, runCheckersForPreStmt void runCheckersForPostStmt(ExplodedNodeSet &Dst, const ExplodedNodeSet &Src, const Stmt *S, ExprEngine &Eng, bool wasInlined = false) { runCheckersForStmt(/*isPreVisit=*/false, Dst, Src, S, Eng, wasInlined); } /// \brief Run checkers for visiting Stmts. void runCheckersForStmt(bool isPreVisit, ExplodedNodeSet &Dst, const ExplodedNodeSet &Src, const Stmt *S, ExprEngine &Eng, bool wasInlined = false); /// \brief Run checkers for pre-visiting obj-c messages. void runCheckersForPreObjCMessage(ExplodedNodeSet &Dst, const ExplodedNodeSet &Src, const ObjCMethodCall &msg, ExprEngine &Eng) { runCheckersForObjCMessage(/*isPreVisit=*/true, Dst, Src, msg, Eng); } /// \brief Run checkers for post-visiting obj-c messages. void runCheckersForPostObjCMessage(ExplodedNodeSet &Dst, const ExplodedNodeSet &Src, const ObjCMethodCall &msg, ExprEngine &Eng, bool wasInlined = false) { runCheckersForObjCMessage(/*isPreVisit=*/false, Dst, Src, msg, Eng, wasInlined); } /// \brief Run checkers for visiting obj-c messages. void runCheckersForObjCMessage(bool isPreVisit, ExplodedNodeSet &Dst, const ExplodedNodeSet &Src, const ObjCMethodCall &msg, ExprEngine &Eng, bool wasInlined = false); /// \brief Run checkers for pre-visiting obj-c messages. void runCheckersForPreCall(ExplodedNodeSet &Dst, const ExplodedNodeSet &Src, const CallEvent &Call, ExprEngine &Eng) { runCheckersForCallEvent(/*isPreVisit=*/true, Dst, Src, Call, Eng); } /// \brief Run checkers for post-visiting obj-c messages. void runCheckersForPostCall(ExplodedNodeSet &Dst, const ExplodedNodeSet &Src, const CallEvent &Call, ExprEngine &Eng, bool wasInlined = false) { runCheckersForCallEvent(/*isPreVisit=*/false, Dst, Src, Call, Eng, wasInlined); } /// \brief Run checkers for visiting obj-c messages. void runCheckersForCallEvent(bool isPreVisit, ExplodedNodeSet &Dst, const ExplodedNodeSet &Src, const CallEvent &Call, ExprEngine &Eng, bool wasInlined = false); /// \brief Run checkers for load/store of a location. void runCheckersForLocation(ExplodedNodeSet &Dst, const ExplodedNodeSet &Src, SVal location, bool isLoad, const Stmt *NodeEx, const Stmt *BoundEx, ExprEngine &Eng); /// \brief Run checkers for binding of a value to a location. void runCheckersForBind(ExplodedNodeSet &Dst, const ExplodedNodeSet &Src, SVal location, SVal val, const Stmt *S, ExprEngine &Eng, const ProgramPoint &PP); /// \brief Run checkers for end of analysis. void runCheckersForEndAnalysis(ExplodedGraph &G, BugReporter &BR, ExprEngine &Eng); /// \brief Run checkers on end of function. void runCheckersForEndFunction(NodeBuilderContext &BC, ExplodedNodeSet &Dst, ExplodedNode *Pred, ExprEngine &Eng); /// \brief Run checkers for branch condition. void runCheckersForBranchCondition(const Stmt *condition, ExplodedNodeSet &Dst, ExplodedNode *Pred, ExprEngine &Eng); /// \brief Run checkers for live symbols. /// /// Allows modifying SymbolReaper object. For example, checkers can explicitly /// register symbols of interest as live. These symbols will not be marked /// dead and removed. void runCheckersForLiveSymbols(ProgramStateRef state, SymbolReaper &SymReaper); /// \brief Run checkers for dead symbols. /// /// Notifies checkers when symbols become dead. For example, this allows /// checkers to aggressively clean up/reduce the checker state and produce /// precise diagnostics. void runCheckersForDeadSymbols(ExplodedNodeSet &Dst, const ExplodedNodeSet &Src, SymbolReaper &SymReaper, const Stmt *S, ExprEngine &Eng, ProgramPoint::Kind K); /// \brief True if at least one checker wants to check region changes. bool wantsRegionChangeUpdate(ProgramStateRef state); /// \brief Run checkers for region changes. /// /// This corresponds to the check::RegionChanges callback. /// \param state The current program state. /// \param invalidated A set of all symbols potentially touched by the change. /// \param ExplicitRegions The regions explicitly requested for invalidation. /// For example, in the case of a function call, these would be arguments. /// \param Regions The transitive closure of accessible regions, /// i.e. all regions that may have been touched by this change. /// \param Call The call expression wrapper if the regions are invalidated /// by a call. ProgramStateRef runCheckersForRegionChanges(ProgramStateRef state, const InvalidatedSymbols *invalidated, ArrayRef<const MemRegion *> ExplicitRegions, ArrayRef<const MemRegion *> Regions, const CallEvent *Call); /// \brief Run checkers when pointers escape. /// /// This notifies the checkers about pointer escape, which occurs whenever /// the analyzer cannot track the symbol any more. For example, as a /// result of assigning a pointer into a global or when it's passed to a /// function call the analyzer cannot model. /// /// \param State The state at the point of escape. /// \param Escaped The list of escaped symbols. /// \param Call The corresponding CallEvent, if the symbols escape as /// parameters to the given call. /// \param Kind The reason of pointer escape. /// \param ITraits Information about invalidation for a particular /// region/symbol. /// \returns Checkers can modify the state by returning a new one. ProgramStateRef runCheckersForPointerEscape(ProgramStateRef State, const InvalidatedSymbols &Escaped, const CallEvent *Call, PointerEscapeKind Kind, RegionAndSymbolInvalidationTraits *ITraits); /// \brief Run checkers for handling assumptions on symbolic values. ProgramStateRef runCheckersForEvalAssume(ProgramStateRef state, SVal Cond, bool Assumption); /// \brief Run checkers for evaluating a call. /// /// Warning: Currently, the CallEvent MUST come from a CallExpr! void runCheckersForEvalCall(ExplodedNodeSet &Dst, const ExplodedNodeSet &Src, const CallEvent &CE, ExprEngine &Eng); /// \brief Run checkers for the entire Translation Unit. void runCheckersOnEndOfTranslationUnit(const TranslationUnitDecl *TU, AnalysisManager &mgr, BugReporter &BR); /// \brief Run checkers for debug-printing a ProgramState. /// /// Unlike most other callbacks, any checker can simply implement the virtual /// method CheckerBase::printState if it has custom data to print. /// \param Out The output stream /// \param State The state being printed /// \param NL The preferred representation of a newline. /// \param Sep The preferred separator between different kinds of data. void runCheckersForPrintState(raw_ostream &Out, ProgramStateRef State, const char *NL, const char *Sep); //===----------------------------------------------------------------------===// // Internal registration functions for AST traversing. //===----------------------------------------------------------------------===// // Functions used by the registration mechanism, checkers should not touch // these directly. typedef CheckerFn<void (const Decl *, AnalysisManager&, BugReporter &)> CheckDeclFunc; typedef bool (*HandlesDeclFunc)(const Decl *D); void _registerForDecl(CheckDeclFunc checkfn, HandlesDeclFunc isForDeclFn); void _registerForBody(CheckDeclFunc checkfn); //===----------------------------------------------------------------------===// // Internal registration functions for path-sensitive checking. //===----------------------------------------------------------------------===// typedef CheckerFn<void (const Stmt *, CheckerContext &)> CheckStmtFunc; typedef CheckerFn<void (const ObjCMethodCall &, CheckerContext &)> CheckObjCMessageFunc; typedef CheckerFn<void (const CallEvent &, CheckerContext &)> CheckCallFunc; typedef CheckerFn<void (const SVal &location, bool isLoad, const Stmt *S, CheckerContext &)> CheckLocationFunc; typedef CheckerFn<void (const SVal &location, const SVal &val, const Stmt *S, CheckerContext &)> CheckBindFunc; typedef CheckerFn<void (ExplodedGraph &, BugReporter &, ExprEngine &)> CheckEndAnalysisFunc; typedef CheckerFn<void (CheckerContext &)> CheckEndFunctionFunc; typedef CheckerFn<void (const Stmt *, CheckerContext &)> CheckBranchConditionFunc; typedef CheckerFn<void (SymbolReaper &, CheckerContext &)> CheckDeadSymbolsFunc; typedef CheckerFn<void (ProgramStateRef,SymbolReaper &)> CheckLiveSymbolsFunc; typedef CheckerFn<ProgramStateRef (ProgramStateRef, const InvalidatedSymbols *symbols, ArrayRef<const MemRegion *> ExplicitRegions, ArrayRef<const MemRegion *> Regions, const CallEvent *Call)> CheckRegionChangesFunc; typedef CheckerFn<bool (ProgramStateRef)> WantsRegionChangeUpdateFunc; typedef CheckerFn<ProgramStateRef (ProgramStateRef, const InvalidatedSymbols &Escaped, const CallEvent *Call, PointerEscapeKind Kind, RegionAndSymbolInvalidationTraits *ITraits)> CheckPointerEscapeFunc; typedef CheckerFn<ProgramStateRef (ProgramStateRef, const SVal &cond, bool assumption)> EvalAssumeFunc; typedef CheckerFn<bool (const CallExpr *, CheckerContext &)> EvalCallFunc; typedef CheckerFn<void (const TranslationUnitDecl *, AnalysisManager&, BugReporter &)> CheckEndOfTranslationUnit; typedef bool (*HandlesStmtFunc)(const Stmt *D); void _registerForPreStmt(CheckStmtFunc checkfn, HandlesStmtFunc isForStmtFn); void _registerForPostStmt(CheckStmtFunc checkfn, HandlesStmtFunc isForStmtFn); void _registerForPreObjCMessage(CheckObjCMessageFunc checkfn); void _registerForPostObjCMessage(CheckObjCMessageFunc checkfn); void _registerForPreCall(CheckCallFunc checkfn); void _registerForPostCall(CheckCallFunc checkfn); void _registerForLocation(CheckLocationFunc checkfn); void _registerForBind(CheckBindFunc checkfn); void _registerForEndAnalysis(CheckEndAnalysisFunc checkfn); void _registerForEndFunction(CheckEndFunctionFunc checkfn); void _registerForBranchCondition(CheckBranchConditionFunc checkfn); void _registerForLiveSymbols(CheckLiveSymbolsFunc checkfn); void _registerForDeadSymbols(CheckDeadSymbolsFunc checkfn); void _registerForRegionChanges(CheckRegionChangesFunc checkfn, WantsRegionChangeUpdateFunc wantUpdateFn); void _registerForPointerEscape(CheckPointerEscapeFunc checkfn); void _registerForConstPointerEscape(CheckPointerEscapeFunc checkfn); void _registerForEvalAssume(EvalAssumeFunc checkfn); void _registerForEvalCall(EvalCallFunc checkfn); void _registerForEndOfTranslationUnit(CheckEndOfTranslationUnit checkfn); //===----------------------------------------------------------------------===// // Internal registration functions for events. //===----------------------------------------------------------------------===// typedef void *EventTag; typedef CheckerFn<void (const void *event)> CheckEventFunc; template <typename EVENT> void _registerListenerForEvent(CheckEventFunc checkfn) { EventInfo &info = Events[getTag<EVENT>()]; info.Checkers.push_back(checkfn); } template <typename EVENT> void _registerDispatcherForEvent() { EventInfo &info = Events[getTag<EVENT>()]; info.HasDispatcher = true; } template <typename EVENT> void _dispatchEvent(const EVENT &event) const { EventsTy::const_iterator I = Events.find(getTag<EVENT>()); if (I == Events.end()) return; const EventInfo &info = I->second; for (unsigned i = 0, e = info.Checkers.size(); i != e; ++i) info.Checkers[i](&event); } //===----------------------------------------------------------------------===// // Implementation details. // // /////////////////////////////////////////////////////////////////////////////// private: template <typename CHECKER> static void destruct(void *obj) { delete static_cast<CHECKER *>(obj); } template <typename T> static void *getTag() { static int tag; return &tag; } llvm::DenseMap<CheckerTag, CheckerRef> CheckerTags; std::vector<CheckerDtor> CheckerDtors; struct DeclCheckerInfo { CheckDeclFunc CheckFn; HandlesDeclFunc IsForDeclFn; }; std::vector<DeclCheckerInfo> DeclCheckers; std::vector<CheckDeclFunc> BodyCheckers; typedef SmallVector<CheckDeclFunc, 4> CachedDeclCheckers; typedef llvm::DenseMap<unsigned, CachedDeclCheckers> CachedDeclCheckersMapTy; CachedDeclCheckersMapTy CachedDeclCheckersMap; struct StmtCheckerInfo { CheckStmtFunc CheckFn; HandlesStmtFunc IsForStmtFn; bool IsPreVisit; }; std::vector<StmtCheckerInfo> StmtCheckers; typedef SmallVector<CheckStmtFunc, 4> CachedStmtCheckers; typedef llvm::DenseMap<unsigned, CachedStmtCheckers> CachedStmtCheckersMapTy; CachedStmtCheckersMapTy CachedStmtCheckersMap; const CachedStmtCheckers &getCachedStmtCheckersFor(const Stmt *S, bool isPreVisit); std::vector<CheckObjCMessageFunc> PreObjCMessageCheckers; std::vector<CheckObjCMessageFunc> PostObjCMessageCheckers; std::vector<CheckCallFunc> PreCallCheckers; std::vector<CheckCallFunc> PostCallCheckers; std::vector<CheckLocationFunc> LocationCheckers; std::vector<CheckBindFunc> BindCheckers; std::vector<CheckEndAnalysisFunc> EndAnalysisCheckers; std::vector<CheckEndFunctionFunc> EndFunctionCheckers; std::vector<CheckBranchConditionFunc> BranchConditionCheckers; std::vector<CheckLiveSymbolsFunc> LiveSymbolsCheckers; std::vector<CheckDeadSymbolsFunc> DeadSymbolsCheckers; struct RegionChangesCheckerInfo { CheckRegionChangesFunc CheckFn; WantsRegionChangeUpdateFunc WantUpdateFn; }; std::vector<RegionChangesCheckerInfo> RegionChangesCheckers; std::vector<CheckPointerEscapeFunc> PointerEscapeCheckers; std::vector<EvalAssumeFunc> EvalAssumeCheckers; std::vector<EvalCallFunc> EvalCallCheckers; std::vector<CheckEndOfTranslationUnit> EndOfTranslationUnitCheckers; struct EventInfo { SmallVector<CheckEventFunc, 4> Checkers; bool HasDispatcher; EventInfo() : HasDispatcher(false) { } }; typedef llvm::DenseMap<EventTag, EventInfo> EventsTy; EventsTy Events; }; } // end ento namespace } // end clang namespace #endif
0
repos/DirectXShaderCompiler/tools/clang/include/clang/StaticAnalyzer
repos/DirectXShaderCompiler/tools/clang/include/clang/StaticAnalyzer/Core/CheckerRegistry.h
//===--- CheckerRegistry.h - Maintains all available checkers ---*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_STATICANALYZER_CORE_CHECKERREGISTRY_H #define LLVM_CLANG_STATICANALYZER_CORE_CHECKERREGISTRY_H #include "clang/Basic/LLVM.h" #include "clang/StaticAnalyzer/Core/CheckerManager.h" #include <vector> // FIXME: move this information to an HTML file in docs/. // At the very least, a checker plugin is a dynamic library that exports // clang_analyzerAPIVersionString. This should be defined as follows: // // extern "C" // const char clang_analyzerAPIVersionString[] = // CLANG_ANALYZER_API_VERSION_STRING; // // This is used to check whether the current version of the analyzer is known to // be incompatible with a plugin. Plugins with incompatible version strings, // or without a version string at all, will not be loaded. // // To add a custom checker to the analyzer, the plugin must also define the // function clang_registerCheckers. For example: // // extern "C" // void clang_registerCheckers (CheckerRegistry &registry) { // registry.addChecker<MainCallChecker>("example.MainCallChecker", // "Disallows calls to functions called main"); // } // // The first method argument is the full name of the checker, including its // enclosing package. By convention, the registered name of a checker is the // name of the associated class (the template argument). // The second method argument is a short human-readable description of the // checker. // // The clang_registerCheckers function may add any number of checkers to the // registry. If any checkers require additional initialization, use the three- // argument form of CheckerRegistry::addChecker. // // To load a checker plugin, specify the full path to the dynamic library as // the argument to the -load option in the cc1 frontend. You can then enable // your custom checker using the -analyzer-checker: // // clang -cc1 -load </path/to/plugin.dylib> -analyze // -analyzer-checker=<example.MainCallChecker> // // For a complete working example, see examples/analyzer-plugin. #ifndef CLANG_ANALYZER_API_VERSION_STRING // FIXME: The Clang version string is not particularly granular; // the analyzer infrastructure can change a lot between releases. // Unfortunately, this string has to be statically embedded in each plugin, // so we can't just use the functions defined in Version.h. #include "clang/Basic/Version.h" #define CLANG_ANALYZER_API_VERSION_STRING CLANG_VERSION_STRING #endif namespace clang { class DiagnosticsEngine; class AnalyzerOptions; namespace ento { class CheckerOptInfo; /// Manages a set of available checkers for running a static analysis. /// The checkers are organized into packages by full name, where including /// a package will recursively include all subpackages and checkers within it. /// For example, the checker "core.builtin.NoReturnFunctionChecker" will be /// included if initializeManager() is called with an option of "core", /// "core.builtin", or the full name "core.builtin.NoReturnFunctionChecker". class CheckerRegistry { public: /// Initialization functions perform any necessary setup for a checker. /// They should include a call to CheckerManager::registerChecker. typedef void (*InitializationFunction)(CheckerManager &); struct CheckerInfo { InitializationFunction Initialize; StringRef FullName; StringRef Desc; CheckerInfo(InitializationFunction fn, StringRef name, StringRef desc) : Initialize(fn), FullName(name), Desc(desc) {} }; typedef std::vector<CheckerInfo> CheckerInfoList; private: template <typename T> static void initializeManager(CheckerManager &mgr) { mgr.registerChecker<T>(); } public: /// Adds a checker to the registry. Use this non-templated overload when your /// checker requires custom initialization. void addChecker(InitializationFunction fn, StringRef fullName, StringRef desc); /// Adds a checker to the registry. Use this templated overload when your /// checker does not require any custom initialization. template <class T> void addChecker(StringRef fullName, StringRef desc) { // Avoid MSVC's Compiler Error C2276: // http://msdn.microsoft.com/en-us/library/850cstw1(v=VS.80).aspx addChecker(&CheckerRegistry::initializeManager<T>, fullName, desc); } /// Initializes a CheckerManager by calling the initialization functions for /// all checkers specified by the given CheckerOptInfo list. The order of this /// list is significant; later options can be used to reverse earlier ones. /// This can be used to exclude certain checkers in an included package. void initializeManager(CheckerManager &mgr, SmallVectorImpl<CheckerOptInfo> &opts) const; /// Check if every option corresponds to a specific checker or package. void validateCheckerOptions(const AnalyzerOptions &opts, DiagnosticsEngine &diags) const; /// Prints the name and description of all checkers in this registry. /// This output is not intended to be machine-parseable. void printHelp(raw_ostream &out, size_t maxNameChars = 30) const ; private: mutable CheckerInfoList Checkers; mutable llvm::StringMap<size_t> Packages; }; } // end namespace ento } // end namespace clang #endif
0
repos/DirectXShaderCompiler/tools/clang/include/clang/StaticAnalyzer
repos/DirectXShaderCompiler/tools/clang/include/clang/StaticAnalyzer/Core/Analyses.def
//===-- Analyses.def - Metadata about Static Analyses -----------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines the set of static analyses used by AnalysisConsumer. // //===----------------------------------------------------------------------===// #ifndef ANALYSIS_STORE #define ANALYSIS_STORE(NAME, CMDFLAG, DESC, CREATFN) #endif ANALYSIS_STORE(RegionStore, "region", "Use region-based analyzer store", CreateRegionStoreManager) #ifndef ANALYSIS_CONSTRAINTS #define ANALYSIS_CONSTRAINTS(NAME, CMDFLAG, DESC, CREATFN) #endif ANALYSIS_CONSTRAINTS(RangeConstraints, "range", "Use constraint tracking of concrete value ranges", CreateRangeConstraintManager) #ifndef ANALYSIS_DIAGNOSTICS #define ANALYSIS_DIAGNOSTICS(NAME, CMDFLAG, DESC, CREATEFN) #endif ANALYSIS_DIAGNOSTICS(HTML, "html", "Output analysis results using HTML", createHTMLDiagnosticConsumer) ANALYSIS_DIAGNOSTICS(PLIST, "plist", "Output analysis results using Plists", createPlistDiagnosticConsumer) ANALYSIS_DIAGNOSTICS(PLIST_MULTI_FILE, "plist-multi-file", "Output analysis results using Plists (allowing for mult-file bugs)", createPlistMultiFileDiagnosticConsumer) ANALYSIS_DIAGNOSTICS(PLIST_HTML, "plist-html", "Output analysis results using HTML wrapped with Plists", createPlistHTMLDiagnosticConsumer) ANALYSIS_DIAGNOSTICS(TEXT, "text", "Text output of analysis results", createTextPathDiagnosticConsumer) #ifndef ANALYSIS_PURGE #define ANALYSIS_PURGE(NAME, CMDFLAG, DESC) #endif ANALYSIS_PURGE(PurgeStmt, "statement", "Purge symbols, bindings, and constraints before every statement") ANALYSIS_PURGE(PurgeBlock, "block", "Purge symbols, bindings, and constraints before every basic block") ANALYSIS_PURGE(PurgeNone, "none", "Do not purge symbols, bindings, or constraints") #ifndef ANALYSIS_INLINING_MODE #define ANALYSIS_INLINING_MODE(NAME, CMDFLAG, DESC) #endif ANALYSIS_INLINING_MODE(All, "all", "Analyze all functions as top level") ANALYSIS_INLINING_MODE(NoRedundancy, "noredundancy", "Do not analyze a function which has been previously inlined") #undef ANALYSIS_STORE #undef ANALYSIS_CONSTRAINTS #undef ANALYSIS_DIAGNOSTICS #undef ANALYSIS_PURGE #undef ANALYSIS_INLINING_MODE #undef ANALYSIS_IPA
0
repos/DirectXShaderCompiler/tools/clang/include/clang/StaticAnalyzer/Core
repos/DirectXShaderCompiler/tools/clang/include/clang/StaticAnalyzer/Core/PathSensitive/Environment.h
//== Environment.h - Map from Stmt* to Locations/Values ---------*- C++ -*--==// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defined the Environment and EnvironmentManager classes. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_ENVIRONMENT_H #define LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_ENVIRONMENT_H #include "clang/Analysis/AnalysisContext.h" #include "clang/StaticAnalyzer/Core/PathSensitive/SVals.h" #include "llvm/ADT/ImmutableMap.h" namespace clang { class LiveVariables; namespace ento { class EnvironmentManager; class SValBuilder; /// An entry in the environment consists of a Stmt and an LocationContext. /// This allows the environment to manage context-sensitive bindings, /// which is essentially for modeling recursive function analysis, among /// other things. class EnvironmentEntry : public std::pair<const Stmt*, const StackFrameContext *> { public: EnvironmentEntry(const Stmt *s, const LocationContext *L); const Stmt *getStmt() const { return first; } const LocationContext *getLocationContext() const { return second; } /// Profile an EnvironmentEntry for inclusion in a FoldingSet. static void Profile(llvm::FoldingSetNodeID &ID, const EnvironmentEntry &E) { ID.AddPointer(E.getStmt()); ID.AddPointer(E.getLocationContext()); } void Profile(llvm::FoldingSetNodeID &ID) const { Profile(ID, *this); } }; /// An immutable map from EnvironemntEntries to SVals. class Environment { private: friend class EnvironmentManager; // Type definitions. typedef llvm::ImmutableMap<EnvironmentEntry, SVal> BindingsTy; // Data. BindingsTy ExprBindings; Environment(BindingsTy eb) : ExprBindings(eb) {} SVal lookupExpr(const EnvironmentEntry &E) const; public: typedef BindingsTy::iterator iterator; iterator begin() const { return ExprBindings.begin(); } iterator end() const { return ExprBindings.end(); } /// Fetches the current binding of the expression in the /// Environment. SVal getSVal(const EnvironmentEntry &E, SValBuilder &svalBuilder) const; /// Profile - Profile the contents of an Environment object for use /// in a FoldingSet. static void Profile(llvm::FoldingSetNodeID& ID, const Environment* env) { env->ExprBindings.Profile(ID); } /// Profile - Used to profile the contents of this object for inclusion /// in a FoldingSet. void Profile(llvm::FoldingSetNodeID& ID) const { Profile(ID, this); } bool operator==(const Environment& RHS) const { return ExprBindings == RHS.ExprBindings; } void print(raw_ostream &Out, const char *NL, const char *Sep) const; private: void printAux(raw_ostream &Out, bool printLocations, const char *NL, const char *Sep) const; }; class EnvironmentManager { private: typedef Environment::BindingsTy::Factory FactoryTy; FactoryTy F; public: EnvironmentManager(llvm::BumpPtrAllocator& Allocator) : F(Allocator) {} Environment getInitialEnvironment() { return Environment(F.getEmptyMap()); } /// Bind a symbolic value to the given environment entry. Environment bindExpr(Environment Env, const EnvironmentEntry &E, SVal V, bool Invalidate); Environment removeDeadBindings(Environment Env, SymbolReaper &SymReaper, ProgramStateRef state); }; } // end GR namespace } // end clang namespace #endif
0
repos/DirectXShaderCompiler/tools/clang/include/clang/StaticAnalyzer/Core
repos/DirectXShaderCompiler/tools/clang/include/clang/StaticAnalyzer/Core/PathSensitive/DynamicTypeInfo.h
//== DynamicTypeInfo.h - Runtime type information ----------------*- C++ -*--=// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_DYNAMICTYPEINFO_H #define LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_DYNAMICTYPEINFO_H #include "clang/AST/Type.h" namespace clang { namespace ento { /// \brief Stores the currently inferred strictest bound on the runtime type /// of a region in a given state along the analysis path. class DynamicTypeInfo { private: QualType T; bool CanBeASubClass; public: DynamicTypeInfo() : T(QualType()) {} DynamicTypeInfo(QualType WithType, bool CanBeSub = true) : T(WithType), CanBeASubClass(CanBeSub) {} /// \brief Return false if no dynamic type info is available. bool isValid() const { return !T.isNull(); } /// \brief Returns the currently inferred upper bound on the runtime type. QualType getType() const { return T; } /// \brief Returns false if the type information is precise (the type T is /// the only type in the lattice), true otherwise. bool canBeASubClass() const { return CanBeASubClass; } void Profile(llvm::FoldingSetNodeID &ID) const { ID.Add(T); ID.AddInteger((unsigned)CanBeASubClass); } bool operator==(const DynamicTypeInfo &X) const { return T == X.T && CanBeASubClass == X.CanBeASubClass; } }; } // end ento } // end clang #endif
0
repos/DirectXShaderCompiler/tools/clang/include/clang/StaticAnalyzer/Core
repos/DirectXShaderCompiler/tools/clang/include/clang/StaticAnalyzer/Core/PathSensitive/TaintManager.h
//== TaintManager.h - Managing taint --------------------------- -*- C++ -*--=// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file provides APIs for adding, removing, querying symbol taint. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_TAINTMANAGER_H #define LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_TAINTMANAGER_H #include "clang/StaticAnalyzer/Core/BugReporter/PathDiagnostic.h" #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h" #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h" #include "clang/StaticAnalyzer/Core/PathSensitive/TaintTag.h" #include "llvm/ADT/ImmutableMap.h" namespace clang { namespace ento { /// The GDM component containing the tainted root symbols. We lazily infer the /// taint of the dependent symbols. Currently, this is a map from a symbol to /// tag kind. TODO: Should support multiple tag kinds. // FIXME: This does not use the nice trait macros because it must be accessible // from multiple translation units. struct TaintMap {}; typedef llvm::ImmutableMap<SymbolRef, TaintTagType> TaintMapImpl; template<> struct ProgramStateTrait<TaintMap> : public ProgramStatePartialTrait<TaintMapImpl> { static void *GDMIndex() { static int index = 0; return &index; } }; class TaintManager { TaintManager() {} }; } } #endif
0
repos/DirectXShaderCompiler/tools/clang/include/clang/StaticAnalyzer/Core
repos/DirectXShaderCompiler/tools/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h
//== CheckerContext.h - Context info for path-sensitive checkers--*- C++ -*--=// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines CheckerContext that provides contextual info for // path-sensitive checkers. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_CHECKERCONTEXT_H #define LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_CHECKERCONTEXT_H #include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h" #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h" namespace clang { namespace ento { /// Declares an immutable map of type \p NameTy, suitable for placement into /// the ProgramState. This is implementing using llvm::ImmutableMap. /// /// \code /// State = State->set<Name>(K, V); /// const Value *V = State->get<Name>(K); // Returns NULL if not in the map. /// State = State->remove<Name>(K); /// NameTy Map = State->get<Name>(); /// \endcode /// /// The macro should not be used inside namespaces, or for traits that must /// be accessible from more than one translation unit. #define REGISTER_MAP_WITH_PROGRAMSTATE(Name, Key, Value) \ REGISTER_TRAIT_WITH_PROGRAMSTATE(Name, \ CLANG_ENTO_PROGRAMSTATE_MAP(Key, Value)) /// Declares an immutable set of type \p NameTy, suitable for placement into /// the ProgramState. This is implementing using llvm::ImmutableSet. /// /// \code /// State = State->add<Name>(E); /// State = State->remove<Name>(E); /// bool Present = State->contains<Name>(E); /// NameTy Set = State->get<Name>(); /// \endcode /// /// The macro should not be used inside namespaces, or for traits that must /// be accessible from more than one translation unit. #define REGISTER_SET_WITH_PROGRAMSTATE(Name, Elem) \ REGISTER_TRAIT_WITH_PROGRAMSTATE(Name, llvm::ImmutableSet<Elem>) /// Declares an immutable list of type \p NameTy, suitable for placement into /// the ProgramState. This is implementing using llvm::ImmutableList. /// /// \code /// State = State->add<Name>(E); // Adds to the /end/ of the list. /// bool Present = State->contains<Name>(E); /// NameTy List = State->get<Name>(); /// \endcode /// /// The macro should not be used inside namespaces, or for traits that must /// be accessible from more than one translation unit. #define REGISTER_LIST_WITH_PROGRAMSTATE(Name, Elem) \ REGISTER_TRAIT_WITH_PROGRAMSTATE(Name, llvm::ImmutableList<Elem>) class CheckerContext { ExprEngine &Eng; /// The current exploded(symbolic execution) graph node. ExplodedNode *Pred; /// The flag is true if the (state of the execution) has been modified /// by the checker using this context. For example, a new transition has been /// added or a bug report issued. bool Changed; /// The tagged location, which is used to generate all new nodes. const ProgramPoint Location; NodeBuilder &NB; public: /// If we are post visiting a call, this flag will be set if the /// call was inlined. In all other cases it will be false. const bool wasInlined; CheckerContext(NodeBuilder &builder, ExprEngine &eng, ExplodedNode *pred, const ProgramPoint &loc, bool wasInlined = false) : Eng(eng), Pred(pred), Changed(false), Location(loc), NB(builder), wasInlined(wasInlined) { assert(Pred->getState() && "We should not call the checkers on an empty state."); } AnalysisManager &getAnalysisManager() { return Eng.getAnalysisManager(); } ConstraintManager &getConstraintManager() { return Eng.getConstraintManager(); } StoreManager &getStoreManager() { return Eng.getStoreManager(); } /// \brief Returns the previous node in the exploded graph, which includes /// the state of the program before the checker ran. Note, checkers should /// not retain the node in their state since the nodes might get invalidated. ExplodedNode *getPredecessor() { return Pred; } const ProgramStateRef &getState() const { return Pred->getState(); } /// \brief Check if the checker changed the state of the execution; ex: added /// a new transition or a bug report. bool isDifferent() { return Changed; } /// \brief Returns the number of times the current block has been visited /// along the analyzed path. unsigned blockCount() const { return NB.getContext().blockCount(); } ASTContext &getASTContext() { return Eng.getContext(); } const LangOptions &getLangOpts() const { return Eng.getContext().getLangOpts(); } const LocationContext *getLocationContext() const { return Pred->getLocationContext(); } const StackFrameContext *getStackFrame() const { return Pred->getStackFrame(); } /// Return true if the current LocationContext has no caller context. bool inTopFrame() const { return getLocationContext()->inTopFrame(); } BugReporter &getBugReporter() { return Eng.getBugReporter(); } SourceManager &getSourceManager() { return getBugReporter().getSourceManager(); } SValBuilder &getSValBuilder() { return Eng.getSValBuilder(); } SymbolManager &getSymbolManager() { return getSValBuilder().getSymbolManager(); } bool isObjCGCEnabled() const { return Eng.isObjCGCEnabled(); } ProgramStateManager &getStateManager() { return Eng.getStateManager(); } AnalysisDeclContext *getCurrentAnalysisDeclContext() const { return Pred->getLocationContext()->getAnalysisDeclContext(); } /// \brief Get the blockID. unsigned getBlockID() const { return NB.getContext().getBlock()->getBlockID(); } /// \brief If the given node corresponds to a PostStore program point, /// retrieve the location region as it was uttered in the code. /// /// This utility can be useful for generating extensive diagnostics, for /// example, for finding variables that the given symbol was assigned to. static const MemRegion *getLocationRegionIfPostStore(const ExplodedNode *N) { ProgramPoint L = N->getLocation(); if (Optional<PostStore> PSL = L.getAs<PostStore>()) return reinterpret_cast<const MemRegion*>(PSL->getLocationValue()); return nullptr; } /// \brief Get the value of arbitrary expressions at this point in the path. SVal getSVal(const Stmt *S) const { return getState()->getSVal(S, getLocationContext()); } /// \brief Generates a new transition in the program state graph /// (ExplodedGraph). Uses the default CheckerContext predecessor node. /// /// @param State The state of the generated node. If not specified, the state /// will not be changed, but the new node will have the checker's tag. /// @param Tag The tag is used to uniquely identify the creation site. If no /// tag is specified, a default tag, unique to the given checker, /// will be used. Tags are used to prevent states generated at /// different sites from caching out. ExplodedNode *addTransition(ProgramStateRef State = nullptr, const ProgramPointTag *Tag = nullptr) { return addTransitionImpl(State ? State : getState(), false, nullptr, Tag); } /// \brief Generates a new transition with the given predecessor. /// Allows checkers to generate a chain of nodes. /// /// @param State The state of the generated node. /// @param Pred The transition will be generated from the specified Pred node /// to the newly generated node. /// @param Tag The tag to uniquely identify the creation site. ExplodedNode *addTransition(ProgramStateRef State, ExplodedNode *Pred, const ProgramPointTag *Tag = nullptr) { return addTransitionImpl(State, false, Pred, Tag); } /// \brief Generate a sink node. Generating a sink stops exploration of the /// given path. ExplodedNode *generateSink(ProgramStateRef State = nullptr, ExplodedNode *Pred = nullptr, const ProgramPointTag *Tag = nullptr) { return addTransitionImpl(State ? State : getState(), true, Pred, Tag); } /// \brief Emit the diagnostics report. void emitReport(std::unique_ptr<BugReport> R) { Changed = true; Eng.getBugReporter().emitReport(std::move(R)); } /// \brief Get the declaration of the called function (path-sensitive). const FunctionDecl *getCalleeDecl(const CallExpr *CE) const; /// \brief Get the name of the called function (path-sensitive). StringRef getCalleeName(const FunctionDecl *FunDecl) const; /// \brief Get the identifier of the called function (path-sensitive). const IdentifierInfo *getCalleeIdentifier(const CallExpr *CE) const { const FunctionDecl *FunDecl = getCalleeDecl(CE); if (FunDecl) return FunDecl->getIdentifier(); else return nullptr; } /// \brief Get the name of the called function (path-sensitive). StringRef getCalleeName(const CallExpr *CE) const { const FunctionDecl *FunDecl = getCalleeDecl(CE); return getCalleeName(FunDecl); } /// \brief Returns true if the callee is an externally-visible function in the /// top-level namespace, such as \c malloc. /// /// If a name is provided, the function must additionally match the given /// name. /// /// Note that this deliberately excludes C++ library functions in the \c std /// namespace, but will include C library functions accessed through the /// \c std namespace. This also does not check if the function is declared /// as 'extern "C"', or if it uses C++ name mangling. static bool isCLibraryFunction(const FunctionDecl *FD, StringRef Name = StringRef()); /// \brief Depending on wither the location corresponds to a macro, return /// either the macro name or the token spelling. /// /// This could be useful when checkers' logic depends on whether a function /// is called with a given macro argument. For example: /// s = socket(AF_INET,..) /// If AF_INET is a macro, the result should be treated as a source of taint. /// /// \sa clang::Lexer::getSpelling(), clang::Lexer::getImmediateMacroName(). StringRef getMacroNameOrSpelling(SourceLocation &Loc); private: ExplodedNode *addTransitionImpl(ProgramStateRef State, bool MarkAsSink, ExplodedNode *P = nullptr, const ProgramPointTag *Tag = nullptr) { if (!State || (State == Pred->getState() && !Tag && !MarkAsSink)) return Pred; Changed = true; const ProgramPoint &LocalLoc = (Tag ? Location.withTag(Tag) : Location); if (!P) P = Pred; ExplodedNode *node; if (MarkAsSink) node = NB.generateSink(LocalLoc, State, P); else node = NB.generateNode(LocalLoc, State, P); return node; } }; } // end GR namespace } // end clang namespace #endif
0
repos/DirectXShaderCompiler/tools/clang/include/clang/StaticAnalyzer/Core
repos/DirectXShaderCompiler/tools/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ProgramState_Fwd.h
//== ProgramState_Fwd.h - Incomplete declarations of ProgramState -*- C++ -*--=/ // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_PROGRAMSTATE_FWD_H #define LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_PROGRAMSTATE_FWD_H #include "clang/Basic/LLVM.h" #include "llvm/ADT/IntrusiveRefCntPtr.h" namespace clang { namespace ento { class ProgramState; class ProgramStateManager; void ProgramStateRetain(const ProgramState *state); void ProgramStateRelease(const ProgramState *state); } } namespace llvm { template <> struct IntrusiveRefCntPtrInfo<const clang::ento::ProgramState> { static void retain(const clang::ento::ProgramState *state) { clang::ento::ProgramStateRetain(state); } static void release(const clang::ento::ProgramState *state) { clang::ento::ProgramStateRelease(state); } }; } namespace clang { namespace ento { typedef IntrusiveRefCntPtr<const ProgramState> ProgramStateRef; } } #endif
0
repos/DirectXShaderCompiler/tools/clang/include/clang/StaticAnalyzer/Core
repos/DirectXShaderCompiler/tools/clang/include/clang/StaticAnalyzer/Core/PathSensitive/SummaryManager.h
//== SummaryManager.h - Generic handling of function summaries --*- C++ -*--==// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines SummaryManager and related classes, which provides // a generic mechanism for managing function summaries. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_GR_SUMMARY #define LLVM_CLANG_GR_SUMMARY #include "llvm/ADT/FoldingSet.h" #include "llvm/Support/Allocator.h" namespace clang { namespace ento { namespace summMgr { /* Key kinds: - C functions - C++ functions (name + parameter types) - ObjC methods: - Class, selector (class method) - Class, selector (instance method) - Category, selector (instance method) - Protocol, selector (instance method) - C++ methods - Class, function name + parameter types + const */ class SummaryKey { }; } // end namespace clang::summMgr class SummaryManagerImpl { }; template <typename T> class SummaryManager : SummaryManagerImpl { }; } // end GR namespace } // end clang namespace #endif
0
repos/DirectXShaderCompiler/tools/clang/include/clang/StaticAnalyzer/Core
repos/DirectXShaderCompiler/tools/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ExplodedGraph.h
//=-- ExplodedGraph.h - Local, Path-Sens. "Exploded Graph" -*- C++ -*-------==// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines the template classes ExplodedNode and ExplodedGraph, // which represent a path-sensitive, intra-procedural "exploded graph." // See "Precise interprocedural dataflow analysis via graph reachability" // by Reps, Horwitz, and Sagiv // (http://portal.acm.org/citation.cfm?id=199462) for the definition of an // exploded graph. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_EXPLODEDGRAPH_H #define LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_EXPLODEDGRAPH_H #include "clang/AST/Decl.h" #include "clang/Analysis/AnalysisContext.h" #include "clang/Analysis/ProgramPoint.h" #include "clang/Analysis/Support/BumpVector.h" #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h" #include "llvm/ADT/DepthFirstIterator.h" #include "llvm/ADT/FoldingSet.h" #include "llvm/ADT/GraphTraits.h" #include "llvm/ADT/SmallPtrSet.h" #include "llvm/ADT/SmallVector.h" #include "llvm/Support/Allocator.h" #include "llvm/Support/Casting.h" #include <memory> #include <vector> namespace clang { class CFG; namespace ento { class ExplodedGraph; //===----------------------------------------------------------------------===// // ExplodedGraph "implementation" classes. These classes are not typed to // contain a specific kind of state. Typed-specialized versions are defined // on top of these classes. // // /////////////////////////////////////////////////////////////////////////////// // ExplodedNode is not constified all over the engine because we need to add // successors to it at any time after creating it. class ExplodedNode : public llvm::FoldingSetNode { friend class ExplodedGraph; friend class CoreEngine; friend class NodeBuilder; friend class BranchNodeBuilder; friend class IndirectGotoNodeBuilder; friend class SwitchNodeBuilder; friend class EndOfFunctionNodeBuilder; /// Efficiently stores a list of ExplodedNodes, or an optional flag. /// /// NodeGroup provides opaque storage for a list of ExplodedNodes, optimizing /// for the case when there is only one node in the group. This is a fairly /// common case in an ExplodedGraph, where most nodes have only one /// predecessor and many have only one successor. It can also be used to /// store a flag rather than a node list, which ExplodedNode uses to mark /// whether a node is a sink. If the flag is set, the group is implicitly /// empty and no nodes may be added. class NodeGroup { // Conceptually a discriminated union. If the low bit is set, the node is // a sink. If the low bit is not set, the pointer refers to the storage // for the nodes in the group. // This is not a PointerIntPair in order to keep the storage type opaque. uintptr_t P; public: NodeGroup(bool Flag = false) : P(Flag) { assert(getFlag() == Flag); } ExplodedNode * const *begin() const; ExplodedNode * const *end() const; unsigned size() const; bool empty() const { return P == 0 || getFlag() != 0; } /// Adds a node to the list. /// /// The group must not have been created with its flag set. void addNode(ExplodedNode *N, ExplodedGraph &G); /// Replaces the single node in this group with a new node. /// /// Note that this should only be used when you know the group was not /// created with its flag set, and that the group is empty or contains /// only a single node. void replaceNode(ExplodedNode *node); /// Returns whether this group was created with its flag set. bool getFlag() const { return (P & 1); } }; /// Location - The program location (within a function body) associated /// with this node. const ProgramPoint Location; /// State - The state associated with this node. ProgramStateRef State; /// Preds - The predecessors of this node. NodeGroup Preds; /// Succs - The successors of this node. NodeGroup Succs; public: explicit ExplodedNode(const ProgramPoint &loc, ProgramStateRef state, bool IsSink) : Location(loc), State(state), Succs(IsSink) { assert(isSink() == IsSink); } /// getLocation - Returns the edge associated with the given node. ProgramPoint getLocation() const { return Location; } const LocationContext *getLocationContext() const { return getLocation().getLocationContext(); } const StackFrameContext *getStackFrame() const { return getLocationContext()->getCurrentStackFrame(); } const Decl &getCodeDecl() const { return *getLocationContext()->getDecl(); } CFG &getCFG() const { return *getLocationContext()->getCFG(); } ParentMap &getParentMap() const {return getLocationContext()->getParentMap();} template <typename T> T &getAnalysis() const { return *getLocationContext()->getAnalysis<T>(); } const ProgramStateRef &getState() const { return State; } template <typename T> Optional<T> getLocationAs() const LLVM_LVALUE_FUNCTION { return Location.getAs<T>(); } static void Profile(llvm::FoldingSetNodeID &ID, const ProgramPoint &Loc, const ProgramStateRef &state, bool IsSink) { ID.Add(Loc); ID.AddPointer(state.get()); ID.AddBoolean(IsSink); } void Profile(llvm::FoldingSetNodeID& ID) const { // We avoid copy constructors by not using accessors. Profile(ID, Location, State, isSink()); } /// addPredeccessor - Adds a predecessor to the current node, and /// in tandem add this node as a successor of the other node. void addPredecessor(ExplodedNode *V, ExplodedGraph &G); unsigned succ_size() const { return Succs.size(); } unsigned pred_size() const { return Preds.size(); } bool succ_empty() const { return Succs.empty(); } bool pred_empty() const { return Preds.empty(); } bool isSink() const { return Succs.getFlag(); } bool hasSinglePred() const { return (pred_size() == 1); } ExplodedNode *getFirstPred() { return pred_empty() ? nullptr : *(pred_begin()); } const ExplodedNode *getFirstPred() const { return const_cast<ExplodedNode*>(this)->getFirstPred(); } const ExplodedNode *getFirstSucc() const { return succ_empty() ? nullptr : *(succ_begin()); } // Iterators over successor and predecessor vertices. typedef ExplodedNode* const * succ_iterator; typedef const ExplodedNode* const * const_succ_iterator; typedef ExplodedNode* const * pred_iterator; typedef const ExplodedNode* const * const_pred_iterator; pred_iterator pred_begin() { return Preds.begin(); } pred_iterator pred_end() { return Preds.end(); } const_pred_iterator pred_begin() const { return const_cast<ExplodedNode*>(this)->pred_begin(); } const_pred_iterator pred_end() const { return const_cast<ExplodedNode*>(this)->pred_end(); } succ_iterator succ_begin() { return Succs.begin(); } succ_iterator succ_end() { return Succs.end(); } const_succ_iterator succ_begin() const { return const_cast<ExplodedNode*>(this)->succ_begin(); } const_succ_iterator succ_end() const { return const_cast<ExplodedNode*>(this)->succ_end(); } // For debugging. public: class Auditor { public: virtual ~Auditor(); virtual void AddEdge(ExplodedNode *Src, ExplodedNode *Dst) = 0; }; static void SetAuditor(Auditor* A); private: void replaceSuccessor(ExplodedNode *node) { Succs.replaceNode(node); } void replacePredecessor(ExplodedNode *node) { Preds.replaceNode(node); } }; typedef llvm::DenseMap<const ExplodedNode *, const ExplodedNode *> InterExplodedGraphMap; class ExplodedGraph { protected: friend class CoreEngine; // Type definitions. typedef std::vector<ExplodedNode *> NodeVector; /// The roots of the simulation graph. Usually there will be only /// one, but clients are free to establish multiple subgraphs within a single /// SimulGraph. Moreover, these subgraphs can often merge when paths from /// different roots reach the same state at the same program location. NodeVector Roots; /// The nodes in the simulation graph which have been /// specially marked as the endpoint of an abstract simulation path. NodeVector EndNodes; /// Nodes - The nodes in the graph. llvm::FoldingSet<ExplodedNode> Nodes; /// BVC - Allocator and context for allocating nodes and their predecessor /// and successor groups. BumpVectorContext BVC; /// NumNodes - The number of nodes in the graph. unsigned NumNodes; /// A list of recently allocated nodes that can potentially be recycled. NodeVector ChangedNodes; /// A list of nodes that can be reused. NodeVector FreeNodes; /// Determines how often nodes are reclaimed. /// /// If this is 0, nodes will never be reclaimed. unsigned ReclaimNodeInterval; /// Counter to determine when to reclaim nodes. unsigned ReclaimCounter; public: /// \brief Retrieve the node associated with a (Location,State) pair, /// where the 'Location' is a ProgramPoint in the CFG. If no node for /// this pair exists, it is created. IsNew is set to true if /// the node was freshly created. ExplodedNode *getNode(const ProgramPoint &L, ProgramStateRef State, bool IsSink = false, bool* IsNew = nullptr); std::unique_ptr<ExplodedGraph> MakeEmptyGraph() const { return llvm::make_unique<ExplodedGraph>(); } /// addRoot - Add an untyped node to the set of roots. ExplodedNode *addRoot(ExplodedNode *V) { Roots.push_back(V); return V; } /// addEndOfPath - Add an untyped node to the set of EOP nodes. ExplodedNode *addEndOfPath(ExplodedNode *V) { EndNodes.push_back(V); return V; } ExplodedGraph(); ~ExplodedGraph(); unsigned num_roots() const { return Roots.size(); } unsigned num_eops() const { return EndNodes.size(); } bool empty() const { return NumNodes == 0; } unsigned size() const { return NumNodes; } // Iterators. typedef ExplodedNode NodeTy; typedef llvm::FoldingSet<ExplodedNode> AllNodesTy; typedef NodeVector::iterator roots_iterator; typedef NodeVector::const_iterator const_roots_iterator; typedef NodeVector::iterator eop_iterator; typedef NodeVector::const_iterator const_eop_iterator; typedef AllNodesTy::iterator node_iterator; typedef AllNodesTy::const_iterator const_node_iterator; node_iterator nodes_begin() { return Nodes.begin(); } node_iterator nodes_end() { return Nodes.end(); } const_node_iterator nodes_begin() const { return Nodes.begin(); } const_node_iterator nodes_end() const { return Nodes.end(); } roots_iterator roots_begin() { return Roots.begin(); } roots_iterator roots_end() { return Roots.end(); } const_roots_iterator roots_begin() const { return Roots.begin(); } const_roots_iterator roots_end() const { return Roots.end(); } eop_iterator eop_begin() { return EndNodes.begin(); } eop_iterator eop_end() { return EndNodes.end(); } const_eop_iterator eop_begin() const { return EndNodes.begin(); } const_eop_iterator eop_end() const { return EndNodes.end(); } llvm::BumpPtrAllocator & getAllocator() { return BVC.getAllocator(); } BumpVectorContext &getNodeAllocator() { return BVC; } typedef llvm::DenseMap<const ExplodedNode*, ExplodedNode*> NodeMap; /// Creates a trimmed version of the graph that only contains paths leading /// to the given nodes. /// /// \param Nodes The nodes which must appear in the final graph. Presumably /// these are end-of-path nodes (i.e. they have no successors). /// \param[out] ForwardMap A optional map from nodes in this graph to nodes in /// the returned graph. /// \param[out] InverseMap An optional map from nodes in the returned graph to /// nodes in this graph. /// \returns The trimmed graph std::unique_ptr<ExplodedGraph> trim(ArrayRef<const NodeTy *> Nodes, InterExplodedGraphMap *ForwardMap = nullptr, InterExplodedGraphMap *InverseMap = nullptr) const; /// Enable tracking of recently allocated nodes for potential reclamation /// when calling reclaimRecentlyAllocatedNodes(). void enableNodeReclamation(unsigned Interval) { ReclaimCounter = ReclaimNodeInterval = Interval; } /// Reclaim "uninteresting" nodes created since the last time this method /// was called. void reclaimRecentlyAllocatedNodes(); /// \brief Returns true if nodes for the given expression kind are always /// kept around. static bool isInterestingLValueExpr(const Expr *Ex); private: bool shouldCollect(const ExplodedNode *node); void collectNode(ExplodedNode *node); }; class ExplodedNodeSet { typedef llvm::SmallPtrSet<ExplodedNode*,5> ImplTy; ImplTy Impl; public: ExplodedNodeSet(ExplodedNode *N) { assert (N && !static_cast<ExplodedNode*>(N)->isSink()); Impl.insert(N); } ExplodedNodeSet() {} inline void Add(ExplodedNode *N) { if (N && !static_cast<ExplodedNode*>(N)->isSink()) Impl.insert(N); } typedef ImplTy::iterator iterator; typedef ImplTy::const_iterator const_iterator; unsigned size() const { return Impl.size(); } bool empty() const { return Impl.empty(); } bool erase(ExplodedNode *N) { return Impl.erase(N); } void clear() { Impl.clear(); } void insert(const ExplodedNodeSet &S) { assert(&S != this); if (empty()) Impl = S.Impl; else Impl.insert(S.begin(), S.end()); } inline iterator begin() { return Impl.begin(); } inline iterator end() { return Impl.end(); } inline const_iterator begin() const { return Impl.begin(); } inline const_iterator end() const { return Impl.end(); } }; } // end GR namespace } // end clang namespace // GraphTraits namespace llvm { template<> struct GraphTraits<clang::ento::ExplodedNode*> { typedef clang::ento::ExplodedNode NodeType; typedef NodeType::succ_iterator ChildIteratorType; typedef llvm::df_iterator<NodeType*> nodes_iterator; static inline NodeType* getEntryNode(NodeType* N) { return N; } static inline ChildIteratorType child_begin(NodeType* N) { return N->succ_begin(); } static inline ChildIteratorType child_end(NodeType* N) { return N->succ_end(); } static inline nodes_iterator nodes_begin(NodeType* N) { return df_begin(N); } static inline nodes_iterator nodes_end(NodeType* N) { return df_end(N); } }; template<> struct GraphTraits<const clang::ento::ExplodedNode*> { typedef const clang::ento::ExplodedNode NodeType; typedef NodeType::const_succ_iterator ChildIteratorType; typedef llvm::df_iterator<NodeType*> nodes_iterator; static inline NodeType* getEntryNode(NodeType* N) { return N; } static inline ChildIteratorType child_begin(NodeType* N) { return N->succ_begin(); } static inline ChildIteratorType child_end(NodeType* N) { return N->succ_end(); } static inline nodes_iterator nodes_begin(NodeType* N) { return df_begin(N); } static inline nodes_iterator nodes_end(NodeType* N) { return df_end(N); } }; } // end llvm namespace #endif
0
repos/DirectXShaderCompiler/tools/clang/include/clang/StaticAnalyzer/Core
repos/DirectXShaderCompiler/tools/clang/include/clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h
//== AnalysisManager.h - Path sensitive analysis data manager ------*- C++ -*-// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines the AnalysisManager class that manages the data and policy // for path sensitive analysis. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_ANALYSISMANAGER_H #define LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_ANALYSISMANAGER_H #include "clang/Analysis/AnalysisContext.h" #include "clang/StaticAnalyzer/Core/AnalyzerOptions.h" #include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h" #include "clang/StaticAnalyzer/Core/BugReporter/PathDiagnostic.h" #include "clang/StaticAnalyzer/Core/PathDiagnosticConsumers.h" namespace clang { class CodeInjector; namespace ento { class CheckerManager; class AnalysisManager : public BugReporterData { virtual void anchor(); AnalysisDeclContextManager AnaCtxMgr; ASTContext &Ctx; DiagnosticsEngine &Diags; const LangOptions &LangOpts; PathDiagnosticConsumers PathConsumers; // Configurable components creators. StoreManagerCreator CreateStoreMgr; ConstraintManagerCreator CreateConstraintMgr; CheckerManager *CheckerMgr; public: AnalyzerOptions &options; AnalysisManager(ASTContext &ctx,DiagnosticsEngine &diags, const LangOptions &lang, const PathDiagnosticConsumers &Consumers, StoreManagerCreator storemgr, ConstraintManagerCreator constraintmgr, CheckerManager *checkerMgr, AnalyzerOptions &Options, CodeInjector* injector = nullptr); ~AnalysisManager() override; void ClearContexts() { AnaCtxMgr.clear(); } AnalysisDeclContextManager& getAnalysisDeclContextManager() { return AnaCtxMgr; } StoreManagerCreator getStoreManagerCreator() { return CreateStoreMgr; } AnalyzerOptions& getAnalyzerOptions() override { return options; } ConstraintManagerCreator getConstraintManagerCreator() { return CreateConstraintMgr; } CheckerManager *getCheckerManager() const { return CheckerMgr; } ASTContext &getASTContext() override { return Ctx; } SourceManager &getSourceManager() override { return getASTContext().getSourceManager(); } DiagnosticsEngine &getDiagnostic() override { return Diags; } const LangOptions &getLangOpts() const { return LangOpts; } ArrayRef<PathDiagnosticConsumer*> getPathDiagnosticConsumers() override { return PathConsumers; } void FlushDiagnostics(); bool shouldVisualize() const { return options.visualizeExplodedGraphWithGraphViz || options.visualizeExplodedGraphWithUbiGraph; } bool shouldInlineCall() const { return options.getIPAMode() != IPAK_None; } CFG *getCFG(Decl const *D) { return AnaCtxMgr.getContext(D)->getCFG(); } template <typename T> T *getAnalysis(Decl const *D) { return AnaCtxMgr.getContext(D)->getAnalysis<T>(); } ParentMap &getParentMap(Decl const *D) { return AnaCtxMgr.getContext(D)->getParentMap(); } AnalysisDeclContext *getAnalysisDeclContext(const Decl *D) { return AnaCtxMgr.getContext(D); } }; } // enAnaCtxMgrspace } // end clang namespace #endif
0
repos/DirectXShaderCompiler/tools/clang/include/clang/StaticAnalyzer/Core
repos/DirectXShaderCompiler/tools/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h
//===-- ExprEngine.h - Path-Sensitive Expression-Level Dataflow ---*- C++ -*-=// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines a meta-engine for path-sensitive dataflow analysis that // is built on CoreEngine, but provides the boilerplate to execute transfer // functions and build the ExplodedGraph at the expression level. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_EXPRENGINE_H #define LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_EXPRENGINE_H #include "clang/AST/Expr.h" #include "clang/AST/Type.h" #include "clang/Analysis/DomainSpecific/ObjCNoReturn.h" #include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h" #include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h" #include "clang/StaticAnalyzer/Core/PathSensitive/CoreEngine.h" #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h" #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h" #include "clang/StaticAnalyzer/Core/PathSensitive/SubEngine.h" namespace clang { class AnalysisDeclContextManager; class CXXCatchStmt; class CXXConstructExpr; class CXXDeleteExpr; class CXXNewExpr; class CXXTemporaryObjectExpr; class CXXThisExpr; class MaterializeTemporaryExpr; class ObjCAtSynchronizedStmt; class ObjCForCollectionStmt; namespace ento { class AnalysisManager; class CallEvent; class CXXConstructorCall; class ExprEngine : public SubEngine { public: /// The modes of inlining, which override the default analysis-wide settings. enum InliningModes { /// Follow the default settings for inlining callees. Inline_Regular = 0, /// Do minimal inlining of callees. Inline_Minimal = 0x1 }; private: AnalysisManager &AMgr; AnalysisDeclContextManager &AnalysisDeclContexts; CoreEngine Engine; /// G - the simulation graph. ExplodedGraph& G; /// StateMgr - Object that manages the data for all created states. ProgramStateManager StateMgr; /// SymMgr - Object that manages the symbol information. SymbolManager& SymMgr; /// svalBuilder - SValBuilder object that creates SVals from expressions. SValBuilder &svalBuilder; unsigned int currStmtIdx; const NodeBuilderContext *currBldrCtx; /// Helper object to determine if an Objective-C message expression /// implicitly never returns. ObjCNoReturn ObjCNoRet; /// Whether or not GC is enabled in this analysis. bool ObjCGCEnabled; /// The BugReporter associated with this engine. It is important that /// this object be placed at the very end of member variables so that its /// destructor is called before the rest of the ExprEngine is destroyed. GRBugReporter BR; /// The functions which have been analyzed through inlining. This is owned by /// AnalysisConsumer. It can be null. SetOfConstDecls *VisitedCallees; /// The flag, which specifies the mode of inlining for the engine. InliningModes HowToInline; public: ExprEngine(AnalysisManager &mgr, bool gcEnabled, SetOfConstDecls *VisitedCalleesIn, FunctionSummariesTy *FS, InliningModes HowToInlineIn); ~ExprEngine() override; /// Returns true if there is still simulation state on the worklist. bool ExecuteWorkList(const LocationContext *L, unsigned Steps = 150000) { return Engine.ExecuteWorkList(L, Steps, nullptr); } /// Execute the work list with an initial state. Nodes that reaches the exit /// of the function are added into the Dst set, which represent the exit /// state of the function call. Returns true if there is still simulation /// state on the worklist. bool ExecuteWorkListWithInitialState(const LocationContext *L, unsigned Steps, ProgramStateRef InitState, ExplodedNodeSet &Dst) { return Engine.ExecuteWorkListWithInitialState(L, Steps, InitState, Dst); } /// getContext - Return the ASTContext associated with this analysis. ASTContext &getContext() const { return AMgr.getASTContext(); } AnalysisManager &getAnalysisManager() override { return AMgr; } CheckerManager &getCheckerManager() const { return *AMgr.getCheckerManager(); } SValBuilder &getSValBuilder() { return svalBuilder; } BugReporter& getBugReporter() { return BR; } const NodeBuilderContext &getBuilderContext() { assert(currBldrCtx); return *currBldrCtx; } bool isObjCGCEnabled() { return ObjCGCEnabled; } const Stmt *getStmt() const; void GenerateAutoTransition(ExplodedNode *N); void enqueueEndOfPath(ExplodedNodeSet &S); void GenerateCallExitNode(ExplodedNode *N); /// Visualize the ExplodedGraph created by executing the simulation. void ViewGraph(bool trim = false); /// Visualize a trimmed ExplodedGraph that only contains paths to the given /// nodes. void ViewGraph(ArrayRef<const ExplodedNode*> Nodes); /// getInitialState - Return the initial state used for the root vertex /// in the ExplodedGraph. ProgramStateRef getInitialState(const LocationContext *InitLoc) override; ExplodedGraph& getGraph() { return G; } const ExplodedGraph& getGraph() const { return G; } /// \brief Run the analyzer's garbage collection - remove dead symbols and /// bindings from the state. /// /// Checkers can participate in this process with two callbacks: /// \c checkLiveSymbols and \c checkDeadSymbols. See the CheckerDocumentation /// class for more information. /// /// \param Node The predecessor node, from which the processing should start. /// \param Out The returned set of output nodes. /// \param ReferenceStmt The statement which is about to be processed. /// Everything needed for this statement should be considered live. /// A null statement means that everything in child LocationContexts /// is dead. /// \param LC The location context of the \p ReferenceStmt. A null location /// context means that we have reached the end of analysis and that /// all statements and local variables should be considered dead. /// \param DiagnosticStmt Used as a location for any warnings that should /// occur while removing the dead (e.g. leaks). By default, the /// \p ReferenceStmt is used. /// \param K Denotes whether this is a pre- or post-statement purge. This /// must only be ProgramPoint::PostStmtPurgeDeadSymbolsKind if an /// entire location context is being cleared, in which case the /// \p ReferenceStmt must either be a ReturnStmt or \c NULL. Otherwise, /// it must be ProgramPoint::PreStmtPurgeDeadSymbolsKind (the default) /// and \p ReferenceStmt must be valid (non-null). void removeDead(ExplodedNode *Node, ExplodedNodeSet &Out, const Stmt *ReferenceStmt, const LocationContext *LC, const Stmt *DiagnosticStmt = nullptr, ProgramPoint::Kind K = ProgramPoint::PreStmtPurgeDeadSymbolsKind); /// processCFGElement - Called by CoreEngine. Used to generate new successor /// nodes by processing the 'effects' of a CFG element. void processCFGElement(const CFGElement E, ExplodedNode *Pred, unsigned StmtIdx, NodeBuilderContext *Ctx) override; void ProcessStmt(const CFGStmt S, ExplodedNode *Pred); void ProcessInitializer(const CFGInitializer I, ExplodedNode *Pred); void ProcessImplicitDtor(const CFGImplicitDtor D, ExplodedNode *Pred); void ProcessNewAllocator(const CXXNewExpr *NE, ExplodedNode *Pred); void ProcessAutomaticObjDtor(const CFGAutomaticObjDtor D, ExplodedNode *Pred, ExplodedNodeSet &Dst); void ProcessDeleteDtor(const CFGDeleteDtor D, ExplodedNode *Pred, ExplodedNodeSet &Dst); void ProcessBaseDtor(const CFGBaseDtor D, ExplodedNode *Pred, ExplodedNodeSet &Dst); void ProcessMemberDtor(const CFGMemberDtor D, ExplodedNode *Pred, ExplodedNodeSet &Dst); void ProcessTemporaryDtor(const CFGTemporaryDtor D, ExplodedNode *Pred, ExplodedNodeSet &Dst); /// Called by CoreEngine when processing the entrance of a CFGBlock. void processCFGBlockEntrance(const BlockEdge &L, NodeBuilderWithSinks &nodeBuilder, ExplodedNode *Pred) override; /// ProcessBranch - Called by CoreEngine. Used to generate successor /// nodes by processing the 'effects' of a branch condition. void processBranch(const Stmt *Condition, const Stmt *Term, NodeBuilderContext& BuilderCtx, ExplodedNode *Pred, ExplodedNodeSet &Dst, const CFGBlock *DstT, const CFGBlock *DstF) override; /// Called by CoreEngine. /// Used to generate successor nodes for temporary destructors depending /// on whether the corresponding constructor was visited. void processCleanupTemporaryBranch(const CXXBindTemporaryExpr *BTE, NodeBuilderContext &BldCtx, ExplodedNode *Pred, ExplodedNodeSet &Dst, const CFGBlock *DstT, const CFGBlock *DstF) override; /// Called by CoreEngine. Used to processing branching behavior /// at static initalizers. void processStaticInitializer(const DeclStmt *DS, NodeBuilderContext& BuilderCtx, ExplodedNode *Pred, ExplodedNodeSet &Dst, const CFGBlock *DstT, const CFGBlock *DstF) override; /// processIndirectGoto - Called by CoreEngine. Used to generate successor /// nodes by processing the 'effects' of a computed goto jump. void processIndirectGoto(IndirectGotoNodeBuilder& builder) override; /// ProcessSwitch - Called by CoreEngine. Used to generate successor /// nodes by processing the 'effects' of a switch statement. void processSwitch(SwitchNodeBuilder& builder) override; /// Called by CoreEngine. Used to generate end-of-path /// nodes when the control reaches the end of a function. void processEndOfFunction(NodeBuilderContext& BC, ExplodedNode *Pred) override; /// Remove dead bindings/symbols before exiting a function. void removeDeadOnEndOfFunction(NodeBuilderContext& BC, ExplodedNode *Pred, ExplodedNodeSet &Dst); /// Generate the entry node of the callee. void processCallEnter(CallEnter CE, ExplodedNode *Pred) override; /// Generate the sequence of nodes that simulate the call exit and the post /// visit for CallExpr. void processCallExit(ExplodedNode *Pred) override; /// Called by CoreEngine when the analysis worklist has terminated. void processEndWorklist(bool hasWorkRemaining) override; /// evalAssume - Callback function invoked by the ConstraintManager when /// making assumptions about state values. ProgramStateRef processAssume(ProgramStateRef state, SVal cond, bool assumption) override; /// wantsRegionChangeUpdate - Called by ProgramStateManager to determine if a /// region change should trigger a processRegionChanges update. bool wantsRegionChangeUpdate(ProgramStateRef state) override; /// processRegionChanges - Called by ProgramStateManager whenever a change is made /// to the store. Used to update checkers that track region values. ProgramStateRef processRegionChanges(ProgramStateRef state, const InvalidatedSymbols *invalidated, ArrayRef<const MemRegion *> ExplicitRegions, ArrayRef<const MemRegion *> Regions, const CallEvent *Call) override; /// printState - Called by ProgramStateManager to print checker-specific data. void printState(raw_ostream &Out, ProgramStateRef State, const char *NL, const char *Sep) override; ProgramStateManager& getStateManager() override { return StateMgr; } StoreManager& getStoreManager() { return StateMgr.getStoreManager(); } ConstraintManager& getConstraintManager() { return StateMgr.getConstraintManager(); } // FIXME: Remove when we migrate over to just using SValBuilder. BasicValueFactory& getBasicVals() { return StateMgr.getBasicVals(); } // FIXME: Remove when we migrate over to just using ValueManager. SymbolManager& getSymbolManager() { return SymMgr; } const SymbolManager& getSymbolManager() const { return SymMgr; } // Functions for external checking of whether we have unfinished work bool wasBlocksExhausted() const { return Engine.wasBlocksExhausted(); } bool hasEmptyWorkList() const { return !Engine.getWorkList()->hasWork(); } bool hasWorkRemaining() const { return Engine.hasWorkRemaining(); } const CoreEngine &getCoreEngine() const { return Engine; } public: /// Visit - Transfer function logic for all statements. Dispatches to /// other functions that handle specific kinds of statements. void Visit(const Stmt *S, ExplodedNode *Pred, ExplodedNodeSet &Dst); /// VisitArraySubscriptExpr - Transfer function for array accesses. void VisitLvalArraySubscriptExpr(const ArraySubscriptExpr *Ex, ExplodedNode *Pred, ExplodedNodeSet &Dst); /// VisitGCCAsmStmt - Transfer function logic for inline asm. void VisitGCCAsmStmt(const GCCAsmStmt *A, ExplodedNode *Pred, ExplodedNodeSet &Dst); /// VisitMSAsmStmt - Transfer function logic for MS inline asm. void VisitMSAsmStmt(const MSAsmStmt *A, ExplodedNode *Pred, ExplodedNodeSet &Dst); /// VisitBlockExpr - Transfer function logic for BlockExprs. void VisitBlockExpr(const BlockExpr *BE, ExplodedNode *Pred, ExplodedNodeSet &Dst); /// VisitBinaryOperator - Transfer function logic for binary operators. void VisitBinaryOperator(const BinaryOperator* B, ExplodedNode *Pred, ExplodedNodeSet &Dst); /// VisitCall - Transfer function for function calls. void VisitCallExpr(const CallExpr *CE, ExplodedNode *Pred, ExplodedNodeSet &Dst); /// VisitCast - Transfer function logic for all casts (implicit and explicit). void VisitCast(const CastExpr *CastE, const Expr *Ex, ExplodedNode *Pred, ExplodedNodeSet &Dst); /// VisitCompoundLiteralExpr - Transfer function logic for compound literals. void VisitCompoundLiteralExpr(const CompoundLiteralExpr *CL, ExplodedNode *Pred, ExplodedNodeSet &Dst); /// Transfer function logic for DeclRefExprs and BlockDeclRefExprs. void VisitCommonDeclRefExpr(const Expr *DR, const NamedDecl *D, ExplodedNode *Pred, ExplodedNodeSet &Dst); /// VisitDeclStmt - Transfer function logic for DeclStmts. void VisitDeclStmt(const DeclStmt *DS, ExplodedNode *Pred, ExplodedNodeSet &Dst); /// VisitGuardedExpr - Transfer function logic for ?, __builtin_choose void VisitGuardedExpr(const Expr *Ex, const Expr *L, const Expr *R, ExplodedNode *Pred, ExplodedNodeSet &Dst); void VisitInitListExpr(const InitListExpr *E, ExplodedNode *Pred, ExplodedNodeSet &Dst); /// VisitLogicalExpr - Transfer function logic for '&&', '||' void VisitLogicalExpr(const BinaryOperator* B, ExplodedNode *Pred, ExplodedNodeSet &Dst); /// VisitMemberExpr - Transfer function for member expressions. void VisitMemberExpr(const MemberExpr *M, ExplodedNode *Pred, ExplodedNodeSet &Dst); /// Transfer function logic for ObjCAtSynchronizedStmts. void VisitObjCAtSynchronizedStmt(const ObjCAtSynchronizedStmt *S, ExplodedNode *Pred, ExplodedNodeSet &Dst); /// Transfer function logic for computing the lvalue of an Objective-C ivar. void VisitLvalObjCIvarRefExpr(const ObjCIvarRefExpr *DR, ExplodedNode *Pred, ExplodedNodeSet &Dst); /// VisitObjCForCollectionStmt - Transfer function logic for /// ObjCForCollectionStmt. void VisitObjCForCollectionStmt(const ObjCForCollectionStmt *S, ExplodedNode *Pred, ExplodedNodeSet &Dst); void VisitObjCMessage(const ObjCMessageExpr *ME, ExplodedNode *Pred, ExplodedNodeSet &Dst); /// VisitReturnStmt - Transfer function logic for return statements. void VisitReturnStmt(const ReturnStmt *R, ExplodedNode *Pred, ExplodedNodeSet &Dst); /// VisitOffsetOfExpr - Transfer function for offsetof. void VisitOffsetOfExpr(const OffsetOfExpr *Ex, ExplodedNode *Pred, ExplodedNodeSet &Dst); /// VisitUnaryExprOrTypeTraitExpr - Transfer function for sizeof. void VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *Ex, ExplodedNode *Pred, ExplodedNodeSet &Dst); /// VisitUnaryOperator - Transfer function logic for unary operators. void VisitUnaryOperator(const UnaryOperator* B, ExplodedNode *Pred, ExplodedNodeSet &Dst); /// Handle ++ and -- (both pre- and post-increment). void VisitIncrementDecrementOperator(const UnaryOperator* U, ExplodedNode *Pred, ExplodedNodeSet &Dst); void VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *BTE, ExplodedNodeSet &PreVisit, ExplodedNodeSet &Dst); void VisitCXXCatchStmt(const CXXCatchStmt *CS, ExplodedNode *Pred, ExplodedNodeSet &Dst); void VisitCXXThisExpr(const CXXThisExpr *TE, ExplodedNode *Pred, ExplodedNodeSet & Dst); void VisitCXXConstructExpr(const CXXConstructExpr *E, ExplodedNode *Pred, ExplodedNodeSet &Dst); void VisitCXXDestructor(QualType ObjectType, const MemRegion *Dest, const Stmt *S, bool IsBaseDtor, ExplodedNode *Pred, ExplodedNodeSet &Dst); void VisitCXXNewAllocatorCall(const CXXNewExpr *CNE, ExplodedNode *Pred, ExplodedNodeSet &Dst); void VisitCXXNewExpr(const CXXNewExpr *CNE, ExplodedNode *Pred, ExplodedNodeSet &Dst); void VisitCXXDeleteExpr(const CXXDeleteExpr *CDE, ExplodedNode *Pred, ExplodedNodeSet &Dst); /// Create a C++ temporary object for an rvalue. void CreateCXXTemporaryObject(const MaterializeTemporaryExpr *ME, ExplodedNode *Pred, ExplodedNodeSet &Dst); /// evalEagerlyAssumeBinOpBifurcation - Given the nodes in 'Src', eagerly assume symbolic /// expressions of the form 'x != 0' and generate new nodes (stored in Dst) /// with those assumptions. void evalEagerlyAssumeBinOpBifurcation(ExplodedNodeSet &Dst, ExplodedNodeSet &Src, const Expr *Ex); std::pair<const ProgramPointTag *, const ProgramPointTag*> geteagerlyAssumeBinOpBifurcationTags(); SVal evalMinus(SVal X) { return X.isValid() ? svalBuilder.evalMinus(X.castAs<NonLoc>()) : X; } SVal evalComplement(SVal X) { return X.isValid() ? svalBuilder.evalComplement(X.castAs<NonLoc>()) : X; } public: SVal evalBinOp(ProgramStateRef state, BinaryOperator::Opcode op, NonLoc L, NonLoc R, QualType T) { return svalBuilder.evalBinOpNN(state, op, L, R, T); } SVal evalBinOp(ProgramStateRef state, BinaryOperator::Opcode op, NonLoc L, SVal R, QualType T) { return R.isValid() ? svalBuilder.evalBinOpNN(state, op, L, R.castAs<NonLoc>(), T) : R; } SVal evalBinOp(ProgramStateRef ST, BinaryOperator::Opcode Op, SVal LHS, SVal RHS, QualType T) { return svalBuilder.evalBinOp(ST, Op, LHS, RHS, T); } protected: /// evalBind - Handle the semantics of binding a value to a specific location. /// This method is used by evalStore, VisitDeclStmt, and others. void evalBind(ExplodedNodeSet &Dst, const Stmt *StoreE, ExplodedNode *Pred, SVal location, SVal Val, bool atDeclInit = false, const ProgramPoint *PP = nullptr); /// Call PointerEscape callback when a value escapes as a result of bind. ProgramStateRef processPointerEscapedOnBind(ProgramStateRef State, SVal Loc, SVal Val) override; /// Call PointerEscape callback when a value escapes as a result of /// region invalidation. /// \param[in] ITraits Specifies invalidation traits for regions/symbols. ProgramStateRef notifyCheckersOfPointerEscape( ProgramStateRef State, const InvalidatedSymbols *Invalidated, ArrayRef<const MemRegion *> ExplicitRegions, ArrayRef<const MemRegion *> Regions, const CallEvent *Call, RegionAndSymbolInvalidationTraits &ITraits) override; public: // FIXME: 'tag' should be removed, and a LocationContext should be used // instead. // FIXME: Comment on the meaning of the arguments, when 'St' may not // be the same as Pred->state, and when 'location' may not be the // same as state->getLValue(Ex). /// Simulate a read of the result of Ex. void evalLoad(ExplodedNodeSet &Dst, const Expr *NodeEx, /* Eventually will be a CFGStmt */ const Expr *BoundExpr, ExplodedNode *Pred, ProgramStateRef St, SVal location, const ProgramPointTag *tag = nullptr, QualType LoadTy = QualType()); // FIXME: 'tag' should be removed, and a LocationContext should be used // instead. void evalStore(ExplodedNodeSet &Dst, const Expr *AssignE, const Expr *StoreE, ExplodedNode *Pred, ProgramStateRef St, SVal TargetLV, SVal Val, const ProgramPointTag *tag = nullptr); /// \brief Create a new state in which the call return value is binded to the /// call origin expression. ProgramStateRef bindReturnValue(const CallEvent &Call, const LocationContext *LCtx, ProgramStateRef State); /// Evaluate a call, running pre- and post-call checks and allowing checkers /// to be responsible for handling the evaluation of the call itself. void evalCall(ExplodedNodeSet &Dst, ExplodedNode *Pred, const CallEvent &Call); /// \brief Default implementation of call evaluation. void defaultEvalCall(NodeBuilder &B, ExplodedNode *Pred, const CallEvent &Call); private: void evalLoadCommon(ExplodedNodeSet &Dst, const Expr *NodeEx, /* Eventually will be a CFGStmt */ const Expr *BoundEx, ExplodedNode *Pred, ProgramStateRef St, SVal location, const ProgramPointTag *tag, QualType LoadTy); // FIXME: 'tag' should be removed, and a LocationContext should be used // instead. void evalLocation(ExplodedNodeSet &Dst, const Stmt *NodeEx, /* This will eventually be a CFGStmt */ const Stmt *BoundEx, ExplodedNode *Pred, ProgramStateRef St, SVal location, const ProgramPointTag *tag, bool isLoad); /// Count the stack depth and determine if the call is recursive. void examineStackFrames(const Decl *D, const LocationContext *LCtx, bool &IsRecursive, unsigned &StackDepth); /// Checks our policies and decides weither the given call should be inlined. bool shouldInlineCall(const CallEvent &Call, const Decl *D, const ExplodedNode *Pred); bool inlineCall(const CallEvent &Call, const Decl *D, NodeBuilder &Bldr, ExplodedNode *Pred, ProgramStateRef State); /// \brief Conservatively evaluate call by invalidating regions and binding /// a conjured return value. void conservativeEvalCall(const CallEvent &Call, NodeBuilder &Bldr, ExplodedNode *Pred, ProgramStateRef State); /// \brief Either inline or process the call conservatively (or both), based /// on DynamicDispatchBifurcation data. void BifurcateCall(const MemRegion *BifurReg, const CallEvent &Call, const Decl *D, NodeBuilder &Bldr, ExplodedNode *Pred); bool replayWithoutInlining(ExplodedNode *P, const LocationContext *CalleeLC); /// Models a trivial copy or move constructor or trivial assignment operator /// call with a simple bind. void performTrivialCopy(NodeBuilder &Bldr, ExplodedNode *Pred, const CallEvent &Call); /// If the value of the given expression is a NonLoc, copy it into a new /// temporary object region, and replace the value of the expression with /// that. /// /// If \p ResultE is provided, the new region will be bound to this expression /// instead of \p E. ProgramStateRef createTemporaryRegionIfNeeded(ProgramStateRef State, const LocationContext *LC, const Expr *E, const Expr *ResultE = nullptr); }; /// Traits for storing the call processing policy inside GDM. /// The GDM stores the corresponding CallExpr pointer. // FIXME: This does not use the nice trait macros because it must be accessible // from multiple translation units. struct ReplayWithoutInlining{}; template <> struct ProgramStateTrait<ReplayWithoutInlining> : public ProgramStatePartialTrait<const void*> { static void *GDMIndex() { static int index = 0; return &index; } }; } // end ento namespace } // end clang namespace #endif
0
repos/DirectXShaderCompiler/tools/clang/include/clang/StaticAnalyzer/Core
repos/DirectXShaderCompiler/tools/clang/include/clang/StaticAnalyzer/Core/PathSensitive/FunctionSummary.h
//== FunctionSummary.h - Stores summaries of functions. ------------*- C++ -*-// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines a summary of a function gathered/used by static analysis. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_FUNCTIONSUMMARY_H #define LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_FUNCTIONSUMMARY_H #include "clang/Basic/LLVM.h" #include "llvm/ADT/DenseMap.h" #include "llvm/ADT/DenseSet.h" #include "llvm/ADT/Optional.h" #include "llvm/ADT/SmallBitVector.h" #include <deque> namespace clang { class Decl; namespace ento { typedef std::deque<Decl*> SetOfDecls; typedef llvm::DenseSet<const Decl*> SetOfConstDecls; class FunctionSummariesTy { class FunctionSummary { public: /// Marks the IDs of the basic blocks visited during the analyzes. llvm::SmallBitVector VisitedBasicBlocks; /// Total number of blocks in the function. unsigned TotalBasicBlocks : 30; /// True if this function has been checked against the rules for which /// functions may be inlined. unsigned InlineChecked : 1; /// True if this function may be inlined. unsigned MayInline : 1; /// The number of times the function has been inlined. unsigned TimesInlined : 32; FunctionSummary() : TotalBasicBlocks(0), InlineChecked(0), TimesInlined(0) {} }; typedef llvm::DenseMap<const Decl *, FunctionSummary> MapTy; MapTy Map; public: MapTy::iterator findOrInsertSummary(const Decl *D) { MapTy::iterator I = Map.find(D); if (I != Map.end()) return I; typedef std::pair<const Decl *, FunctionSummary> KVPair; I = Map.insert(KVPair(D, FunctionSummary())).first; assert(I != Map.end()); return I; } void markMayInline(const Decl *D) { MapTy::iterator I = findOrInsertSummary(D); I->second.InlineChecked = 1; I->second.MayInline = 1; } void markShouldNotInline(const Decl *D) { MapTy::iterator I = findOrInsertSummary(D); I->second.InlineChecked = 1; I->second.MayInline = 0; } void markReachedMaxBlockCount(const Decl *D) { markShouldNotInline(D); } Optional<bool> mayInline(const Decl *D) { MapTy::const_iterator I = Map.find(D); if (I != Map.end() && I->second.InlineChecked) return I->second.MayInline; return None; } void markVisitedBasicBlock(unsigned ID, const Decl* D, unsigned TotalIDs) { MapTy::iterator I = findOrInsertSummary(D); llvm::SmallBitVector &Blocks = I->second.VisitedBasicBlocks; assert(ID < TotalIDs); if (TotalIDs > Blocks.size()) { Blocks.resize(TotalIDs); I->second.TotalBasicBlocks = TotalIDs; } Blocks.set(ID); } unsigned getNumVisitedBasicBlocks(const Decl* D) { MapTy::const_iterator I = Map.find(D); if (I != Map.end()) return I->second.VisitedBasicBlocks.count(); return 0; } unsigned getNumTimesInlined(const Decl* D) { MapTy::const_iterator I = Map.find(D); if (I != Map.end()) return I->second.TimesInlined; return 0; } void bumpNumTimesInlined(const Decl* D) { MapTy::iterator I = findOrInsertSummary(D); I->second.TimesInlined++; } /// Get the percentage of the reachable blocks. unsigned getPercentBlocksReachable(const Decl *D) { MapTy::const_iterator I = Map.find(D); if (I != Map.end()) return ((I->second.VisitedBasicBlocks.count() * 100) / I->second.TotalBasicBlocks); return 0; } unsigned getTotalNumBasicBlocks(); unsigned getTotalNumVisitedBasicBlocks(); }; }} // end clang ento namespaces #endif
0
repos/DirectXShaderCompiler/tools/clang/include/clang/StaticAnalyzer/Core
repos/DirectXShaderCompiler/tools/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CheckerHelpers.h
//== CheckerHelpers.h - Helper functions for checkers ------------*- C++ -*--=// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines CheckerVisitor. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_CHECKERHELPERS_H #define LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_CHECKERHELPERS_H #include "clang/AST/Stmt.h" namespace clang { namespace ento { bool containsMacro(const Stmt *S); bool containsEnum(const Stmt *S); bool containsStaticLocal(const Stmt *S); bool containsBuiltinOffsetOf(const Stmt *S); template <class T> bool containsStmt(const Stmt *S) { if (isa<T>(S)) return true; for (const Stmt *Child : S->children()) if (Child && containsStmt<T>(Child)) return true; return false; } } // end GR namespace } // end clang namespace #endif
0
repos/DirectXShaderCompiler/tools/clang/include/clang/StaticAnalyzer/Core
repos/DirectXShaderCompiler/tools/clang/include/clang/StaticAnalyzer/Core/PathSensitive/StoreRef.h
//== StoreRef.h - Smart pointer for store objects ---------------*- C++ -*--==// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defined the type StoreRef. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_STOREREF_H #define LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_STOREREF_H #include <cassert> namespace clang { namespace ento { /// Store - This opaque type encapsulates an immutable mapping from /// locations to values. At a high-level, it represents the symbolic /// memory model. Different subclasses of StoreManager may choose /// different types to represent the locations and values. typedef const void *Store; class StoreManager; class StoreRef { Store store; StoreManager &mgr; public: StoreRef(Store, StoreManager &); StoreRef(const StoreRef &); StoreRef &operator=(StoreRef const &); bool operator==(const StoreRef &x) const { assert(&mgr == &x.mgr); return x.store == store; } bool operator!=(const StoreRef &x) const { return !operator==(x); } ~StoreRef(); Store getStore() const { return store; } const StoreManager &getStoreManager() const { return mgr; } }; }} #endif
0
repos/DirectXShaderCompiler/tools/clang/include/clang/StaticAnalyzer/Core
repos/DirectXShaderCompiler/tools/clang/include/clang/StaticAnalyzer/Core/PathSensitive/BasicValueFactory.h
//=== BasicValueFactory.h - Basic values for Path Sens analysis --*- C++ -*---// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines BasicValueFactory, a class that manages the lifetime // of APSInt objects and symbolic constraints used by ExprEngine // and related classes. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_BASICVALUEFACTORY_H #define LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_BASICVALUEFACTORY_H #include "clang/AST/ASTContext.h" #include "clang/StaticAnalyzer/Core/PathSensitive/APSIntType.h" #include "clang/StaticAnalyzer/Core/PathSensitive/SVals.h" #include "clang/StaticAnalyzer/Core/PathSensitive/StoreRef.h" namespace clang { namespace ento { class CompoundValData : public llvm::FoldingSetNode { QualType T; llvm::ImmutableList<SVal> L; public: CompoundValData(QualType t, llvm::ImmutableList<SVal> l) : T(t), L(l) {} typedef llvm::ImmutableList<SVal>::iterator iterator; iterator begin() const { return L.begin(); } iterator end() const { return L.end(); } static void Profile(llvm::FoldingSetNodeID& ID, QualType T, llvm::ImmutableList<SVal> L); void Profile(llvm::FoldingSetNodeID& ID) { Profile(ID, T, L); } }; class LazyCompoundValData : public llvm::FoldingSetNode { StoreRef store; const TypedValueRegion *region; public: LazyCompoundValData(const StoreRef &st, const TypedValueRegion *r) : store(st), region(r) {} const void *getStore() const { return store.getStore(); } const TypedValueRegion *getRegion() const { return region; } static void Profile(llvm::FoldingSetNodeID& ID, const StoreRef &store, const TypedValueRegion *region); void Profile(llvm::FoldingSetNodeID& ID) { Profile(ID, store, region); } }; class BasicValueFactory { typedef llvm::FoldingSet<llvm::FoldingSetNodeWrapper<llvm::APSInt> > APSIntSetTy; ASTContext &Ctx; llvm::BumpPtrAllocator& BPAlloc; APSIntSetTy APSIntSet; void * PersistentSVals; void * PersistentSValPairs; llvm::ImmutableList<SVal>::Factory SValListFactory; llvm::FoldingSet<CompoundValData> CompoundValDataSet; llvm::FoldingSet<LazyCompoundValData> LazyCompoundValDataSet; // This is private because external clients should use the factory // method that takes a QualType. const llvm::APSInt& getValue(uint64_t X, unsigned BitWidth, bool isUnsigned); public: BasicValueFactory(ASTContext &ctx, llvm::BumpPtrAllocator &Alloc) : Ctx(ctx), BPAlloc(Alloc), PersistentSVals(nullptr), PersistentSValPairs(nullptr), SValListFactory(Alloc) {} ~BasicValueFactory(); ASTContext &getContext() const { return Ctx; } const llvm::APSInt& getValue(const llvm::APSInt& X); const llvm::APSInt& getValue(const llvm::APInt& X, bool isUnsigned); const llvm::APSInt& getValue(uint64_t X, QualType T); /// Returns the type of the APSInt used to store values of the given QualType. APSIntType getAPSIntType(QualType T) const { assert(T->isIntegralOrEnumerationType() || Loc::isLocType(T)); return APSIntType(Ctx.getTypeSize(T), !T->isSignedIntegerOrEnumerationType()); } /// Convert - Create a new persistent APSInt with the same value as 'From' /// but with the bitwidth and signedness of 'To'. const llvm::APSInt &Convert(const llvm::APSInt& To, const llvm::APSInt& From) { APSIntType TargetType(To); if (TargetType == APSIntType(From)) return From; return getValue(TargetType.convert(From)); } const llvm::APSInt &Convert(QualType T, const llvm::APSInt &From) { APSIntType TargetType = getAPSIntType(T); if (TargetType == APSIntType(From)) return From; return getValue(TargetType.convert(From)); } const llvm::APSInt& getIntValue(uint64_t X, bool isUnsigned) { QualType T = isUnsigned ? Ctx.UnsignedIntTy : Ctx.IntTy; return getValue(X, T); } inline const llvm::APSInt& getMaxValue(const llvm::APSInt &v) { return getValue(APSIntType(v).getMaxValue()); } inline const llvm::APSInt& getMinValue(const llvm::APSInt &v) { return getValue(APSIntType(v).getMinValue()); } inline const llvm::APSInt& getMaxValue(QualType T) { return getValue(getAPSIntType(T).getMaxValue()); } inline const llvm::APSInt& getMinValue(QualType T) { return getValue(getAPSIntType(T).getMinValue()); } inline const llvm::APSInt& Add1(const llvm::APSInt& V) { llvm::APSInt X = V; ++X; return getValue(X); } inline const llvm::APSInt& Sub1(const llvm::APSInt& V) { llvm::APSInt X = V; --X; return getValue(X); } inline const llvm::APSInt& getZeroWithPtrWidth(bool isUnsigned = true) { return getValue(0, Ctx.getTypeSize(Ctx.VoidPtrTy), isUnsigned); } inline const llvm::APSInt &getIntWithPtrWidth(uint64_t X, bool isUnsigned) { return getValue(X, Ctx.getTypeSize(Ctx.VoidPtrTy), isUnsigned); } inline const llvm::APSInt& getTruthValue(bool b, QualType T) { return getValue(b ? 1 : 0, Ctx.getTypeSize(T), false); } inline const llvm::APSInt& getTruthValue(bool b) { return getTruthValue(b, Ctx.getLogicalOperationType()); } const CompoundValData *getCompoundValData(QualType T, llvm::ImmutableList<SVal> Vals); const LazyCompoundValData *getLazyCompoundValData(const StoreRef &store, const TypedValueRegion *region); llvm::ImmutableList<SVal> getEmptySValList() { return SValListFactory.getEmptyList(); } llvm::ImmutableList<SVal> consVals(SVal X, llvm::ImmutableList<SVal> L) { return SValListFactory.add(X, L); } const llvm::APSInt* evalAPSInt(BinaryOperator::Opcode Op, const llvm::APSInt& V1, const llvm::APSInt& V2); const std::pair<SVal, uintptr_t>& getPersistentSValWithData(const SVal& V, uintptr_t Data); const std::pair<SVal, SVal>& getPersistentSValPair(const SVal& V1, const SVal& V2); const SVal* getPersistentSVal(SVal X); }; } // end GR namespace } // end clang namespace #endif
0
repos/DirectXShaderCompiler/tools/clang/include/clang/StaticAnalyzer/Core
repos/DirectXShaderCompiler/tools/clang/include/clang/StaticAnalyzer/Core/PathSensitive/SVals.h
//== SVals.h - Abstract Values for Static Analysis ---------*- C++ -*--==// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines SVal, Loc, and NonLoc, classes that represent // abstract r-values for use with path-sensitive value tracking. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_SVALS_H #define LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_SVALS_H #include "clang/Basic/LLVM.h" #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState_Fwd.h" #include "clang/StaticAnalyzer/Core/PathSensitive/SymbolManager.h" #include "llvm/ADT/ImmutableList.h" //==------------------------------------------------------------------------==// // Base SVal types. //==------------------------------------------------------------------------==// namespace clang { namespace ento { class CompoundValData; class LazyCompoundValData; class ProgramState; class BasicValueFactory; class MemRegion; class TypedValueRegion; class MemRegionManager; class ProgramStateManager; class SValBuilder; /// SVal - This represents a symbolic expression, which can be either /// an L-value or an R-value. /// class SVal { public: enum BaseKind { // The enumerators must be representable using 2 bits. UndefinedKind = 0, // for subclass UndefinedVal (an uninitialized value) UnknownKind = 1, // for subclass UnknownVal (a void value) LocKind = 2, // for subclass Loc (an L-value) NonLocKind = 3 // for subclass NonLoc (an R-value that's not // an L-value) }; enum { BaseBits = 2, BaseMask = 0x3 }; protected: const void *Data; /// The lowest 2 bits are a BaseKind (0 -- 3). /// The higher bits are an unsigned "kind" value. unsigned Kind; explicit SVal(const void *d, bool isLoc, unsigned ValKind) : Data(d), Kind((isLoc ? LocKind : NonLocKind) | (ValKind << BaseBits)) {} explicit SVal(BaseKind k, const void *D = nullptr) : Data(D), Kind(k) {} public: explicit SVal() : Data(nullptr), Kind(0) {} /// \brief Convert to the specified SVal type, asserting that this SVal is of /// the desired type. template<typename T> T castAs() const { assert(T::isKind(*this)); T t; SVal& sv = t; sv = *this; return t; } /// \brief Convert to the specified SVal type, returning None if this SVal is /// not of the desired type. template<typename T> Optional<T> getAs() const { if (!T::isKind(*this)) return None; T t; SVal& sv = t; sv = *this; return t; } /// BufferTy - A temporary buffer to hold a set of SVals. typedef SmallVector<SVal,5> BufferTy; inline unsigned getRawKind() const { return Kind; } inline BaseKind getBaseKind() const { return (BaseKind) (Kind & BaseMask); } inline unsigned getSubKind() const { return (Kind & ~BaseMask) >> BaseBits; } // This method is required for using SVal in a FoldingSetNode. It // extracts a unique signature for this SVal object. inline void Profile(llvm::FoldingSetNodeID& ID) const { ID.AddInteger((unsigned) getRawKind()); ID.AddPointer(Data); } inline bool operator==(const SVal& R) const { return getRawKind() == R.getRawKind() && Data == R.Data; } inline bool operator!=(const SVal& R) const { return !(*this == R); } inline bool isUnknown() const { return getRawKind() == UnknownKind; } inline bool isUndef() const { return getRawKind() == UndefinedKind; } inline bool isUnknownOrUndef() const { return getRawKind() <= UnknownKind; } inline bool isValid() const { return getRawKind() > UnknownKind; } bool isConstant() const; bool isConstant(int I) const; bool isZeroConstant() const; /// hasConjuredSymbol - If this SVal wraps a conjured symbol, return true; bool hasConjuredSymbol() const; /// getAsFunctionDecl - If this SVal is a MemRegionVal and wraps a /// CodeTextRegion wrapping a FunctionDecl, return that FunctionDecl. /// Otherwise return 0. const FunctionDecl *getAsFunctionDecl() const; /// \brief If this SVal is a location and wraps a symbol, return that /// SymbolRef. Otherwise return 0. /// /// Casts are ignored during lookup. /// \param IncludeBaseRegions The boolean that controls whether the search /// should continue to the base regions if the region is not symbolic. SymbolRef getAsLocSymbol(bool IncludeBaseRegions = false) const; /// Get the symbol in the SVal or its base region. SymbolRef getLocSymbolInBase() const; /// \brief If this SVal wraps a symbol return that SymbolRef. /// Otherwise, return 0. /// /// Casts are ignored during lookup. /// \param IncludeBaseRegions The boolean that controls whether the search /// should continue to the base regions if the region is not symbolic. SymbolRef getAsSymbol(bool IncludeBaseRegions = false) const; /// getAsSymbolicExpression - If this Sval wraps a symbolic expression then /// return that expression. Otherwise return NULL. const SymExpr *getAsSymbolicExpression() const; const SymExpr* getAsSymExpr() const; const MemRegion *getAsRegion() const; void dumpToStream(raw_ostream &OS) const; void dump() const; SymExpr::symbol_iterator symbol_begin() const { const SymExpr *SE = getAsSymbolicExpression(); if (SE) return SE->symbol_begin(); else return SymExpr::symbol_iterator(); } SymExpr::symbol_iterator symbol_end() const { return SymExpr::symbol_end(); } }; class UndefinedVal : public SVal { public: UndefinedVal() : SVal(UndefinedKind) {} private: friend class SVal; static bool isKind(const SVal& V) { return V.getBaseKind() == UndefinedKind; } }; class DefinedOrUnknownSVal : public SVal { private: // We want calling these methods to be a compiler error since they are // tautologically false. bool isUndef() const = delete; bool isValid() const = delete; protected: DefinedOrUnknownSVal() {} explicit DefinedOrUnknownSVal(const void *d, bool isLoc, unsigned ValKind) : SVal(d, isLoc, ValKind) {} explicit DefinedOrUnknownSVal(BaseKind k, void *D = nullptr) : SVal(k, D) {} private: friend class SVal; static bool isKind(const SVal& V) { return !V.isUndef(); } }; class UnknownVal : public DefinedOrUnknownSVal { public: explicit UnknownVal() : DefinedOrUnknownSVal(UnknownKind) {} private: friend class SVal; static bool isKind(const SVal &V) { return V.getBaseKind() == UnknownKind; } }; class DefinedSVal : public DefinedOrUnknownSVal { private: // We want calling these methods to be a compiler error since they are // tautologically true/false. bool isUnknown() const = delete; bool isUnknownOrUndef() const = delete; bool isValid() const = delete; protected: DefinedSVal() {} explicit DefinedSVal(const void *d, bool isLoc, unsigned ValKind) : DefinedOrUnknownSVal(d, isLoc, ValKind) {} private: friend class SVal; static bool isKind(const SVal& V) { return !V.isUnknownOrUndef(); } }; /// \brief Represents an SVal that is guaranteed to not be UnknownVal. class KnownSVal : public SVal { KnownSVal() {} friend class SVal; static bool isKind(const SVal &V) { return !V.isUnknown(); } public: KnownSVal(const DefinedSVal &V) : SVal(V) {} KnownSVal(const UndefinedVal &V) : SVal(V) {} }; class NonLoc : public DefinedSVal { protected: NonLoc() {} explicit NonLoc(unsigned SubKind, const void *d) : DefinedSVal(d, false, SubKind) {} public: void dumpToStream(raw_ostream &Out) const; private: friend class SVal; static bool isKind(const SVal& V) { return V.getBaseKind() == NonLocKind; } }; class Loc : public DefinedSVal { protected: Loc() {} explicit Loc(unsigned SubKind, const void *D) : DefinedSVal(const_cast<void*>(D), true, SubKind) {} public: void dumpToStream(raw_ostream &Out) const; static inline bool isLocType(QualType T) { return T->isAnyPointerType() || T->isBlockPointerType() || T->isReferenceType() || T->isNullPtrType(); } private: friend class SVal; static bool isKind(const SVal& V) { return V.getBaseKind() == LocKind; } }; //==------------------------------------------------------------------------==// // Subclasses of NonLoc. //==------------------------------------------------------------------------==// namespace nonloc { enum Kind { ConcreteIntKind, SymbolValKind, LocAsIntegerKind, CompoundValKind, LazyCompoundValKind }; /// \brief Represents symbolic expression. class SymbolVal : public NonLoc { public: SymbolVal(SymbolRef sym) : NonLoc(SymbolValKind, sym) {} SymbolRef getSymbol() const { return (const SymExpr*) Data; } bool isExpression() const { return !isa<SymbolData>(getSymbol()); } private: friend class SVal; SymbolVal() {} static bool isKind(const SVal& V) { return V.getBaseKind() == NonLocKind && V.getSubKind() == SymbolValKind; } static bool isKind(const NonLoc& V) { return V.getSubKind() == SymbolValKind; } }; /// \brief Value representing integer constant. class ConcreteInt : public NonLoc { public: explicit ConcreteInt(const llvm::APSInt& V) : NonLoc(ConcreteIntKind, &V) {} const llvm::APSInt& getValue() const { return *static_cast<const llvm::APSInt*>(Data); } // Transfer functions for binary/unary operations on ConcreteInts. SVal evalBinOp(SValBuilder &svalBuilder, BinaryOperator::Opcode Op, const ConcreteInt& R) const; ConcreteInt evalComplement(SValBuilder &svalBuilder) const; ConcreteInt evalMinus(SValBuilder &svalBuilder) const; private: friend class SVal; ConcreteInt() {} static bool isKind(const SVal& V) { return V.getBaseKind() == NonLocKind && V.getSubKind() == ConcreteIntKind; } static bool isKind(const NonLoc& V) { return V.getSubKind() == ConcreteIntKind; } }; class LocAsInteger : public NonLoc { friend class ento::SValBuilder; explicit LocAsInteger(const std::pair<SVal, uintptr_t> &data) : NonLoc(LocAsIntegerKind, &data) { assert (data.first.getAs<Loc>()); } public: Loc getLoc() const { const std::pair<SVal, uintptr_t> *D = static_cast<const std::pair<SVal, uintptr_t> *>(Data); return D->first.castAs<Loc>(); } Loc getPersistentLoc() const { const std::pair<SVal, uintptr_t> *D = static_cast<const std::pair<SVal, uintptr_t> *>(Data); const SVal& V = D->first; return V.castAs<Loc>(); } unsigned getNumBits() const { const std::pair<SVal, uintptr_t> *D = static_cast<const std::pair<SVal, uintptr_t> *>(Data); return D->second; } private: friend class SVal; LocAsInteger() {} static bool isKind(const SVal& V) { return V.getBaseKind() == NonLocKind && V.getSubKind() == LocAsIntegerKind; } static bool isKind(const NonLoc& V) { return V.getSubKind() == LocAsIntegerKind; } }; class CompoundVal : public NonLoc { friend class ento::SValBuilder; explicit CompoundVal(const CompoundValData* D) : NonLoc(CompoundValKind, D) {} public: const CompoundValData* getValue() const { return static_cast<const CompoundValData*>(Data); } typedef llvm::ImmutableList<SVal>::iterator iterator; iterator begin() const; iterator end() const; private: friend class SVal; CompoundVal() {} static bool isKind(const SVal& V) { return V.getBaseKind() == NonLocKind && V.getSubKind() == CompoundValKind; } static bool isKind(const NonLoc& V) { return V.getSubKind() == CompoundValKind; } }; class LazyCompoundVal : public NonLoc { friend class ento::SValBuilder; explicit LazyCompoundVal(const LazyCompoundValData *D) : NonLoc(LazyCompoundValKind, D) {} public: const LazyCompoundValData *getCVData() const { return static_cast<const LazyCompoundValData*>(Data); } const void *getStore() const; const TypedValueRegion *getRegion() const; private: friend class SVal; LazyCompoundVal() {} static bool isKind(const SVal& V) { return V.getBaseKind() == NonLocKind && V.getSubKind() == LazyCompoundValKind; } static bool isKind(const NonLoc& V) { return V.getSubKind() == LazyCompoundValKind; } }; } // end namespace ento::nonloc //==------------------------------------------------------------------------==// // Subclasses of Loc. //==------------------------------------------------------------------------==// namespace loc { enum Kind { GotoLabelKind, MemRegionKind, ConcreteIntKind }; class GotoLabel : public Loc { public: explicit GotoLabel(LabelDecl *Label) : Loc(GotoLabelKind, Label) {} const LabelDecl *getLabel() const { return static_cast<const LabelDecl*>(Data); } private: friend class SVal; GotoLabel() {} static bool isKind(const SVal& V) { return V.getBaseKind() == LocKind && V.getSubKind() == GotoLabelKind; } static bool isKind(const Loc& V) { return V.getSubKind() == GotoLabelKind; } }; class MemRegionVal : public Loc { public: explicit MemRegionVal(const MemRegion* r) : Loc(MemRegionKind, r) {} /// \brief Get the underlining region. const MemRegion* getRegion() const { return static_cast<const MemRegion*>(Data); } /// \brief Get the underlining region and strip casts. const MemRegion* stripCasts(bool StripBaseCasts = true) const; template <typename REGION> const REGION* getRegionAs() const { return dyn_cast<REGION>(getRegion()); } inline bool operator==(const MemRegionVal& R) const { return getRegion() == R.getRegion(); } inline bool operator!=(const MemRegionVal& R) const { return getRegion() != R.getRegion(); } private: friend class SVal; MemRegionVal() {} static bool isKind(const SVal& V) { return V.getBaseKind() == LocKind && V.getSubKind() == MemRegionKind; } static bool isKind(const Loc& V) { return V.getSubKind() == MemRegionKind; } }; class ConcreteInt : public Loc { public: explicit ConcreteInt(const llvm::APSInt& V) : Loc(ConcreteIntKind, &V) {} const llvm::APSInt& getValue() const { return *static_cast<const llvm::APSInt*>(Data); } // Transfer functions for binary/unary operations on ConcreteInts. SVal evalBinOp(BasicValueFactory& BasicVals, BinaryOperator::Opcode Op, const ConcreteInt& R) const; private: friend class SVal; ConcreteInt() {} static bool isKind(const SVal& V) { return V.getBaseKind() == LocKind && V.getSubKind() == ConcreteIntKind; } static bool isKind(const Loc& V) { return V.getSubKind() == ConcreteIntKind; } }; } // end ento::loc namespace } // end ento namespace } // end clang namespace namespace llvm { static inline raw_ostream &operator<<(raw_ostream &os, clang::ento::SVal V) { V.dumpToStream(os); return os; } template <typename T> struct isPodLike; template <> struct isPodLike<clang::ento::SVal> { static const bool value = true; }; } // end llvm namespace #endif
0
repos/DirectXShaderCompiler/tools/clang/include/clang/StaticAnalyzer/Core
repos/DirectXShaderCompiler/tools/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ConstraintManager.h
//== ConstraintManager.h - Constraints on symbolic values.-------*- C++ -*--==// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defined the interface to manage constraints on symbolic values. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_CONSTRAINTMANAGER_H #define LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_CONSTRAINTMANAGER_H #include "clang/StaticAnalyzer/Core/PathSensitive/SVals.h" #include "clang/StaticAnalyzer/Core/PathSensitive/SymbolManager.h" #include "llvm/Support/SaveAndRestore.h" namespace llvm { class APSInt; } namespace clang { namespace ento { class SubEngine; class ConditionTruthVal { Optional<bool> Val; public: /// Construct a ConditionTruthVal indicating the constraint is constrained /// to either true or false, depending on the boolean value provided. ConditionTruthVal(bool constraint) : Val(constraint) {} /// Construct a ConstraintVal indicating the constraint is underconstrained. ConditionTruthVal() {} /// Return true if the constraint is perfectly constrained to 'true'. bool isConstrainedTrue() const { return Val.hasValue() && Val.getValue(); } /// Return true if the constraint is perfectly constrained to 'false'. bool isConstrainedFalse() const { return Val.hasValue() && !Val.getValue(); } /// Return true if the constrained is perfectly constrained. bool isConstrained() const { return Val.hasValue(); } /// Return true if the constrained is underconstrained and we do not know /// if the constraint is true of value. bool isUnderconstrained() const { return !Val.hasValue(); } }; class ConstraintManager { public: ConstraintManager() : NotifyAssumeClients(true) {} virtual ~ConstraintManager(); virtual ProgramStateRef assume(ProgramStateRef state, DefinedSVal Cond, bool Assumption) = 0; typedef std::pair<ProgramStateRef, ProgramStateRef> ProgramStatePair; /// Returns a pair of states (StTrue, StFalse) where the given condition is /// assumed to be true or false, respectively. ProgramStatePair assumeDual(ProgramStateRef State, DefinedSVal Cond) { ProgramStateRef StTrue = assume(State, Cond, true); // If StTrue is infeasible, asserting the falseness of Cond is unnecessary // because the existing constraints already establish this. if (!StTrue) { #ifndef __OPTIMIZE__ // This check is expensive and should be disabled even in Release+Asserts // builds. // FIXME: __OPTIMIZE__ is a GNU extension that Clang implements but MSVC // does not. Is there a good equivalent there? assert(assume(State, Cond, false) && "System is over constrained."); #endif return ProgramStatePair((ProgramStateRef)nullptr, State); } ProgramStateRef StFalse = assume(State, Cond, false); if (!StFalse) { // We are careful to return the original state, /not/ StTrue, // because we want to avoid having callers generate a new node // in the ExplodedGraph. return ProgramStatePair(State, (ProgramStateRef)nullptr); } return ProgramStatePair(StTrue, StFalse); } /// \brief If a symbol is perfectly constrained to a constant, attempt /// to return the concrete value. /// /// Note that a ConstraintManager is not obligated to return a concretized /// value for a symbol, even if it is perfectly constrained. virtual const llvm::APSInt* getSymVal(ProgramStateRef state, SymbolRef sym) const { return nullptr; } virtual ProgramStateRef removeDeadBindings(ProgramStateRef state, SymbolReaper& SymReaper) = 0; virtual void print(ProgramStateRef state, raw_ostream &Out, const char* nl, const char *sep) = 0; virtual void EndPath(ProgramStateRef state) {} /// Convenience method to query the state to see if a symbol is null or /// not null, or if neither assumption can be made. ConditionTruthVal isNull(ProgramStateRef State, SymbolRef Sym) { SaveAndRestore<bool> DisableNotify(NotifyAssumeClients, false); return checkNull(State, Sym); } protected: /// A flag to indicate that clients should be notified of assumptions. /// By default this is the case, but sometimes this needs to be restricted /// to avoid infinite recursions within the ConstraintManager. /// /// Note that this flag allows the ConstraintManager to be re-entrant, /// but not thread-safe. bool NotifyAssumeClients; /// canReasonAbout - Not all ConstraintManagers can accurately reason about /// all SVal values. This method returns true if the ConstraintManager can /// reasonably handle a given SVal value. This is typically queried by /// ExprEngine to determine if the value should be replaced with a /// conjured symbolic value in order to recover some precision. virtual bool canReasonAbout(SVal X) const = 0; /// Returns whether or not a symbol is known to be null ("true"), known to be /// non-null ("false"), or may be either ("underconstrained"). virtual ConditionTruthVal checkNull(ProgramStateRef State, SymbolRef Sym); }; std::unique_ptr<ConstraintManager> CreateRangeConstraintManager(ProgramStateManager &statemgr, SubEngine *subengine); } // end GR namespace } // end clang namespace #endif
0
repos/DirectXShaderCompiler/tools/clang/include/clang/StaticAnalyzer/Core
repos/DirectXShaderCompiler/tools/clang/include/clang/StaticAnalyzer/Core/PathSensitive/SubEngine.h
//== SubEngine.h - Interface of the subengine of CoreEngine --------*- C++ -*-// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines the interface of a subengine of the CoreEngine. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_SUBENGINE_H #define LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_SUBENGINE_H #include "clang/Analysis/ProgramPoint.h" #include "clang/StaticAnalyzer/Core/PathSensitive/SVals.h" #include "clang/StaticAnalyzer/Core/PathSensitive/Store.h" namespace clang { class CFGBlock; class CFGElement; class LocationContext; class Stmt; namespace ento { struct NodeBuilderContext; class AnalysisManager; class ExplodedNodeSet; class ExplodedNode; class ProgramState; class ProgramStateManager; class BlockCounter; class BranchNodeBuilder; class IndirectGotoNodeBuilder; class SwitchNodeBuilder; class EndOfFunctionNodeBuilder; class NodeBuilderWithSinks; class MemRegion; class SubEngine { virtual void anchor(); public: virtual ~SubEngine() {} virtual ProgramStateRef getInitialState(const LocationContext *InitLoc) = 0; virtual AnalysisManager &getAnalysisManager() = 0; virtual ProgramStateManager &getStateManager() = 0; /// Called by CoreEngine. Used to generate new successor /// nodes by processing the 'effects' of a block-level statement. virtual void processCFGElement(const CFGElement E, ExplodedNode* Pred, unsigned StmtIdx, NodeBuilderContext *Ctx)=0; /// Called by CoreEngine when it starts processing a CFGBlock. The /// SubEngine is expected to populate dstNodes with new nodes representing /// updated analysis state, or generate no nodes at all if it doesn't. virtual void processCFGBlockEntrance(const BlockEdge &L, NodeBuilderWithSinks &nodeBuilder, ExplodedNode *Pred) = 0; /// Called by CoreEngine. Used to generate successor /// nodes by processing the 'effects' of a branch condition. virtual void processBranch(const Stmt *Condition, const Stmt *Term, NodeBuilderContext& BuilderCtx, ExplodedNode *Pred, ExplodedNodeSet &Dst, const CFGBlock *DstT, const CFGBlock *DstF) = 0; /// Called by CoreEngine. /// Used to generate successor nodes for temporary destructors depending /// on whether the corresponding constructor was visited. virtual void processCleanupTemporaryBranch(const CXXBindTemporaryExpr *BTE, NodeBuilderContext &BldCtx, ExplodedNode *Pred, ExplodedNodeSet &Dst, const CFGBlock *DstT, const CFGBlock *DstF) = 0; /// Called by CoreEngine. Used to processing branching behavior /// at static initalizers. virtual void processStaticInitializer(const DeclStmt *DS, NodeBuilderContext& BuilderCtx, ExplodedNode *Pred, ExplodedNodeSet &Dst, const CFGBlock *DstT, const CFGBlock *DstF) = 0; /// Called by CoreEngine. Used to generate successor /// nodes by processing the 'effects' of a computed goto jump. virtual void processIndirectGoto(IndirectGotoNodeBuilder& builder) = 0; /// Called by CoreEngine. Used to generate successor /// nodes by processing the 'effects' of a switch statement. virtual void processSwitch(SwitchNodeBuilder& builder) = 0; /// Called by CoreEngine. Used to generate end-of-path /// nodes when the control reaches the end of a function. virtual void processEndOfFunction(NodeBuilderContext& BC, ExplodedNode *Pred) = 0; // Generate the entry node of the callee. virtual void processCallEnter(CallEnter CE, ExplodedNode *Pred) = 0; // Generate the first post callsite node. virtual void processCallExit(ExplodedNode *Pred) = 0; /// Called by ConstraintManager. Used to call checker-specific /// logic for handling assumptions on symbolic values. virtual ProgramStateRef processAssume(ProgramStateRef state, SVal cond, bool assumption) = 0; /// wantsRegionChangeUpdate - Called by ProgramStateManager to determine if a /// region change should trigger a processRegionChanges update. virtual bool wantsRegionChangeUpdate(ProgramStateRef state) = 0; /// processRegionChanges - Called by ProgramStateManager whenever a change is /// made to the store. Used to update checkers that track region values. virtual ProgramStateRef processRegionChanges(ProgramStateRef state, const InvalidatedSymbols *invalidated, ArrayRef<const MemRegion *> ExplicitRegions, ArrayRef<const MemRegion *> Regions, const CallEvent *Call) = 0; inline ProgramStateRef processRegionChange(ProgramStateRef state, const MemRegion* MR) { return processRegionChanges(state, nullptr, MR, MR, nullptr); } virtual ProgramStateRef processPointerEscapedOnBind(ProgramStateRef State, SVal Loc, SVal Val) = 0; virtual ProgramStateRef notifyCheckersOfPointerEscape(ProgramStateRef State, const InvalidatedSymbols *Invalidated, ArrayRef<const MemRegion *> ExplicitRegions, ArrayRef<const MemRegion *> Regions, const CallEvent *Call, RegionAndSymbolInvalidationTraits &HTraits) = 0; /// printState - Called by ProgramStateManager to print checker-specific data. virtual void printState(raw_ostream &Out, ProgramStateRef State, const char *NL, const char *Sep) = 0; /// Called by CoreEngine when the analysis worklist is either empty or the // maximum number of analysis steps have been reached. virtual void processEndWorklist(bool hasWorkRemaining) = 0; }; } // end GR namespace } // end clang namespace #endif
0
repos/DirectXShaderCompiler/tools/clang/include/clang/StaticAnalyzer/Core
repos/DirectXShaderCompiler/tools/clang/include/clang/StaticAnalyzer/Core/PathSensitive/SymbolManager.h
//== SymbolManager.h - Management of Symbolic Values ------------*- C++ -*--==// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines SymbolManager, a class that manages symbolic values // created for use by ExprEngine and related classes. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_SYMBOLMANAGER_H #define LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_SYMBOLMANAGER_H #include "clang/AST/Decl.h" #include "clang/AST/Expr.h" #include "clang/Analysis/AnalysisContext.h" #include "clang/Basic/LLVM.h" #include "clang/StaticAnalyzer/Core/PathSensitive/StoreRef.h" #include "llvm/ADT/DenseMap.h" #include "llvm/ADT/DenseSet.h" #include "llvm/ADT/FoldingSet.h" #include "llvm/Support/Allocator.h" #include "llvm/Support/DataTypes.h" namespace clang { class ASTContext; class StackFrameContext; namespace ento { class BasicValueFactory; class MemRegion; class SubRegion; class TypedValueRegion; class VarRegion; /// \brief Symbolic value. These values used to capture symbolic execution of /// the program. class SymExpr : public llvm::FoldingSetNode { virtual void anchor(); public: enum Kind { RegionValueKind, ConjuredKind, DerivedKind, ExtentKind, MetadataKind, BEGIN_SYMBOLS = RegionValueKind, END_SYMBOLS = MetadataKind, SymIntKind, IntSymKind, SymSymKind, BEGIN_BINARYSYMEXPRS = SymIntKind, END_BINARYSYMEXPRS = SymSymKind, CastSymbolKind }; private: Kind K; protected: SymExpr(Kind k) : K(k) {} public: virtual ~SymExpr() {} Kind getKind() const { return K; } virtual void dump() const; virtual void dumpToStream(raw_ostream &os) const {} virtual QualType getType() const = 0; virtual void Profile(llvm::FoldingSetNodeID& profile) = 0; /// \brief Iterator over symbols that the current symbol depends on. /// /// For SymbolData, it's the symbol itself; for expressions, it's the /// expression symbol and all the operands in it. Note, SymbolDerived is /// treated as SymbolData - the iterator will NOT visit the parent region. class symbol_iterator { SmallVector<const SymExpr*, 5> itr; void expand(); public: symbol_iterator() {} symbol_iterator(const SymExpr *SE); symbol_iterator &operator++(); const SymExpr* operator*(); bool operator==(const symbol_iterator &X) const; bool operator!=(const symbol_iterator &X) const; }; symbol_iterator symbol_begin() const { return symbol_iterator(this); } static symbol_iterator symbol_end() { return symbol_iterator(); } unsigned computeComplexity() const; }; typedef const SymExpr* SymbolRef; typedef SmallVector<SymbolRef, 2> SymbolRefSmallVectorTy; typedef unsigned SymbolID; /// \brief A symbol representing data which can be stored in a memory location /// (region). class SymbolData : public SymExpr { void anchor() override; const SymbolID Sym; protected: SymbolData(Kind k, SymbolID sym) : SymExpr(k), Sym(sym) {} public: ~SymbolData() override {} SymbolID getSymbolID() const { return Sym; } // Implement isa<T> support. static inline bool classof(const SymExpr *SE) { Kind k = SE->getKind(); return k >= BEGIN_SYMBOLS && k <= END_SYMBOLS; } }; ///\brief A symbol representing the value stored at a MemRegion. class SymbolRegionValue : public SymbolData { const TypedValueRegion *R; public: SymbolRegionValue(SymbolID sym, const TypedValueRegion *r) : SymbolData(RegionValueKind, sym), R(r) {} const TypedValueRegion* getRegion() const { return R; } static void Profile(llvm::FoldingSetNodeID& profile, const TypedValueRegion* R) { profile.AddInteger((unsigned) RegionValueKind); profile.AddPointer(R); } void Profile(llvm::FoldingSetNodeID& profile) override { Profile(profile, R); } void dumpToStream(raw_ostream &os) const override; QualType getType() const override; // Implement isa<T> support. static inline bool classof(const SymExpr *SE) { return SE->getKind() == RegionValueKind; } }; /// A symbol representing the result of an expression in the case when we do /// not know anything about what the expression is. class SymbolConjured : public SymbolData { const Stmt *S; QualType T; unsigned Count; const LocationContext *LCtx; const void *SymbolTag; public: SymbolConjured(SymbolID sym, const Stmt *s, const LocationContext *lctx, QualType t, unsigned count, const void *symbolTag) : SymbolData(ConjuredKind, sym), S(s), T(t), Count(count), LCtx(lctx), SymbolTag(symbolTag) {} const Stmt *getStmt() const { return S; } unsigned getCount() const { return Count; } const void *getTag() const { return SymbolTag; } QualType getType() const override; void dumpToStream(raw_ostream &os) const override; static void Profile(llvm::FoldingSetNodeID& profile, const Stmt *S, QualType T, unsigned Count, const LocationContext *LCtx, const void *SymbolTag) { profile.AddInteger((unsigned) ConjuredKind); profile.AddPointer(S); profile.AddPointer(LCtx); profile.Add(T); profile.AddInteger(Count); profile.AddPointer(SymbolTag); } void Profile(llvm::FoldingSetNodeID& profile) override { Profile(profile, S, T, Count, LCtx, SymbolTag); } // Implement isa<T> support. static inline bool classof(const SymExpr *SE) { return SE->getKind() == ConjuredKind; } }; /// A symbol representing the value of a MemRegion whose parent region has /// symbolic value. class SymbolDerived : public SymbolData { SymbolRef parentSymbol; const TypedValueRegion *R; public: SymbolDerived(SymbolID sym, SymbolRef parent, const TypedValueRegion *r) : SymbolData(DerivedKind, sym), parentSymbol(parent), R(r) {} SymbolRef getParentSymbol() const { return parentSymbol; } const TypedValueRegion *getRegion() const { return R; } QualType getType() const override; void dumpToStream(raw_ostream &os) const override; static void Profile(llvm::FoldingSetNodeID& profile, SymbolRef parent, const TypedValueRegion *r) { profile.AddInteger((unsigned) DerivedKind); profile.AddPointer(r); profile.AddPointer(parent); } void Profile(llvm::FoldingSetNodeID& profile) override { Profile(profile, parentSymbol, R); } // Implement isa<T> support. static inline bool classof(const SymExpr *SE) { return SE->getKind() == DerivedKind; } }; /// SymbolExtent - Represents the extent (size in bytes) of a bounded region. /// Clients should not ask the SymbolManager for a region's extent. Always use /// SubRegion::getExtent instead -- the value returned may not be a symbol. class SymbolExtent : public SymbolData { const SubRegion *R; public: SymbolExtent(SymbolID sym, const SubRegion *r) : SymbolData(ExtentKind, sym), R(r) {} const SubRegion *getRegion() const { return R; } QualType getType() const override; void dumpToStream(raw_ostream &os) const override; static void Profile(llvm::FoldingSetNodeID& profile, const SubRegion *R) { profile.AddInteger((unsigned) ExtentKind); profile.AddPointer(R); } void Profile(llvm::FoldingSetNodeID& profile) override { Profile(profile, R); } // Implement isa<T> support. static inline bool classof(const SymExpr *SE) { return SE->getKind() == ExtentKind; } }; /// SymbolMetadata - Represents path-dependent metadata about a specific region. /// Metadata symbols remain live as long as they are marked as in use before /// dead-symbol sweeping AND their associated regions are still alive. /// Intended for use by checkers. class SymbolMetadata : public SymbolData { const MemRegion* R; const Stmt *S; QualType T; unsigned Count; const void *Tag; public: SymbolMetadata(SymbolID sym, const MemRegion* r, const Stmt *s, QualType t, unsigned count, const void *tag) : SymbolData(MetadataKind, sym), R(r), S(s), T(t), Count(count), Tag(tag) {} const MemRegion *getRegion() const { return R; } const Stmt *getStmt() const { return S; } unsigned getCount() const { return Count; } const void *getTag() const { return Tag; } QualType getType() const override; void dumpToStream(raw_ostream &os) const override; static void Profile(llvm::FoldingSetNodeID& profile, const MemRegion *R, const Stmt *S, QualType T, unsigned Count, const void *Tag) { profile.AddInteger((unsigned) MetadataKind); profile.AddPointer(R); profile.AddPointer(S); profile.Add(T); profile.AddInteger(Count); profile.AddPointer(Tag); } void Profile(llvm::FoldingSetNodeID& profile) override { Profile(profile, R, S, T, Count, Tag); } // Implement isa<T> support. static inline bool classof(const SymExpr *SE) { return SE->getKind() == MetadataKind; } }; /// \brief Represents a cast expression. class SymbolCast : public SymExpr { const SymExpr *Operand; /// Type of the operand. QualType FromTy; /// The type of the result. QualType ToTy; public: SymbolCast(const SymExpr *In, QualType From, QualType To) : SymExpr(CastSymbolKind), Operand(In), FromTy(From), ToTy(To) { } QualType getType() const override { return ToTy; } const SymExpr *getOperand() const { return Operand; } void dumpToStream(raw_ostream &os) const override; static void Profile(llvm::FoldingSetNodeID& ID, const SymExpr *In, QualType From, QualType To) { ID.AddInteger((unsigned) CastSymbolKind); ID.AddPointer(In); ID.Add(From); ID.Add(To); } void Profile(llvm::FoldingSetNodeID& ID) override { Profile(ID, Operand, FromTy, ToTy); } // Implement isa<T> support. static inline bool classof(const SymExpr *SE) { return SE->getKind() == CastSymbolKind; } }; /// \brief Represents a symbolic expression involving a binary operator class BinarySymExpr : public SymExpr { BinaryOperator::Opcode Op; QualType T; protected: BinarySymExpr(Kind k, BinaryOperator::Opcode op, QualType t) : SymExpr(k), Op(op), T(t) {} public: // FIXME: We probably need to make this out-of-line to avoid redundant // generation of virtual functions. QualType getType() const override { return T; } BinaryOperator::Opcode getOpcode() const { return Op; } // Implement isa<T> support. static inline bool classof(const SymExpr *SE) { Kind k = SE->getKind(); return k >= BEGIN_BINARYSYMEXPRS && k <= END_BINARYSYMEXPRS; } }; /// \brief Represents a symbolic expression like 'x' + 3. class SymIntExpr : public BinarySymExpr { const SymExpr *LHS; const llvm::APSInt& RHS; public: SymIntExpr(const SymExpr *lhs, BinaryOperator::Opcode op, const llvm::APSInt& rhs, QualType t) : BinarySymExpr(SymIntKind, op, t), LHS(lhs), RHS(rhs) {} void dumpToStream(raw_ostream &os) const override; const SymExpr *getLHS() const { return LHS; } const llvm::APSInt &getRHS() const { return RHS; } static void Profile(llvm::FoldingSetNodeID& ID, const SymExpr *lhs, BinaryOperator::Opcode op, const llvm::APSInt& rhs, QualType t) { ID.AddInteger((unsigned) SymIntKind); ID.AddPointer(lhs); ID.AddInteger(op); ID.AddPointer(&rhs); ID.Add(t); } void Profile(llvm::FoldingSetNodeID& ID) override { Profile(ID, LHS, getOpcode(), RHS, getType()); } // Implement isa<T> support. static inline bool classof(const SymExpr *SE) { return SE->getKind() == SymIntKind; } }; /// \brief Represents a symbolic expression like 3 - 'x'. class IntSymExpr : public BinarySymExpr { const llvm::APSInt& LHS; const SymExpr *RHS; public: IntSymExpr(const llvm::APSInt& lhs, BinaryOperator::Opcode op, const SymExpr *rhs, QualType t) : BinarySymExpr(IntSymKind, op, t), LHS(lhs), RHS(rhs) {} void dumpToStream(raw_ostream &os) const override; const SymExpr *getRHS() const { return RHS; } const llvm::APSInt &getLHS() const { return LHS; } static void Profile(llvm::FoldingSetNodeID& ID, const llvm::APSInt& lhs, BinaryOperator::Opcode op, const SymExpr *rhs, QualType t) { ID.AddInteger((unsigned) IntSymKind); ID.AddPointer(&lhs); ID.AddInteger(op); ID.AddPointer(rhs); ID.Add(t); } void Profile(llvm::FoldingSetNodeID& ID) override { Profile(ID, LHS, getOpcode(), RHS, getType()); } // Implement isa<T> support. static inline bool classof(const SymExpr *SE) { return SE->getKind() == IntSymKind; } }; /// \brief Represents a symbolic expression like 'x' + 'y'. class SymSymExpr : public BinarySymExpr { const SymExpr *LHS; const SymExpr *RHS; public: SymSymExpr(const SymExpr *lhs, BinaryOperator::Opcode op, const SymExpr *rhs, QualType t) : BinarySymExpr(SymSymKind, op, t), LHS(lhs), RHS(rhs) {} const SymExpr *getLHS() const { return LHS; } const SymExpr *getRHS() const { return RHS; } void dumpToStream(raw_ostream &os) const override; static void Profile(llvm::FoldingSetNodeID& ID, const SymExpr *lhs, BinaryOperator::Opcode op, const SymExpr *rhs, QualType t) { ID.AddInteger((unsigned) SymSymKind); ID.AddPointer(lhs); ID.AddInteger(op); ID.AddPointer(rhs); ID.Add(t); } void Profile(llvm::FoldingSetNodeID& ID) override { Profile(ID, LHS, getOpcode(), RHS, getType()); } // Implement isa<T> support. static inline bool classof(const SymExpr *SE) { return SE->getKind() == SymSymKind; } }; class SymbolManager { typedef llvm::FoldingSet<SymExpr> DataSetTy; typedef llvm::DenseMap<SymbolRef, SymbolRefSmallVectorTy*> SymbolDependTy; DataSetTy DataSet; /// Stores the extra dependencies between symbols: the data should be kept /// alive as long as the key is live. SymbolDependTy SymbolDependencies; unsigned SymbolCounter; llvm::BumpPtrAllocator& BPAlloc; BasicValueFactory &BV; ASTContext &Ctx; public: SymbolManager(ASTContext &ctx, BasicValueFactory &bv, llvm::BumpPtrAllocator& bpalloc) : SymbolDependencies(16), SymbolCounter(0), BPAlloc(bpalloc), BV(bv), Ctx(ctx) {} ~SymbolManager(); static bool canSymbolicate(QualType T); /// \brief Make a unique symbol for MemRegion R according to its kind. const SymbolRegionValue* getRegionValueSymbol(const TypedValueRegion* R); const SymbolConjured* conjureSymbol(const Stmt *E, const LocationContext *LCtx, QualType T, unsigned VisitCount, const void *SymbolTag = nullptr); const SymbolConjured* conjureSymbol(const Expr *E, const LocationContext *LCtx, unsigned VisitCount, const void *SymbolTag = nullptr) { return conjureSymbol(E, LCtx, E->getType(), VisitCount, SymbolTag); } const SymbolDerived *getDerivedSymbol(SymbolRef parentSymbol, const TypedValueRegion *R); const SymbolExtent *getExtentSymbol(const SubRegion *R); /// \brief Creates a metadata symbol associated with a specific region. /// /// VisitCount can be used to differentiate regions corresponding to /// different loop iterations, thus, making the symbol path-dependent. const SymbolMetadata *getMetadataSymbol(const MemRegion *R, const Stmt *S, QualType T, unsigned VisitCount, const void *SymbolTag = nullptr); const SymbolCast* getCastSymbol(const SymExpr *Operand, QualType From, QualType To); const SymIntExpr *getSymIntExpr(const SymExpr *lhs, BinaryOperator::Opcode op, const llvm::APSInt& rhs, QualType t); const SymIntExpr *getSymIntExpr(const SymExpr &lhs, BinaryOperator::Opcode op, const llvm::APSInt& rhs, QualType t) { return getSymIntExpr(&lhs, op, rhs, t); } const IntSymExpr *getIntSymExpr(const llvm::APSInt& lhs, BinaryOperator::Opcode op, const SymExpr *rhs, QualType t); const SymSymExpr *getSymSymExpr(const SymExpr *lhs, BinaryOperator::Opcode op, const SymExpr *rhs, QualType t); QualType getType(const SymExpr *SE) const { return SE->getType(); } /// \brief Add artificial symbol dependency. /// /// The dependent symbol should stay alive as long as the primary is alive. void addSymbolDependency(const SymbolRef Primary, const SymbolRef Dependent); const SymbolRefSmallVectorTy *getDependentSymbols(const SymbolRef Primary); ASTContext &getContext() { return Ctx; } BasicValueFactory &getBasicVals() { return BV; } }; /// \brief A class responsible for cleaning up unused symbols. class SymbolReaper { enum SymbolStatus { NotProcessed, HaveMarkedDependents }; typedef llvm::DenseSet<SymbolRef> SymbolSetTy; typedef llvm::DenseMap<SymbolRef, SymbolStatus> SymbolMapTy; typedef llvm::DenseSet<const MemRegion *> RegionSetTy; SymbolMapTy TheLiving; SymbolSetTy MetadataInUse; SymbolSetTy TheDead; RegionSetTy RegionRoots; const StackFrameContext *LCtx; const Stmt *Loc; SymbolManager& SymMgr; StoreRef reapedStore; llvm::DenseMap<const MemRegion *, unsigned> includedRegionCache; public: /// \brief Construct a reaper object, which removes everything which is not /// live before we execute statement s in the given location context. /// /// If the statement is NULL, everything is this and parent contexts is /// considered live. /// If the stack frame context is NULL, everything on stack is considered /// dead. SymbolReaper(const StackFrameContext *Ctx, const Stmt *s, SymbolManager& symmgr, StoreManager &storeMgr) : LCtx(Ctx), Loc(s), SymMgr(symmgr), reapedStore(nullptr, storeMgr) {} const LocationContext *getLocationContext() const { return LCtx; } bool isLive(SymbolRef sym); bool isLiveRegion(const MemRegion *region); bool isLive(const Stmt *ExprVal, const LocationContext *LCtx) const; bool isLive(const VarRegion *VR, bool includeStoreBindings = false) const; /// \brief Unconditionally marks a symbol as live. /// /// This should never be /// used by checkers, only by the state infrastructure such as the store and /// environment. Checkers should instead use metadata symbols and markInUse. void markLive(SymbolRef sym); /// \brief Marks a symbol as important to a checker. /// /// For metadata symbols, /// this will keep the symbol alive as long as its associated region is also /// live. For other symbols, this has no effect; checkers are not permitted /// to influence the life of other symbols. This should be used before any /// symbol marking has occurred, i.e. in the MarkLiveSymbols callback. void markInUse(SymbolRef sym); /// \brief If a symbol is known to be live, marks the symbol as live. /// /// Otherwise, if the symbol cannot be proven live, it is marked as dead. /// Returns true if the symbol is dead, false if live. bool maybeDead(SymbolRef sym); typedef SymbolSetTy::const_iterator dead_iterator; dead_iterator dead_begin() const { return TheDead.begin(); } dead_iterator dead_end() const { return TheDead.end(); } bool hasDeadSymbols() const { return !TheDead.empty(); } typedef RegionSetTy::const_iterator region_iterator; region_iterator region_begin() const { return RegionRoots.begin(); } region_iterator region_end() const { return RegionRoots.end(); } /// \brief Returns whether or not a symbol has been confirmed dead. /// /// This should only be called once all marking of dead symbols has completed. /// (For checkers, this means only in the evalDeadSymbols callback.) bool isDead(SymbolRef sym) const { return TheDead.count(sym); } void markLive(const MemRegion *region); /// \brief Set to the value of the symbolic store after /// StoreManager::removeDeadBindings has been called. void setReapedStore(StoreRef st) { reapedStore = st; } private: /// Mark the symbols dependent on the input symbol as live. void markDependentsLive(SymbolRef sym); }; class SymbolVisitor { public: /// \brief A visitor method invoked by ProgramStateManager::scanReachableSymbols. /// /// The method returns \c true if symbols should continue be scanned and \c /// false otherwise. virtual bool VisitSymbol(SymbolRef sym) = 0; virtual bool VisitMemRegion(const MemRegion *region) { return true; } virtual ~SymbolVisitor(); }; } // end GR namespace } // end clang namespace namespace llvm { static inline raw_ostream &operator<<(raw_ostream &os, const clang::ento::SymExpr *SE) { SE->dumpToStream(os); return os; } } // end llvm namespace #endif
0
repos/DirectXShaderCompiler/tools/clang/include/clang/StaticAnalyzer/Core
repos/DirectXShaderCompiler/tools/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h
//== ProgramState.h - Path-sensitive "State" for tracking values -*- C++ -*--=// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines the state of the program along the analysisa path. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_PROGRAMSTATE_H #define LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_PROGRAMSTATE_H #include "clang/Basic/LLVM.h" #include "clang/StaticAnalyzer/Core/PathSensitive/ConstraintManager.h" #include "clang/StaticAnalyzer/Core/PathSensitive/DynamicTypeInfo.h" #include "clang/StaticAnalyzer/Core/PathSensitive/Environment.h" #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState_Fwd.h" #include "clang/StaticAnalyzer/Core/PathSensitive/SValBuilder.h" #include "clang/StaticAnalyzer/Core/PathSensitive/Store.h" #include "clang/StaticAnalyzer/Core/PathSensitive/TaintTag.h" #include "llvm/ADT/FoldingSet.h" #include "llvm/ADT/ImmutableMap.h" #include "llvm/ADT/PointerIntPair.h" #include "llvm/Support/Allocator.h" namespace llvm { class APSInt; } namespace clang { class ASTContext; namespace ento { class CallEvent; class CallEventManager; typedef std::unique_ptr<ConstraintManager>(*ConstraintManagerCreator)( ProgramStateManager &, SubEngine *); typedef std::unique_ptr<StoreManager>(*StoreManagerCreator)( ProgramStateManager &); //===----------------------------------------------------------------------===// // ProgramStateTrait - Traits used by the Generic Data Map of a ProgramState. //===----------------------------------------------------------------------===// template <typename T> struct ProgramStatePartialTrait; template <typename T> struct ProgramStateTrait { typedef typename T::data_type data_type; static inline void *MakeVoidPtr(data_type D) { return (void*) D; } static inline data_type MakeData(void *const* P) { return P ? (data_type) *P : (data_type) 0; } }; /// \class ProgramState /// ProgramState - This class encapsulates: /// /// 1. A mapping from expressions to values (Environment) /// 2. A mapping from locations to values (Store) /// 3. Constraints on symbolic values (GenericDataMap) /// /// Together these represent the "abstract state" of a program. /// /// ProgramState is intended to be used as a functional object; that is, /// once it is created and made "persistent" in a FoldingSet, its /// values will never change. class ProgramState : public llvm::FoldingSetNode { public: typedef llvm::ImmutableSet<llvm::APSInt*> IntSetTy; typedef llvm::ImmutableMap<void*, void*> GenericDataMap; private: void operator=(const ProgramState& R) = delete; friend class ProgramStateManager; friend class ExplodedGraph; friend class ExplodedNode; ProgramStateManager *stateMgr; Environment Env; // Maps a Stmt to its current SVal. Store store; // Maps a location to its current value. GenericDataMap GDM; // Custom data stored by a client of this class. unsigned refCount; /// makeWithStore - Return a ProgramState with the same values as the current /// state with the exception of using the specified Store. ProgramStateRef makeWithStore(const StoreRef &store) const; void setStore(const StoreRef &storeRef); public: /// This ctor is used when creating the first ProgramState object. ProgramState(ProgramStateManager *mgr, const Environment& env, StoreRef st, GenericDataMap gdm); /// Copy ctor - We must explicitly define this or else the "Next" ptr /// in FoldingSetNode will also get copied. ProgramState(const ProgramState &RHS); ~ProgramState(); /// Return the ProgramStateManager associated with this state. ProgramStateManager &getStateManager() const { return *stateMgr; } /// Return the ConstraintManager. ConstraintManager &getConstraintManager() const; /// getEnvironment - Return the environment associated with this state. /// The environment is the mapping from expressions to values. const Environment& getEnvironment() const { return Env; } /// Return the store associated with this state. The store /// is a mapping from locations to values. Store getStore() const { return store; } /// getGDM - Return the generic data map associated with this state. GenericDataMap getGDM() const { return GDM; } void setGDM(GenericDataMap gdm) { GDM = gdm; } /// Profile - Profile the contents of a ProgramState object for use in a /// FoldingSet. Two ProgramState objects are considered equal if they /// have the same Environment, Store, and GenericDataMap. static void Profile(llvm::FoldingSetNodeID& ID, const ProgramState *V) { V->Env.Profile(ID); ID.AddPointer(V->store); V->GDM.Profile(ID); } /// Profile - Used to profile the contents of this object for inclusion /// in a FoldingSet. void Profile(llvm::FoldingSetNodeID& ID) const { Profile(ID, this); } BasicValueFactory &getBasicVals() const; SymbolManager &getSymbolManager() const; //==---------------------------------------------------------------------==// // Constraints on values. //==---------------------------------------------------------------------==// // // Each ProgramState records constraints on symbolic values. These constraints // are managed using the ConstraintManager associated with a ProgramStateManager. // As constraints gradually accrue on symbolic values, added constraints // may conflict and indicate that a state is infeasible (as no real values // could satisfy all the constraints). This is the principal mechanism // for modeling path-sensitivity in ExprEngine/ProgramState. // // Various "assume" methods form the interface for adding constraints to // symbolic values. A call to 'assume' indicates an assumption being placed // on one or symbolic values. 'assume' methods take the following inputs: // // (1) A ProgramState object representing the current state. // // (2) The assumed constraint (which is specific to a given "assume" method). // // (3) A binary value "Assumption" that indicates whether the constraint is // assumed to be true or false. // // The output of "assume*" is a new ProgramState object with the added constraints. // If no new state is feasible, NULL is returned. // /// Assumes that the value of \p cond is zero (if \p assumption is "false") /// or non-zero (if \p assumption is "true"). /// /// This returns a new state with the added constraint on \p cond. /// If no new state is feasible, NULL is returned. ProgramStateRef assume(DefinedOrUnknownSVal cond, bool assumption) const; /// Assumes both "true" and "false" for \p cond, and returns both /// corresponding states (respectively). /// /// This is more efficient than calling assume() twice. Note that one (but not /// both) of the returned states may be NULL. std::pair<ProgramStateRef, ProgramStateRef> assume(DefinedOrUnknownSVal cond) const; ProgramStateRef assumeInBound(DefinedOrUnknownSVal idx, DefinedOrUnknownSVal upperBound, bool assumption, QualType IndexType = QualType()) const; /// \brief Check if the given SVal is constrained to zero or is a zero /// constant. ConditionTruthVal isNull(SVal V) const; /// Utility method for getting regions. const VarRegion* getRegion(const VarDecl *D, const LocationContext *LC) const; //==---------------------------------------------------------------------==// // Binding and retrieving values to/from the environment and symbolic store. //==---------------------------------------------------------------------==// /// Create a new state by binding the value 'V' to the statement 'S' in the /// state's environment. ProgramStateRef BindExpr(const Stmt *S, const LocationContext *LCtx, SVal V, bool Invalidate = true) const; ProgramStateRef bindLoc(Loc location, SVal V, bool notifyChanges = true) const; ProgramStateRef bindLoc(SVal location, SVal V) const; ProgramStateRef bindDefault(SVal loc, SVal V) const; ProgramStateRef killBinding(Loc LV) const; /// \brief Returns the state with bindings for the given regions /// cleared from the store. /// /// Optionally invalidates global regions as well. /// /// \param Regions the set of regions to be invalidated. /// \param E the expression that caused the invalidation. /// \param BlockCount The number of times the current basic block has been // visited. /// \param CausesPointerEscape the flag is set to true when /// the invalidation entails escape of a symbol (representing a /// pointer). For example, due to it being passed as an argument in a /// call. /// \param IS the set of invalidated symbols. /// \param Call if non-null, the invalidated regions represent parameters to /// the call and should be considered directly invalidated. /// \param ITraits information about special handling for a particular /// region/symbol. ProgramStateRef invalidateRegions(ArrayRef<const MemRegion *> Regions, const Expr *E, unsigned BlockCount, const LocationContext *LCtx, bool CausesPointerEscape, InvalidatedSymbols *IS = nullptr, const CallEvent *Call = nullptr, RegionAndSymbolInvalidationTraits *ITraits = nullptr) const; ProgramStateRef invalidateRegions(ArrayRef<SVal> Regions, const Expr *E, unsigned BlockCount, const LocationContext *LCtx, bool CausesPointerEscape, InvalidatedSymbols *IS = nullptr, const CallEvent *Call = nullptr, RegionAndSymbolInvalidationTraits *ITraits = nullptr) const; /// enterStackFrame - Returns the state for entry to the given stack frame, /// preserving the current state. ProgramStateRef enterStackFrame(const CallEvent &Call, const StackFrameContext *CalleeCtx) const; /// Get the lvalue for a variable reference. Loc getLValue(const VarDecl *D, const LocationContext *LC) const; Loc getLValue(const CompoundLiteralExpr *literal, const LocationContext *LC) const; /// Get the lvalue for an ivar reference. SVal getLValue(const ObjCIvarDecl *decl, SVal base) const; /// Get the lvalue for a field reference. SVal getLValue(const FieldDecl *decl, SVal Base) const; /// Get the lvalue for an indirect field reference. SVal getLValue(const IndirectFieldDecl *decl, SVal Base) const; /// Get the lvalue for an array index. SVal getLValue(QualType ElementType, SVal Idx, SVal Base) const; /// Returns the SVal bound to the statement 'S' in the state's environment. SVal getSVal(const Stmt *S, const LocationContext *LCtx) const; SVal getSValAsScalarOrLoc(const Stmt *Ex, const LocationContext *LCtx) const; /// \brief Return the value bound to the specified location. /// Returns UnknownVal() if none found. SVal getSVal(Loc LV, QualType T = QualType()) const; /// Returns the "raw" SVal bound to LV before any value simplfication. SVal getRawSVal(Loc LV, QualType T= QualType()) const; /// \brief Return the value bound to the specified location. /// Returns UnknownVal() if none found. SVal getSVal(const MemRegion* R) const; SVal getSValAsScalarOrLoc(const MemRegion *R) const; /// \brief Visits the symbols reachable from the given SVal using the provided /// SymbolVisitor. /// /// This is a convenience API. Consider using ScanReachableSymbols class /// directly when making multiple scans on the same state with the same /// visitor to avoid repeated initialization cost. /// \sa ScanReachableSymbols bool scanReachableSymbols(SVal val, SymbolVisitor& visitor) const; /// \brief Visits the symbols reachable from the SVals in the given range /// using the provided SymbolVisitor. bool scanReachableSymbols(const SVal *I, const SVal *E, SymbolVisitor &visitor) const; /// \brief Visits the symbols reachable from the regions in the given /// MemRegions range using the provided SymbolVisitor. bool scanReachableSymbols(const MemRegion * const *I, const MemRegion * const *E, SymbolVisitor &visitor) const; template <typename CB> CB scanReachableSymbols(SVal val) const; template <typename CB> CB scanReachableSymbols(const SVal *beg, const SVal *end) const; template <typename CB> CB scanReachableSymbols(const MemRegion * const *beg, const MemRegion * const *end) const; /// Create a new state in which the statement is marked as tainted. ProgramStateRef addTaint(const Stmt *S, const LocationContext *LCtx, TaintTagType Kind = TaintTagGeneric) const; /// Create a new state in which the symbol is marked as tainted. ProgramStateRef addTaint(SymbolRef S, TaintTagType Kind = TaintTagGeneric) const; /// Create a new state in which the region symbol is marked as tainted. ProgramStateRef addTaint(const MemRegion *R, TaintTagType Kind = TaintTagGeneric) const; /// Check if the statement is tainted in the current state. bool isTainted(const Stmt *S, const LocationContext *LCtx, TaintTagType Kind = TaintTagGeneric) const; bool isTainted(SVal V, TaintTagType Kind = TaintTagGeneric) const; bool isTainted(SymbolRef Sym, TaintTagType Kind = TaintTagGeneric) const; bool isTainted(const MemRegion *Reg, TaintTagType Kind=TaintTagGeneric) const; /// \brief Get dynamic type information for a region. DynamicTypeInfo getDynamicTypeInfo(const MemRegion *Reg) const; /// \brief Set dynamic type information of the region; return the new state. ProgramStateRef setDynamicTypeInfo(const MemRegion *Reg, DynamicTypeInfo NewTy) const; /// \brief Set dynamic type information of the region; return the new state. ProgramStateRef setDynamicTypeInfo(const MemRegion *Reg, QualType NewTy, bool CanBeSubClassed = true) const { return setDynamicTypeInfo(Reg, DynamicTypeInfo(NewTy, CanBeSubClassed)); } //==---------------------------------------------------------------------==// // Accessing the Generic Data Map (GDM). //==---------------------------------------------------------------------==// void *const* FindGDM(void *K) const; template<typename T> ProgramStateRef add(typename ProgramStateTrait<T>::key_type K) const; template <typename T> typename ProgramStateTrait<T>::data_type get() const { return ProgramStateTrait<T>::MakeData(FindGDM(ProgramStateTrait<T>::GDMIndex())); } template<typename T> typename ProgramStateTrait<T>::lookup_type get(typename ProgramStateTrait<T>::key_type key) const { void *const* d = FindGDM(ProgramStateTrait<T>::GDMIndex()); return ProgramStateTrait<T>::Lookup(ProgramStateTrait<T>::MakeData(d), key); } template <typename T> typename ProgramStateTrait<T>::context_type get_context() const; template<typename T> ProgramStateRef remove(typename ProgramStateTrait<T>::key_type K) const; template<typename T> ProgramStateRef remove(typename ProgramStateTrait<T>::key_type K, typename ProgramStateTrait<T>::context_type C) const; template <typename T> ProgramStateRef remove() const; template<typename T> ProgramStateRef set(typename ProgramStateTrait<T>::data_type D) const; template<typename T> ProgramStateRef set(typename ProgramStateTrait<T>::key_type K, typename ProgramStateTrait<T>::value_type E) const; template<typename T> ProgramStateRef set(typename ProgramStateTrait<T>::key_type K, typename ProgramStateTrait<T>::value_type E, typename ProgramStateTrait<T>::context_type C) const; template<typename T> bool contains(typename ProgramStateTrait<T>::key_type key) const { void *const* d = FindGDM(ProgramStateTrait<T>::GDMIndex()); return ProgramStateTrait<T>::Contains(ProgramStateTrait<T>::MakeData(d), key); } // Pretty-printing. void print(raw_ostream &Out, const char *nl = "\n", const char *sep = "") const; void printDOT(raw_ostream &Out) const; void printTaint(raw_ostream &Out, const char *nl = "\n", const char *sep = "") const; void dump() const; void dumpTaint() const; private: friend void ProgramStateRetain(const ProgramState *state); friend void ProgramStateRelease(const ProgramState *state); /// \sa invalidateValues() /// \sa invalidateRegions() ProgramStateRef invalidateRegionsImpl(ArrayRef<SVal> Values, const Expr *E, unsigned BlockCount, const LocationContext *LCtx, bool ResultsInSymbolEscape, InvalidatedSymbols *IS, RegionAndSymbolInvalidationTraits *HTraits, const CallEvent *Call) const; }; //===----------------------------------------------------------------------===// // ProgramStateManager - Factory object for ProgramStates. //===----------------------------------------------------------------------===// class ProgramStateManager { friend class ProgramState; friend void ProgramStateRelease(const ProgramState *state); private: /// Eng - The SubEngine that owns this state manager. SubEngine *Eng; /* Can be null. */ EnvironmentManager EnvMgr; std::unique_ptr<StoreManager> StoreMgr; std::unique_ptr<ConstraintManager> ConstraintMgr; ProgramState::GenericDataMap::Factory GDMFactory; typedef llvm::DenseMap<void*,std::pair<void*,void (*)(void*)> > GDMContextsTy; GDMContextsTy GDMContexts; /// StateSet - FoldingSet containing all the states created for analyzing /// a particular function. This is used to unique states. llvm::FoldingSet<ProgramState> StateSet; /// Object that manages the data for all created SVals. std::unique_ptr<SValBuilder> svalBuilder; /// Manages memory for created CallEvents. std::unique_ptr<CallEventManager> CallEventMgr; /// A BumpPtrAllocator to allocate states. llvm::BumpPtrAllocator &Alloc; /// A vector of ProgramStates that we can reuse. std::vector<ProgramState *> freeStates; public: ProgramStateManager(ASTContext &Ctx, StoreManagerCreator CreateStoreManager, ConstraintManagerCreator CreateConstraintManager, llvm::BumpPtrAllocator& alloc, SubEngine *subeng); ~ProgramStateManager(); ProgramStateRef getInitialState(const LocationContext *InitLoc); ASTContext &getContext() { return svalBuilder->getContext(); } const ASTContext &getContext() const { return svalBuilder->getContext(); } BasicValueFactory &getBasicVals() { return svalBuilder->getBasicValueFactory(); } SValBuilder &getSValBuilder() { return *svalBuilder; } SymbolManager &getSymbolManager() { return svalBuilder->getSymbolManager(); } const SymbolManager &getSymbolManager() const { return svalBuilder->getSymbolManager(); } llvm::BumpPtrAllocator& getAllocator() { return Alloc; } MemRegionManager& getRegionManager() { return svalBuilder->getRegionManager(); } const MemRegionManager& getRegionManager() const { return svalBuilder->getRegionManager(); } CallEventManager &getCallEventManager() { return *CallEventMgr; } StoreManager& getStoreManager() { return *StoreMgr; } ConstraintManager& getConstraintManager() { return *ConstraintMgr; } SubEngine* getOwningEngine() { return Eng; } ProgramStateRef removeDeadBindings(ProgramStateRef St, const StackFrameContext *LCtx, SymbolReaper& SymReaper); public: SVal ArrayToPointer(Loc Array, QualType ElementTy) { return StoreMgr->ArrayToPointer(Array, ElementTy); } // Methods that manipulate the GDM. ProgramStateRef addGDM(ProgramStateRef St, void *Key, void *Data); ProgramStateRef removeGDM(ProgramStateRef state, void *Key); // Methods that query & manipulate the Store. void iterBindings(ProgramStateRef state, StoreManager::BindingsHandler& F) { StoreMgr->iterBindings(state->getStore(), F); } ProgramStateRef getPersistentState(ProgramState &Impl); ProgramStateRef getPersistentStateWithGDM(ProgramStateRef FromState, ProgramStateRef GDMState); bool haveEqualEnvironments(ProgramStateRef S1, ProgramStateRef S2) { return S1->Env == S2->Env; } bool haveEqualStores(ProgramStateRef S1, ProgramStateRef S2) { return S1->store == S2->store; } //==---------------------------------------------------------------------==// // Generic Data Map methods. //==---------------------------------------------------------------------==// // // ProgramStateManager and ProgramState support a "generic data map" that allows // different clients of ProgramState objects to embed arbitrary data within a // ProgramState object. The generic data map is essentially an immutable map // from a "tag" (that acts as the "key" for a client) and opaque values. // Tags/keys and values are simply void* values. The typical way that clients // generate unique tags are by taking the address of a static variable. // Clients are responsible for ensuring that data values referred to by a // the data pointer are immutable (and thus are essentially purely functional // data). // // The templated methods below use the ProgramStateTrait<T> class // to resolve keys into the GDM and to return data values to clients. // // Trait based GDM dispatch. template <typename T> ProgramStateRef set(ProgramStateRef st, typename ProgramStateTrait<T>::data_type D) { return addGDM(st, ProgramStateTrait<T>::GDMIndex(), ProgramStateTrait<T>::MakeVoidPtr(D)); } template<typename T> ProgramStateRef set(ProgramStateRef st, typename ProgramStateTrait<T>::key_type K, typename ProgramStateTrait<T>::value_type V, typename ProgramStateTrait<T>::context_type C) { return addGDM(st, ProgramStateTrait<T>::GDMIndex(), ProgramStateTrait<T>::MakeVoidPtr(ProgramStateTrait<T>::Set(st->get<T>(), K, V, C))); } template <typename T> ProgramStateRef add(ProgramStateRef st, typename ProgramStateTrait<T>::key_type K, typename ProgramStateTrait<T>::context_type C) { return addGDM(st, ProgramStateTrait<T>::GDMIndex(), ProgramStateTrait<T>::MakeVoidPtr(ProgramStateTrait<T>::Add(st->get<T>(), K, C))); } template <typename T> ProgramStateRef remove(ProgramStateRef st, typename ProgramStateTrait<T>::key_type K, typename ProgramStateTrait<T>::context_type C) { return addGDM(st, ProgramStateTrait<T>::GDMIndex(), ProgramStateTrait<T>::MakeVoidPtr(ProgramStateTrait<T>::Remove(st->get<T>(), K, C))); } template <typename T> ProgramStateRef remove(ProgramStateRef st) { return removeGDM(st, ProgramStateTrait<T>::GDMIndex()); } void *FindGDMContext(void *index, void *(*CreateContext)(llvm::BumpPtrAllocator&), void (*DeleteContext)(void*)); template <typename T> typename ProgramStateTrait<T>::context_type get_context() { void *p = FindGDMContext(ProgramStateTrait<T>::GDMIndex(), ProgramStateTrait<T>::CreateContext, ProgramStateTrait<T>::DeleteContext); return ProgramStateTrait<T>::MakeContext(p); } void EndPath(ProgramStateRef St) { ConstraintMgr->EndPath(St); } }; //===----------------------------------------------------------------------===// // Out-of-line method definitions for ProgramState. // // /////////////////////////////////////////////////////////////////////////////// inline ConstraintManager &ProgramState::getConstraintManager() const { return stateMgr->getConstraintManager(); } inline const VarRegion* ProgramState::getRegion(const VarDecl *D, const LocationContext *LC) const { return getStateManager().getRegionManager().getVarRegion(D, LC); } inline ProgramStateRef ProgramState::assume(DefinedOrUnknownSVal Cond, bool Assumption) const { if (Cond.isUnknown()) return this; return getStateManager().ConstraintMgr ->assume(this, Cond.castAs<DefinedSVal>(), Assumption); } inline std::pair<ProgramStateRef , ProgramStateRef > ProgramState::assume(DefinedOrUnknownSVal Cond) const { if (Cond.isUnknown()) return std::make_pair(this, this); return getStateManager().ConstraintMgr ->assumeDual(this, Cond.castAs<DefinedSVal>()); } inline ProgramStateRef ProgramState::bindLoc(SVal LV, SVal V) const { if (Optional<Loc> L = LV.getAs<Loc>()) return bindLoc(*L, V); return this; } inline Loc ProgramState::getLValue(const VarDecl *VD, const LocationContext *LC) const { return getStateManager().StoreMgr->getLValueVar(VD, LC); } inline Loc ProgramState::getLValue(const CompoundLiteralExpr *literal, const LocationContext *LC) const { return getStateManager().StoreMgr->getLValueCompoundLiteral(literal, LC); } inline SVal ProgramState::getLValue(const ObjCIvarDecl *D, SVal Base) const { return getStateManager().StoreMgr->getLValueIvar(D, Base); } inline SVal ProgramState::getLValue(const FieldDecl *D, SVal Base) const { return getStateManager().StoreMgr->getLValueField(D, Base); } inline SVal ProgramState::getLValue(const IndirectFieldDecl *D, SVal Base) const { StoreManager &SM = *getStateManager().StoreMgr; for (const auto *I : D->chain()) { Base = SM.getLValueField(cast<FieldDecl>(I), Base); } return Base; } inline SVal ProgramState::getLValue(QualType ElementType, SVal Idx, SVal Base) const{ if (Optional<NonLoc> N = Idx.getAs<NonLoc>()) return getStateManager().StoreMgr->getLValueElement(ElementType, *N, Base); return UnknownVal(); } inline SVal ProgramState::getSVal(const Stmt *Ex, const LocationContext *LCtx) const{ return Env.getSVal(EnvironmentEntry(Ex, LCtx), *getStateManager().svalBuilder); } inline SVal ProgramState::getSValAsScalarOrLoc(const Stmt *S, const LocationContext *LCtx) const { if (const Expr *Ex = dyn_cast<Expr>(S)) { QualType T = Ex->getType(); if (Ex->isGLValue() || Loc::isLocType(T) || T->isIntegralOrEnumerationType()) return getSVal(S, LCtx); } return UnknownVal(); } inline SVal ProgramState::getRawSVal(Loc LV, QualType T) const { return getStateManager().StoreMgr->getBinding(getStore(), LV, T); } inline SVal ProgramState::getSVal(const MemRegion* R) const { return getStateManager().StoreMgr->getBinding(getStore(), loc::MemRegionVal(R)); } inline BasicValueFactory &ProgramState::getBasicVals() const { return getStateManager().getBasicVals(); } inline SymbolManager &ProgramState::getSymbolManager() const { return getStateManager().getSymbolManager(); } template<typename T> ProgramStateRef ProgramState::add(typename ProgramStateTrait<T>::key_type K) const { return getStateManager().add<T>(this, K, get_context<T>()); } template <typename T> typename ProgramStateTrait<T>::context_type ProgramState::get_context() const { return getStateManager().get_context<T>(); } template<typename T> ProgramStateRef ProgramState::remove(typename ProgramStateTrait<T>::key_type K) const { return getStateManager().remove<T>(this, K, get_context<T>()); } template<typename T> ProgramStateRef ProgramState::remove(typename ProgramStateTrait<T>::key_type K, typename ProgramStateTrait<T>::context_type C) const { return getStateManager().remove<T>(this, K, C); } template <typename T> ProgramStateRef ProgramState::remove() const { return getStateManager().remove<T>(this); } template<typename T> ProgramStateRef ProgramState::set(typename ProgramStateTrait<T>::data_type D) const { return getStateManager().set<T>(this, D); } template<typename T> ProgramStateRef ProgramState::set(typename ProgramStateTrait<T>::key_type K, typename ProgramStateTrait<T>::value_type E) const { return getStateManager().set<T>(this, K, E, get_context<T>()); } template<typename T> ProgramStateRef ProgramState::set(typename ProgramStateTrait<T>::key_type K, typename ProgramStateTrait<T>::value_type E, typename ProgramStateTrait<T>::context_type C) const { return getStateManager().set<T>(this, K, E, C); } template <typename CB> CB ProgramState::scanReachableSymbols(SVal val) const { CB cb(this); scanReachableSymbols(val, cb); return cb; } template <typename CB> CB ProgramState::scanReachableSymbols(const SVal *beg, const SVal *end) const { CB cb(this); scanReachableSymbols(beg, end, cb); return cb; } template <typename CB> CB ProgramState::scanReachableSymbols(const MemRegion * const *beg, const MemRegion * const *end) const { CB cb(this); scanReachableSymbols(beg, end, cb); return cb; } /// \class ScanReachableSymbols /// A Utility class that allows to visit the reachable symbols using a custom /// SymbolVisitor. class ScanReachableSymbols { typedef llvm::DenseSet<const void*> VisitedItems; VisitedItems visited; ProgramStateRef state; SymbolVisitor &visitor; public: ScanReachableSymbols(ProgramStateRef st, SymbolVisitor& v) : state(st), visitor(v) {} bool scan(nonloc::LazyCompoundVal val); bool scan(nonloc::CompoundVal val); bool scan(SVal val); bool scan(const MemRegion *R); bool scan(const SymExpr *sym); }; } // end ento namespace } // end clang namespace #endif
0
repos/DirectXShaderCompiler/tools/clang/include/clang/StaticAnalyzer/Core
repos/DirectXShaderCompiler/tools/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CoreEngine.h
//==- CoreEngine.h - Path-Sensitive Dataflow Engine ----------------*- C++ -*-// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines a generic engine for intraprocedural, path-sensitive, // dataflow analysis via graph reachability. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_COREENGINE_H #define LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_COREENGINE_H #include "clang/AST/Expr.h" #include "clang/Analysis/AnalysisContext.h" #include "clang/StaticAnalyzer/Core/PathSensitive/BlockCounter.h" #include "clang/StaticAnalyzer/Core/PathSensitive/ExplodedGraph.h" #include "clang/StaticAnalyzer/Core/PathSensitive/FunctionSummary.h" #include "clang/StaticAnalyzer/Core/PathSensitive/WorkList.h" #include <memory> namespace clang { class ProgramPointTag; namespace ento { class NodeBuilder; // // /////////////////////////////////////////////////////////////////////////////// /// CoreEngine - Implements the core logic of the graph-reachability /// analysis. It traverses the CFG and generates the ExplodedGraph. /// Program "states" are treated as opaque void pointers. /// The template class CoreEngine (which subclasses CoreEngine) /// provides the matching component to the engine that knows the actual types /// for states. Note that this engine only dispatches to transfer functions /// at the statement and block-level. The analyses themselves must implement /// any transfer function logic and the sub-expression level (if any). class CoreEngine { friend struct NodeBuilderContext; friend class NodeBuilder; friend class ExprEngine; friend class CommonNodeBuilder; friend class IndirectGotoNodeBuilder; friend class SwitchNodeBuilder; friend class EndOfFunctionNodeBuilder; public: typedef std::vector<std::pair<BlockEdge, const ExplodedNode*> > BlocksExhausted; typedef std::vector<std::pair<const CFGBlock*, const ExplodedNode*> > BlocksAborted; private: SubEngine& SubEng; /// G - The simulation graph. Each node is a (location,state) pair. mutable ExplodedGraph G; /// WList - A set of queued nodes that need to be processed by the /// worklist algorithm. It is up to the implementation of WList to decide /// the order that nodes are processed. std::unique_ptr<WorkList> WList; /// BCounterFactory - A factory object for created BlockCounter objects. /// These are used to record for key nodes in the ExplodedGraph the /// number of times different CFGBlocks have been visited along a path. BlockCounter::Factory BCounterFactory; /// The locations where we stopped doing work because we visited a location /// too many times. BlocksExhausted blocksExhausted; /// The locations where we stopped because the engine aborted analysis, /// usually because it could not reason about something. BlocksAborted blocksAborted; /// The information about functions shared by the whole translation unit. /// (This data is owned by AnalysisConsumer.) FunctionSummariesTy *FunctionSummaries; void generateNode(const ProgramPoint &Loc, ProgramStateRef State, ExplodedNode *Pred); void HandleBlockEdge(const BlockEdge &E, ExplodedNode *Pred); void HandleBlockEntrance(const BlockEntrance &E, ExplodedNode *Pred); void HandleBlockExit(const CFGBlock *B, ExplodedNode *Pred); void HandlePostStmt(const CFGBlock *B, unsigned StmtIdx, ExplodedNode *Pred); void HandleBranch(const Stmt *Cond, const Stmt *Term, const CFGBlock *B, ExplodedNode *Pred); void HandleCleanupTemporaryBranch(const CXXBindTemporaryExpr *BTE, const CFGBlock *B, ExplodedNode *Pred); /// Handle conditional logic for running static initializers. void HandleStaticInit(const DeclStmt *DS, const CFGBlock *B, ExplodedNode *Pred); private: CoreEngine(const CoreEngine &) = delete; void operator=(const CoreEngine &) = delete; ExplodedNode *generateCallExitBeginNode(ExplodedNode *N); public: /// Construct a CoreEngine object to analyze the provided CFG. CoreEngine(SubEngine &subengine, FunctionSummariesTy *FS) : SubEng(subengine), WList(WorkList::makeDFS()), BCounterFactory(G.getAllocator()), FunctionSummaries(FS) {} /// getGraph - Returns the exploded graph. ExplodedGraph &getGraph() { return G; } /// ExecuteWorkList - Run the worklist algorithm for a maximum number of /// steps. Returns true if there is still simulation state on the worklist. bool ExecuteWorkList(const LocationContext *L, unsigned Steps, ProgramStateRef InitState); /// Returns true if there is still simulation state on the worklist. bool ExecuteWorkListWithInitialState(const LocationContext *L, unsigned Steps, ProgramStateRef InitState, ExplodedNodeSet &Dst); /// Dispatch the work list item based on the given location information. /// Use Pred parameter as the predecessor state. void dispatchWorkItem(ExplodedNode* Pred, ProgramPoint Loc, const WorkListUnit& WU); // Functions for external checking of whether we have unfinished work bool wasBlockAborted() const { return !blocksAborted.empty(); } bool wasBlocksExhausted() const { return !blocksExhausted.empty(); } bool hasWorkRemaining() const { return wasBlocksExhausted() || WList->hasWork() || wasBlockAborted(); } /// Inform the CoreEngine that a basic block was aborted because /// it could not be completely analyzed. void addAbortedBlock(const ExplodedNode *node, const CFGBlock *block) { blocksAborted.push_back(std::make_pair(block, node)); } WorkList *getWorkList() const { return WList.get(); } BlocksExhausted::const_iterator blocks_exhausted_begin() const { return blocksExhausted.begin(); } BlocksExhausted::const_iterator blocks_exhausted_end() const { return blocksExhausted.end(); } BlocksAborted::const_iterator blocks_aborted_begin() const { return blocksAborted.begin(); } BlocksAborted::const_iterator blocks_aborted_end() const { return blocksAborted.end(); } /// \brief Enqueue the given set of nodes onto the work list. void enqueue(ExplodedNodeSet &Set); /// \brief Enqueue nodes that were created as a result of processing /// a statement onto the work list. void enqueue(ExplodedNodeSet &Set, const CFGBlock *Block, unsigned Idx); /// \brief enqueue the nodes corresponding to the end of function onto the /// end of path / work list. void enqueueEndOfFunction(ExplodedNodeSet &Set); /// \brief Enqueue a single node created as a result of statement processing. void enqueueStmtNode(ExplodedNode *N, const CFGBlock *Block, unsigned Idx); }; // TODO: Turn into a calss. struct NodeBuilderContext { const CoreEngine &Eng; const CFGBlock *Block; const LocationContext *LC; NodeBuilderContext(const CoreEngine &E, const CFGBlock *B, ExplodedNode *N) : Eng(E), Block(B), LC(N->getLocationContext()) { assert(B); } /// \brief Return the CFGBlock associated with this builder. const CFGBlock *getBlock() const { return Block; } /// \brief Returns the number of times the current basic block has been /// visited on the exploded graph path. unsigned blockCount() const { return Eng.WList->getBlockCounter().getNumVisited( LC->getCurrentStackFrame(), Block->getBlockID()); } }; /// \class NodeBuilder /// \brief This is the simplest builder which generates nodes in the /// ExplodedGraph. /// /// The main benefit of the builder is that it automatically tracks the /// frontier nodes (or destination set). This is the set of nodes which should /// be propagated to the next step / builder. They are the nodes which have been /// added to the builder (either as the input node set or as the newly /// constructed nodes) but did not have any outgoing transitions added. class NodeBuilder { virtual void anchor(); protected: const NodeBuilderContext &C; /// Specifies if the builder results have been finalized. For example, if it /// is set to false, autotransitions are yet to be generated. bool Finalized; bool HasGeneratedNodes; /// \brief The frontier set - a set of nodes which need to be propagated after /// the builder dies. ExplodedNodeSet &Frontier; /// Checkes if the results are ready. virtual bool checkResults() { if (!Finalized) return false; return true; } bool hasNoSinksInFrontier() { for (iterator I = Frontier.begin(), E = Frontier.end(); I != E; ++I) { if ((*I)->isSink()) return false; } return true; } /// Allow subclasses to finalize results before result_begin() is executed. virtual void finalizeResults() {} ExplodedNode *generateNodeImpl(const ProgramPoint &PP, ProgramStateRef State, ExplodedNode *Pred, bool MarkAsSink = false); public: NodeBuilder(ExplodedNode *SrcNode, ExplodedNodeSet &DstSet, const NodeBuilderContext &Ctx, bool F = true) : C(Ctx), Finalized(F), HasGeneratedNodes(false), Frontier(DstSet) { Frontier.Add(SrcNode); } NodeBuilder(const ExplodedNodeSet &SrcSet, ExplodedNodeSet &DstSet, const NodeBuilderContext &Ctx, bool F = true) : C(Ctx), Finalized(F), HasGeneratedNodes(false), Frontier(DstSet) { Frontier.insert(SrcSet); assert(hasNoSinksInFrontier()); } virtual ~NodeBuilder() {} /// \brief Generates a node in the ExplodedGraph. ExplodedNode *generateNode(const ProgramPoint &PP, ProgramStateRef State, ExplodedNode *Pred) { return generateNodeImpl(PP, State, Pred, false); } /// \brief Generates a sink in the ExplodedGraph. /// /// When a node is marked as sink, the exploration from the node is stopped - /// the node becomes the last node on the path and certain kinds of bugs are /// suppressed. ExplodedNode *generateSink(const ProgramPoint &PP, ProgramStateRef State, ExplodedNode *Pred) { return generateNodeImpl(PP, State, Pred, true); } const ExplodedNodeSet &getResults() { finalizeResults(); assert(checkResults()); return Frontier; } typedef ExplodedNodeSet::iterator iterator; /// \brief Iterators through the results frontier. inline iterator begin() { finalizeResults(); assert(checkResults()); return Frontier.begin(); } inline iterator end() { finalizeResults(); return Frontier.end(); } const NodeBuilderContext &getContext() { return C; } bool hasGeneratedNodes() { return HasGeneratedNodes; } void takeNodes(const ExplodedNodeSet &S) { for (ExplodedNodeSet::iterator I = S.begin(), E = S.end(); I != E; ++I ) Frontier.erase(*I); } void takeNodes(ExplodedNode *N) { Frontier.erase(N); } void addNodes(const ExplodedNodeSet &S) { Frontier.insert(S); } void addNodes(ExplodedNode *N) { Frontier.Add(N); } }; /// \class NodeBuilderWithSinks /// \brief This node builder keeps track of the generated sink nodes. class NodeBuilderWithSinks: public NodeBuilder { void anchor() override; protected: SmallVector<ExplodedNode*, 2> sinksGenerated; ProgramPoint &Location; public: NodeBuilderWithSinks(ExplodedNode *Pred, ExplodedNodeSet &DstSet, const NodeBuilderContext &Ctx, ProgramPoint &L) : NodeBuilder(Pred, DstSet, Ctx), Location(L) {} ExplodedNode *generateNode(ProgramStateRef State, ExplodedNode *Pred, const ProgramPointTag *Tag = nullptr) { const ProgramPoint &LocalLoc = (Tag ? Location.withTag(Tag) : Location); return NodeBuilder::generateNode(LocalLoc, State, Pred); } ExplodedNode *generateSink(ProgramStateRef State, ExplodedNode *Pred, const ProgramPointTag *Tag = nullptr) { const ProgramPoint &LocalLoc = (Tag ? Location.withTag(Tag) : Location); ExplodedNode *N = NodeBuilder::generateSink(LocalLoc, State, Pred); if (N && N->isSink()) sinksGenerated.push_back(N); return N; } const SmallVectorImpl<ExplodedNode*> &getSinks() const { return sinksGenerated; } }; /// \class StmtNodeBuilder /// \brief This builder class is useful for generating nodes that resulted from /// visiting a statement. The main difference from its parent NodeBuilder is /// that it creates a statement specific ProgramPoint. class StmtNodeBuilder: public NodeBuilder { NodeBuilder *EnclosingBldr; public: /// \brief Constructs a StmtNodeBuilder. If the builder is going to process /// nodes currently owned by another builder(with larger scope), use /// Enclosing builder to transfer ownership. StmtNodeBuilder(ExplodedNode *SrcNode, ExplodedNodeSet &DstSet, const NodeBuilderContext &Ctx, NodeBuilder *Enclosing = nullptr) : NodeBuilder(SrcNode, DstSet, Ctx), EnclosingBldr(Enclosing) { if (EnclosingBldr) EnclosingBldr->takeNodes(SrcNode); } StmtNodeBuilder(ExplodedNodeSet &SrcSet, ExplodedNodeSet &DstSet, const NodeBuilderContext &Ctx, NodeBuilder *Enclosing = nullptr) : NodeBuilder(SrcSet, DstSet, Ctx), EnclosingBldr(Enclosing) { if (EnclosingBldr) for (ExplodedNodeSet::iterator I = SrcSet.begin(), E = SrcSet.end(); I != E; ++I ) EnclosingBldr->takeNodes(*I); } ~StmtNodeBuilder() override; using NodeBuilder::generateNode; using NodeBuilder::generateSink; ExplodedNode *generateNode(const Stmt *S, ExplodedNode *Pred, ProgramStateRef St, const ProgramPointTag *tag = nullptr, ProgramPoint::Kind K = ProgramPoint::PostStmtKind){ const ProgramPoint &L = ProgramPoint::getProgramPoint(S, K, Pred->getLocationContext(), tag); return NodeBuilder::generateNode(L, St, Pred); } ExplodedNode *generateSink(const Stmt *S, ExplodedNode *Pred, ProgramStateRef St, const ProgramPointTag *tag = nullptr, ProgramPoint::Kind K = ProgramPoint::PostStmtKind){ const ProgramPoint &L = ProgramPoint::getProgramPoint(S, K, Pred->getLocationContext(), tag); return NodeBuilder::generateSink(L, St, Pred); } }; /// \brief BranchNodeBuilder is responsible for constructing the nodes /// corresponding to the two branches of the if statement - true and false. class BranchNodeBuilder: public NodeBuilder { void anchor() override; const CFGBlock *DstT; const CFGBlock *DstF; bool InFeasibleTrue; bool InFeasibleFalse; public: BranchNodeBuilder(ExplodedNode *SrcNode, ExplodedNodeSet &DstSet, const NodeBuilderContext &C, const CFGBlock *dstT, const CFGBlock *dstF) : NodeBuilder(SrcNode, DstSet, C), DstT(dstT), DstF(dstF), InFeasibleTrue(!DstT), InFeasibleFalse(!DstF) { // The branch node builder does not generate autotransitions. // If there are no successors it means that both branches are infeasible. takeNodes(SrcNode); } BranchNodeBuilder(const ExplodedNodeSet &SrcSet, ExplodedNodeSet &DstSet, const NodeBuilderContext &C, const CFGBlock *dstT, const CFGBlock *dstF) : NodeBuilder(SrcSet, DstSet, C), DstT(dstT), DstF(dstF), InFeasibleTrue(!DstT), InFeasibleFalse(!DstF) { takeNodes(SrcSet); } ExplodedNode *generateNode(ProgramStateRef State, bool branch, ExplodedNode *Pred); const CFGBlock *getTargetBlock(bool branch) const { return branch ? DstT : DstF; } void markInfeasible(bool branch) { if (branch) InFeasibleTrue = true; else InFeasibleFalse = true; } bool isFeasible(bool branch) { return branch ? !InFeasibleTrue : !InFeasibleFalse; } }; class IndirectGotoNodeBuilder { CoreEngine& Eng; const CFGBlock *Src; const CFGBlock &DispatchBlock; const Expr *E; ExplodedNode *Pred; public: IndirectGotoNodeBuilder(ExplodedNode *pred, const CFGBlock *src, const Expr *e, const CFGBlock *dispatch, CoreEngine* eng) : Eng(*eng), Src(src), DispatchBlock(*dispatch), E(e), Pred(pred) {} class iterator { CFGBlock::const_succ_iterator I; friend class IndirectGotoNodeBuilder; iterator(CFGBlock::const_succ_iterator i) : I(i) {} public: iterator &operator++() { ++I; return *this; } bool operator!=(const iterator &X) const { return I != X.I; } const LabelDecl *getLabel() const { return cast<LabelStmt>((*I)->getLabel())->getDecl(); } const CFGBlock *getBlock() const { return *I; } }; iterator begin() { return iterator(DispatchBlock.succ_begin()); } iterator end() { return iterator(DispatchBlock.succ_end()); } ExplodedNode *generateNode(const iterator &I, ProgramStateRef State, bool isSink = false); const Expr *getTarget() const { return E; } ProgramStateRef getState() const { return Pred->State; } const LocationContext *getLocationContext() const { return Pred->getLocationContext(); } }; class SwitchNodeBuilder { CoreEngine& Eng; const CFGBlock *Src; const Expr *Condition; ExplodedNode *Pred; public: SwitchNodeBuilder(ExplodedNode *pred, const CFGBlock *src, const Expr *condition, CoreEngine* eng) : Eng(*eng), Src(src), Condition(condition), Pred(pred) {} class iterator { CFGBlock::const_succ_reverse_iterator I; friend class SwitchNodeBuilder; iterator(CFGBlock::const_succ_reverse_iterator i) : I(i) {} public: iterator &operator++() { ++I; return *this; } bool operator!=(const iterator &X) const { return I != X.I; } bool operator==(const iterator &X) const { return I == X.I; } const CaseStmt *getCase() const { return cast<CaseStmt>((*I)->getLabel()); } const CFGBlock *getBlock() const { return *I; } }; iterator begin() { return iterator(Src->succ_rbegin()+1); } iterator end() { return iterator(Src->succ_rend()); } const SwitchStmt *getSwitch() const { return cast<SwitchStmt>(Src->getTerminator()); } ExplodedNode *generateCaseStmtNode(const iterator &I, ProgramStateRef State); ExplodedNode *generateDefaultCaseNode(ProgramStateRef State, bool isSink = false); const Expr *getCondition() const { return Condition; } ProgramStateRef getState() const { return Pred->State; } const LocationContext *getLocationContext() const { return Pred->getLocationContext(); } }; } // end ento namespace } // end clang namespace #endif
0
repos/DirectXShaderCompiler/tools/clang/include/clang/StaticAnalyzer/Core
repos/DirectXShaderCompiler/tools/clang/include/clang/StaticAnalyzer/Core/PathSensitive/APSIntType.h
//== APSIntType.h - Simple record of the type of APSInts --------*- C++ -*--==// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_APSINTTYPE_H #define LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_APSINTTYPE_H #include "llvm/ADT/APSInt.h" #include <tuple> namespace clang { namespace ento { /// \brief A record of the "type" of an APSInt, used for conversions. class APSIntType { uint32_t BitWidth; bool IsUnsigned; public: APSIntType(uint32_t Width, bool Unsigned) : BitWidth(Width), IsUnsigned(Unsigned) {} /* implicit */ APSIntType(const llvm::APSInt &Value) : BitWidth(Value.getBitWidth()), IsUnsigned(Value.isUnsigned()) {} uint32_t getBitWidth() const { return BitWidth; } bool isUnsigned() const { return IsUnsigned; } /// \brief Convert a given APSInt, in place, to match this type. /// /// This behaves like a C cast: converting 255u8 (0xFF) to s16 gives /// 255 (0x00FF), and converting -1s8 (0xFF) to u16 gives 65535 (0xFFFF). void apply(llvm::APSInt &Value) const { // Note the order here. We extend first to preserve the sign, if this value // is signed, /then/ match the signedness of the result type. Value = Value.extOrTrunc(BitWidth); Value.setIsUnsigned(IsUnsigned); } /// Convert and return a new APSInt with the given value, but this /// type's bit width and signedness. /// /// \see apply llvm::APSInt convert(const llvm::APSInt &Value) const LLVM_READONLY { llvm::APSInt Result(Value, Value.isUnsigned()); apply(Result); return Result; } /// Returns an all-zero value for this type. llvm::APSInt getZeroValue() const LLVM_READONLY { return llvm::APSInt(BitWidth, IsUnsigned); } /// Returns the minimum value for this type. llvm::APSInt getMinValue() const LLVM_READONLY { return llvm::APSInt::getMinValue(BitWidth, IsUnsigned); } /// Returns the maximum value for this type. llvm::APSInt getMaxValue() const LLVM_READONLY { return llvm::APSInt::getMaxValue(BitWidth, IsUnsigned); } llvm::APSInt getValue(uint64_t RawValue) const LLVM_READONLY { return (llvm::APSInt(BitWidth, IsUnsigned) = RawValue); } /// Used to classify whether a value is representable using this type. /// /// \see testInRange enum RangeTestResultKind { RTR_Below = -1, ///< Value is less than the minimum representable value. RTR_Within = 0, ///< Value is representable using this type. RTR_Above = 1 ///< Value is greater than the maximum representable value. }; /// Tests whether a given value is losslessly representable using this type. /// /// \param Val The value to test. /// \param AllowMixedSign Whether or not to allow signedness conversions. /// This determines whether -1s8 is considered in range /// for 'unsigned char' (u8). RangeTestResultKind testInRange(const llvm::APSInt &Val, bool AllowMixedSign) const LLVM_READONLY; bool operator==(const APSIntType &Other) const { return BitWidth == Other.BitWidth && IsUnsigned == Other.IsUnsigned; } /// \brief Provide an ordering for finding a common conversion type. /// /// Unsigned integers are considered to be better conversion types than /// signed integers of the same width. bool operator<(const APSIntType &Other) const { return std::tie(BitWidth, IsUnsigned) < std::tie(Other.BitWidth, Other.IsUnsigned); } }; } // end ento namespace } // end clang namespace #endif
0
repos/DirectXShaderCompiler/tools/clang/include/clang/StaticAnalyzer/Core
repos/DirectXShaderCompiler/tools/clang/include/clang/StaticAnalyzer/Core/PathSensitive/WorkList.h
//==- WorkList.h - Worklist class used by CoreEngine ---------------*- C++ -*-// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines WorkList, a pure virtual class that represents an opaque // worklist used by CoreEngine to explore the reachability state space. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_WORKLIST_H #define LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_WORKLIST_H #include "clang/StaticAnalyzer/Core/PathSensitive/BlockCounter.h" #include "clang/StaticAnalyzer/Core/PathSensitive/ExplodedGraph.h" #include <cassert> namespace clang { class CFGBlock; namespace ento { class WorkListUnit { ExplodedNode *node; BlockCounter counter; const CFGBlock *block; unsigned blockIdx; // This is the index of the next statement. public: WorkListUnit(ExplodedNode *N, BlockCounter C, const CFGBlock *B, unsigned idx) : node(N), counter(C), block(B), blockIdx(idx) {} explicit WorkListUnit(ExplodedNode *N, BlockCounter C) : node(N), counter(C), block(nullptr), blockIdx(0) {} /// Returns the node associated with the worklist unit. ExplodedNode *getNode() const { return node; } /// Returns the block counter map associated with the worklist unit. BlockCounter getBlockCounter() const { return counter; } /// Returns the CFGblock associated with the worklist unit. const CFGBlock *getBlock() const { return block; } /// Return the index within the CFGBlock for the worklist unit. unsigned getIndex() const { return blockIdx; } }; class WorkList { BlockCounter CurrentCounter; public: virtual ~WorkList(); virtual bool hasWork() const = 0; virtual void enqueue(const WorkListUnit& U) = 0; void enqueue(ExplodedNode *N, const CFGBlock *B, unsigned idx) { enqueue(WorkListUnit(N, CurrentCounter, B, idx)); } void enqueue(ExplodedNode *N) { assert(N->getLocation().getKind() != ProgramPoint::PostStmtKind); enqueue(WorkListUnit(N, CurrentCounter)); } virtual WorkListUnit dequeue() = 0; void setBlockCounter(BlockCounter C) { CurrentCounter = C; } BlockCounter getBlockCounter() const { return CurrentCounter; } class Visitor { public: Visitor() {} virtual ~Visitor(); virtual bool visit(const WorkListUnit &U) = 0; }; virtual bool visitItemsInWorkList(Visitor &V) = 0; static WorkList *makeDFS(); static WorkList *makeBFS(); static WorkList *makeBFSBlockDFSContents(); }; } // end GR namespace } // end clang namespace #endif
0
repos/DirectXShaderCompiler/tools/clang/include/clang/StaticAnalyzer/Core
repos/DirectXShaderCompiler/tools/clang/include/clang/StaticAnalyzer/Core/PathSensitive/TaintTag.h
//== TaintTag.h - Path-sensitive "State" for tracking values -*- C++ -*--=// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // Defines a set of taint tags. Several tags are used to differentiate kinds // of taint. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_TAINTTAG_H #define LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_TAINTTAG_H namespace clang { namespace ento { /// The type of taint, which helps to differentiate between different types of /// taint. typedef unsigned TaintTagType; static const TaintTagType TaintTagGeneric = 0; }} #endif
0
repos/DirectXShaderCompiler/tools/clang/include/clang/StaticAnalyzer/Core
repos/DirectXShaderCompiler/tools/clang/include/clang/StaticAnalyzer/Core/PathSensitive/MemRegion.h
//== MemRegion.h - Abstract memory regions for static analysis --*- C++ -*--==// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines MemRegion and its subclasses. MemRegion defines a // partially-typed abstraction of memory useful for path-sensitive dataflow // analyses. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_MEMREGION_H #define LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_MEMREGION_H #include "clang/AST/ASTContext.h" #include "clang/AST/CharUnits.h" #include "clang/AST/Decl.h" #include "clang/AST/ExprObjC.h" #include "clang/Basic/LLVM.h" #include "clang/StaticAnalyzer/Core/PathSensitive/SVals.h" #include "llvm/ADT/FoldingSet.h" #include "llvm/Support/Allocator.h" #include "llvm/Support/ErrorHandling.h" #include <string> namespace clang { class LocationContext; class StackFrameContext; namespace ento { class CodeTextRegion; class MemRegionManager; class MemSpaceRegion; class SValBuilder; class SymbolicRegion; class VarRegion; /// Represent a region's offset within the top level base region. class RegionOffset { /// The base region. const MemRegion *R; /// The bit offset within the base region. It shouldn't be negative. int64_t Offset; public: // We're using a const instead of an enumeration due to the size required; // Visual Studio will only create enumerations of size int, not long long. static const int64_t Symbolic = INT64_MAX; RegionOffset() : R(nullptr) {} RegionOffset(const MemRegion *r, int64_t off) : R(r), Offset(off) {} const MemRegion *getRegion() const { return R; } bool hasSymbolicOffset() const { return Offset == Symbolic; } int64_t getOffset() const { assert(!hasSymbolicOffset()); return Offset; } bool isValid() const { return R; } }; //===----------------------------------------------------------------------===// // Base region classes. //===----------------------------------------------------------------------===// /// MemRegion - The root abstract class for all memory regions. class MemRegion : public llvm::FoldingSetNode { friend class MemRegionManager; public: enum Kind { // Memory spaces. GenericMemSpaceRegionKind, StackLocalsSpaceRegionKind, StackArgumentsSpaceRegionKind, HeapSpaceRegionKind, UnknownSpaceRegionKind, StaticGlobalSpaceRegionKind, GlobalInternalSpaceRegionKind, GlobalSystemSpaceRegionKind, GlobalImmutableSpaceRegionKind, BEG_NON_STATIC_GLOBAL_MEMSPACES = GlobalInternalSpaceRegionKind, END_NON_STATIC_GLOBAL_MEMSPACES = GlobalImmutableSpaceRegionKind, BEG_GLOBAL_MEMSPACES = StaticGlobalSpaceRegionKind, END_GLOBAL_MEMSPACES = GlobalImmutableSpaceRegionKind, BEG_MEMSPACES = GenericMemSpaceRegionKind, END_MEMSPACES = GlobalImmutableSpaceRegionKind, // Untyped regions. SymbolicRegionKind, AllocaRegionKind, // Typed regions. BEG_TYPED_REGIONS, FunctionTextRegionKind = BEG_TYPED_REGIONS, BlockTextRegionKind, BlockDataRegionKind, BEG_TYPED_VALUE_REGIONS, CompoundLiteralRegionKind = BEG_TYPED_VALUE_REGIONS, CXXThisRegionKind, StringRegionKind, ObjCStringRegionKind, ElementRegionKind, // Decl Regions. BEG_DECL_REGIONS, VarRegionKind = BEG_DECL_REGIONS, FieldRegionKind, ObjCIvarRegionKind, END_DECL_REGIONS = ObjCIvarRegionKind, CXXTempObjectRegionKind, CXXBaseObjectRegionKind, END_TYPED_VALUE_REGIONS = CXXBaseObjectRegionKind, END_TYPED_REGIONS = CXXBaseObjectRegionKind }; private: const Kind kind; protected: MemRegion(Kind k) : kind(k) {} virtual ~MemRegion(); public: ASTContext &getContext() const; virtual void Profile(llvm::FoldingSetNodeID& ID) const = 0; virtual MemRegionManager* getMemRegionManager() const = 0; const MemSpaceRegion *getMemorySpace() const; const MemRegion *getBaseRegion() const; /// Check if the region is a subregion of the given region. virtual bool isSubRegionOf(const MemRegion *R) const; const MemRegion *StripCasts(bool StripBaseCasts = true) const; /// \brief If this is a symbolic region, returns the region. Otherwise, /// goes up the base chain looking for the first symbolic base region. const SymbolicRegion *getSymbolicBase() const; bool hasGlobalsOrParametersStorage() const; bool hasStackStorage() const; bool hasStackNonParametersStorage() const; bool hasStackParametersStorage() const; /// Compute the offset within the top level memory object. RegionOffset getAsOffset() const; /// \brief Get a string representation of a region for debug use. std::string getString() const; virtual void dumpToStream(raw_ostream &os) const; void dump() const; /// \brief Returns true if this region can be printed in a user-friendly way. virtual bool canPrintPretty() const; /// \brief Print the region for use in diagnostics. virtual void printPretty(raw_ostream &os) const; /// \brief Returns true if this region's textual representation can be used /// as part of a larger expression. virtual bool canPrintPrettyAsExpr() const; /// \brief Print the region as expression. /// /// When this region represents a subexpression, the method is for printing /// an expression containing it. virtual void printPrettyAsExpr(raw_ostream &os) const; Kind getKind() const { return kind; } template<typename RegionTy> const RegionTy* getAs() const; virtual bool isBoundable() const { return false; } }; /// MemSpaceRegion - A memory region that represents a "memory space"; /// for example, the set of global variables, the stack frame, etc. class MemSpaceRegion : public MemRegion { protected: friend class MemRegionManager; MemRegionManager *Mgr; MemSpaceRegion(MemRegionManager *mgr, Kind k = GenericMemSpaceRegionKind) : MemRegion(k), Mgr(mgr) { assert(classof(this)); } MemRegionManager* getMemRegionManager() const override { return Mgr; } public: bool isBoundable() const override { return false; } void Profile(llvm::FoldingSetNodeID &ID) const override; static bool classof(const MemRegion *R) { Kind k = R->getKind(); return k >= BEG_MEMSPACES && k <= END_MEMSPACES; } }; class GlobalsSpaceRegion : public MemSpaceRegion { virtual void anchor(); protected: GlobalsSpaceRegion(MemRegionManager *mgr, Kind k) : MemSpaceRegion(mgr, k) {} public: static bool classof(const MemRegion *R) { Kind k = R->getKind(); return k >= BEG_GLOBAL_MEMSPACES && k <= END_GLOBAL_MEMSPACES; } }; /// \brief The region of the static variables within the current CodeTextRegion /// scope. /// /// Currently, only the static locals are placed there, so we know that these /// variables do not get invalidated by calls to other functions. class StaticGlobalSpaceRegion : public GlobalsSpaceRegion { friend class MemRegionManager; const CodeTextRegion *CR; StaticGlobalSpaceRegion(MemRegionManager *mgr, const CodeTextRegion *cr) : GlobalsSpaceRegion(mgr, StaticGlobalSpaceRegionKind), CR(cr) {} public: void Profile(llvm::FoldingSetNodeID &ID) const override; void dumpToStream(raw_ostream &os) const override; const CodeTextRegion *getCodeRegion() const { return CR; } static bool classof(const MemRegion *R) { return R->getKind() == StaticGlobalSpaceRegionKind; } }; /// \brief The region for all the non-static global variables. /// /// This class is further split into subclasses for efficient implementation of /// invalidating a set of related global values as is done in /// RegionStoreManager::invalidateRegions (instead of finding all the dependent /// globals, we invalidate the whole parent region). class NonStaticGlobalSpaceRegion : public GlobalsSpaceRegion { friend class MemRegionManager; protected: NonStaticGlobalSpaceRegion(MemRegionManager *mgr, Kind k) : GlobalsSpaceRegion(mgr, k) {} public: static bool classof(const MemRegion *R) { Kind k = R->getKind(); return k >= BEG_NON_STATIC_GLOBAL_MEMSPACES && k <= END_NON_STATIC_GLOBAL_MEMSPACES; } }; /// \brief The region containing globals which are defined in system/external /// headers and are considered modifiable by system calls (ex: errno). class GlobalSystemSpaceRegion : public NonStaticGlobalSpaceRegion { friend class MemRegionManager; GlobalSystemSpaceRegion(MemRegionManager *mgr) : NonStaticGlobalSpaceRegion(mgr, GlobalSystemSpaceRegionKind) {} public: void dumpToStream(raw_ostream &os) const override; static bool classof(const MemRegion *R) { return R->getKind() == GlobalSystemSpaceRegionKind; } }; /// \brief The region containing globals which are considered not to be modified /// or point to data which could be modified as a result of a function call /// (system or internal). Ex: Const global scalars would be modeled as part of /// this region. This region also includes most system globals since they have /// low chance of being modified. class GlobalImmutableSpaceRegion : public NonStaticGlobalSpaceRegion { friend class MemRegionManager; GlobalImmutableSpaceRegion(MemRegionManager *mgr) : NonStaticGlobalSpaceRegion(mgr, GlobalImmutableSpaceRegionKind) {} public: void dumpToStream(raw_ostream &os) const override; static bool classof(const MemRegion *R) { return R->getKind() == GlobalImmutableSpaceRegionKind; } }; /// \brief The region containing globals which can be modified by calls to /// "internally" defined functions - (for now just) functions other then system /// calls. class GlobalInternalSpaceRegion : public NonStaticGlobalSpaceRegion { friend class MemRegionManager; GlobalInternalSpaceRegion(MemRegionManager *mgr) : NonStaticGlobalSpaceRegion(mgr, GlobalInternalSpaceRegionKind) {} public: void dumpToStream(raw_ostream &os) const override; static bool classof(const MemRegion *R) { return R->getKind() == GlobalInternalSpaceRegionKind; } }; class HeapSpaceRegion : public MemSpaceRegion { virtual void anchor(); friend class MemRegionManager; HeapSpaceRegion(MemRegionManager *mgr) : MemSpaceRegion(mgr, HeapSpaceRegionKind) {} public: void dumpToStream(raw_ostream &os) const override; static bool classof(const MemRegion *R) { return R->getKind() == HeapSpaceRegionKind; } }; class UnknownSpaceRegion : public MemSpaceRegion { virtual void anchor(); friend class MemRegionManager; UnknownSpaceRegion(MemRegionManager *mgr) : MemSpaceRegion(mgr, UnknownSpaceRegionKind) {} public: void dumpToStream(raw_ostream &os) const override; static bool classof(const MemRegion *R) { return R->getKind() == UnknownSpaceRegionKind; } }; class StackSpaceRegion : public MemSpaceRegion { private: const StackFrameContext *SFC; protected: StackSpaceRegion(MemRegionManager *mgr, Kind k, const StackFrameContext *sfc) : MemSpaceRegion(mgr, k), SFC(sfc) { assert(classof(this)); } public: const StackFrameContext *getStackFrame() const { return SFC; } void Profile(llvm::FoldingSetNodeID &ID) const override; static bool classof(const MemRegion *R) { Kind k = R->getKind(); return k >= StackLocalsSpaceRegionKind && k <= StackArgumentsSpaceRegionKind; } }; class StackLocalsSpaceRegion : public StackSpaceRegion { virtual void anchor(); friend class MemRegionManager; StackLocalsSpaceRegion(MemRegionManager *mgr, const StackFrameContext *sfc) : StackSpaceRegion(mgr, StackLocalsSpaceRegionKind, sfc) {} public: void dumpToStream(raw_ostream &os) const override; static bool classof(const MemRegion *R) { return R->getKind() == StackLocalsSpaceRegionKind; } }; class StackArgumentsSpaceRegion : public StackSpaceRegion { private: virtual void anchor(); friend class MemRegionManager; StackArgumentsSpaceRegion(MemRegionManager *mgr, const StackFrameContext *sfc) : StackSpaceRegion(mgr, StackArgumentsSpaceRegionKind, sfc) {} public: void dumpToStream(raw_ostream &os) const override; static bool classof(const MemRegion *R) { return R->getKind() == StackArgumentsSpaceRegionKind; } }; /// SubRegion - A region that subsets another larger region. Most regions /// are subclasses of SubRegion. class SubRegion : public MemRegion { private: virtual void anchor(); protected: const MemRegion* superRegion; SubRegion(const MemRegion* sReg, Kind k) : MemRegion(k), superRegion(sReg) {} public: const MemRegion* getSuperRegion() const { return superRegion; } /// getExtent - Returns the size of the region in bytes. virtual DefinedOrUnknownSVal getExtent(SValBuilder &svalBuilder) const { return UnknownVal(); } MemRegionManager* getMemRegionManager() const override; bool isSubRegionOf(const MemRegion* R) const override; static bool classof(const MemRegion* R) { return R->getKind() > END_MEMSPACES; } }; //===----------------------------------------------------------------------===// // MemRegion subclasses. //===----------------------------------------------------------------------===// /// AllocaRegion - A region that represents an untyped blob of bytes created /// by a call to 'alloca'. class AllocaRegion : public SubRegion { friend class MemRegionManager; protected: unsigned Cnt; // Block counter. Used to distinguish different pieces of // memory allocated by alloca at the same call site. const Expr *Ex; AllocaRegion(const Expr *ex, unsigned cnt, const MemRegion *superRegion) : SubRegion(superRegion, AllocaRegionKind), Cnt(cnt), Ex(ex) {} public: const Expr *getExpr() const { return Ex; } bool isBoundable() const override { return true; } DefinedOrUnknownSVal getExtent(SValBuilder &svalBuilder) const override; void Profile(llvm::FoldingSetNodeID& ID) const override; static void ProfileRegion(llvm::FoldingSetNodeID& ID, const Expr *Ex, unsigned Cnt, const MemRegion *superRegion); void dumpToStream(raw_ostream &os) const override; static bool classof(const MemRegion* R) { return R->getKind() == AllocaRegionKind; } }; /// TypedRegion - An abstract class representing regions that are typed. class TypedRegion : public SubRegion { public: void anchor() override; protected: TypedRegion(const MemRegion* sReg, Kind k) : SubRegion(sReg, k) {} public: virtual QualType getLocationType() const = 0; QualType getDesugaredLocationType(ASTContext &Context) const { return getLocationType().getDesugaredType(Context); } bool isBoundable() const override { return true; } static bool classof(const MemRegion* R) { unsigned k = R->getKind(); return k >= BEG_TYPED_REGIONS && k <= END_TYPED_REGIONS; } }; /// TypedValueRegion - An abstract class representing regions having a typed value. class TypedValueRegion : public TypedRegion { public: void anchor() override; protected: TypedValueRegion(const MemRegion* sReg, Kind k) : TypedRegion(sReg, k) {} public: virtual QualType getValueType() const = 0; QualType getLocationType() const override { // FIXME: We can possibly optimize this later to cache this value. QualType T = getValueType(); ASTContext &ctx = getContext(); if (T->getAs<ObjCObjectType>()) return ctx.getObjCObjectPointerType(T); return ctx.getPointerType(getValueType()); } QualType getDesugaredValueType(ASTContext &Context) const { QualType T = getValueType(); return T.getTypePtrOrNull() ? T.getDesugaredType(Context) : T; } DefinedOrUnknownSVal getExtent(SValBuilder &svalBuilder) const override; static bool classof(const MemRegion* R) { unsigned k = R->getKind(); return k >= BEG_TYPED_VALUE_REGIONS && k <= END_TYPED_VALUE_REGIONS; } }; class CodeTextRegion : public TypedRegion { public: void anchor() override; protected: CodeTextRegion(const MemRegion *sreg, Kind k) : TypedRegion(sreg, k) {} public: bool isBoundable() const override { return false; } static bool classof(const MemRegion* R) { Kind k = R->getKind(); return k >= FunctionTextRegionKind && k <= BlockTextRegionKind; } }; /// FunctionTextRegion - A region that represents code texts of function. class FunctionTextRegion : public CodeTextRegion { const NamedDecl *FD; public: FunctionTextRegion(const NamedDecl *fd, const MemRegion* sreg) : CodeTextRegion(sreg, FunctionTextRegionKind), FD(fd) { assert(isa<ObjCMethodDecl>(fd) || isa<FunctionDecl>(fd)); } QualType getLocationType() const override { const ASTContext &Ctx = getContext(); if (const FunctionDecl *D = dyn_cast<FunctionDecl>(FD)) { return Ctx.getPointerType(D->getType()); } assert(isa<ObjCMethodDecl>(FD)); assert(false && "Getting the type of ObjCMethod is not supported yet"); // TODO: We might want to return a different type here (ex: id (*ty)(...)) // depending on how it is used. return QualType(); } const NamedDecl *getDecl() const { return FD; } void dumpToStream(raw_ostream &os) const override; void Profile(llvm::FoldingSetNodeID& ID) const override; static void ProfileRegion(llvm::FoldingSetNodeID& ID, const NamedDecl *FD, const MemRegion*); static bool classof(const MemRegion* R) { return R->getKind() == FunctionTextRegionKind; } }; /// BlockTextRegion - A region that represents code texts of blocks (closures). /// Blocks are represented with two kinds of regions. BlockTextRegions /// represent the "code", while BlockDataRegions represent instances of blocks, /// which correspond to "code+data". The distinction is important, because /// like a closure a block captures the values of externally referenced /// variables. class BlockTextRegion : public CodeTextRegion { friend class MemRegionManager; const BlockDecl *BD; AnalysisDeclContext *AC; CanQualType locTy; BlockTextRegion(const BlockDecl *bd, CanQualType lTy, AnalysisDeclContext *ac, const MemRegion* sreg) : CodeTextRegion(sreg, BlockTextRegionKind), BD(bd), AC(ac), locTy(lTy) {} public: QualType getLocationType() const override { return locTy; } const BlockDecl *getDecl() const { return BD; } AnalysisDeclContext *getAnalysisDeclContext() const { return AC; } void dumpToStream(raw_ostream &os) const override; void Profile(llvm::FoldingSetNodeID& ID) const override; static void ProfileRegion(llvm::FoldingSetNodeID& ID, const BlockDecl *BD, CanQualType, const AnalysisDeclContext*, const MemRegion*); static bool classof(const MemRegion* R) { return R->getKind() == BlockTextRegionKind; } }; /// BlockDataRegion - A region that represents a block instance. /// Blocks are represented with two kinds of regions. BlockTextRegions /// represent the "code", while BlockDataRegions represent instances of blocks, /// which correspond to "code+data". The distinction is important, because /// like a closure a block captures the values of externally referenced /// variables. class BlockDataRegion : public TypedRegion { friend class MemRegionManager; const BlockTextRegion *BC; const LocationContext *LC; // Can be null */ unsigned BlockCount; void *ReferencedVars; void *OriginalVars; BlockDataRegion(const BlockTextRegion *bc, const LocationContext *lc, unsigned count, const MemRegion *sreg) : TypedRegion(sreg, BlockDataRegionKind), BC(bc), LC(lc), BlockCount(count), ReferencedVars(nullptr), OriginalVars(nullptr) {} public: const BlockTextRegion *getCodeRegion() const { return BC; } const BlockDecl *getDecl() const { return BC->getDecl(); } QualType getLocationType() const override { return BC->getLocationType(); } class referenced_vars_iterator { const MemRegion * const *R; const MemRegion * const *OriginalR; public: explicit referenced_vars_iterator(const MemRegion * const *r, const MemRegion * const *originalR) : R(r), OriginalR(originalR) {} const VarRegion *getCapturedRegion() const { return cast<VarRegion>(*R); } const VarRegion *getOriginalRegion() const { return cast<VarRegion>(*OriginalR); } bool operator==(const referenced_vars_iterator &I) const { assert((R == nullptr) == (I.R == nullptr)); return I.R == R; } bool operator!=(const referenced_vars_iterator &I) const { assert((R == nullptr) == (I.R == nullptr)); return I.R != R; } referenced_vars_iterator &operator++() { ++R; ++OriginalR; return *this; } }; /// Return the original region for a captured region, if /// one exists. const VarRegion *getOriginalRegion(const VarRegion *VR) const; referenced_vars_iterator referenced_vars_begin() const; referenced_vars_iterator referenced_vars_end() const; void dumpToStream(raw_ostream &os) const override; void Profile(llvm::FoldingSetNodeID& ID) const override; static void ProfileRegion(llvm::FoldingSetNodeID&, const BlockTextRegion *, const LocationContext *, unsigned, const MemRegion *); static bool classof(const MemRegion* R) { return R->getKind() == BlockDataRegionKind; } private: void LazyInitializeReferencedVars(); std::pair<const VarRegion *, const VarRegion *> getCaptureRegions(const VarDecl *VD); }; /// SymbolicRegion - A special, "non-concrete" region. Unlike other region /// classes, SymbolicRegion represents a region that serves as an alias for /// either a real region, a NULL pointer, etc. It essentially is used to /// map the concept of symbolic values into the domain of regions. Symbolic /// regions do not need to be typed. class SymbolicRegion : public SubRegion { protected: const SymbolRef sym; public: SymbolicRegion(const SymbolRef s, const MemRegion* sreg) : SubRegion(sreg, SymbolicRegionKind), sym(s) {} SymbolRef getSymbol() const { return sym; } bool isBoundable() const override { return true; } DefinedOrUnknownSVal getExtent(SValBuilder &svalBuilder) const override; void Profile(llvm::FoldingSetNodeID& ID) const override; static void ProfileRegion(llvm::FoldingSetNodeID& ID, SymbolRef sym, const MemRegion* superRegion); void dumpToStream(raw_ostream &os) const override; static bool classof(const MemRegion* R) { return R->getKind() == SymbolicRegionKind; } }; /// StringRegion - Region associated with a StringLiteral. class StringRegion : public TypedValueRegion { friend class MemRegionManager; const StringLiteral* Str; protected: StringRegion(const StringLiteral* str, const MemRegion* sreg) : TypedValueRegion(sreg, StringRegionKind), Str(str) {} static void ProfileRegion(llvm::FoldingSetNodeID& ID, const StringLiteral* Str, const MemRegion* superRegion); public: const StringLiteral* getStringLiteral() const { return Str; } QualType getValueType() const override { return Str->getType(); } DefinedOrUnknownSVal getExtent(SValBuilder &svalBuilder) const override; bool isBoundable() const override { return false; } void Profile(llvm::FoldingSetNodeID& ID) const override { ProfileRegion(ID, Str, superRegion); } void dumpToStream(raw_ostream &os) const override; static bool classof(const MemRegion* R) { return R->getKind() == StringRegionKind; } }; /// The region associated with an ObjCStringLiteral. class ObjCStringRegion : public TypedValueRegion { friend class MemRegionManager; const ObjCStringLiteral* Str; protected: ObjCStringRegion(const ObjCStringLiteral* str, const MemRegion* sreg) : TypedValueRegion(sreg, ObjCStringRegionKind), Str(str) {} static void ProfileRegion(llvm::FoldingSetNodeID& ID, const ObjCStringLiteral* Str, const MemRegion* superRegion); public: const ObjCStringLiteral* getObjCStringLiteral() const { return Str; } QualType getValueType() const override { return Str->getType(); } bool isBoundable() const override { return false; } void Profile(llvm::FoldingSetNodeID& ID) const override { ProfileRegion(ID, Str, superRegion); } void dumpToStream(raw_ostream &os) const override; static bool classof(const MemRegion* R) { return R->getKind() == ObjCStringRegionKind; } }; /// CompoundLiteralRegion - A memory region representing a compound literal. /// Compound literals are essentially temporaries that are stack allocated /// or in the global constant pool. class CompoundLiteralRegion : public TypedValueRegion { private: friend class MemRegionManager; const CompoundLiteralExpr *CL; CompoundLiteralRegion(const CompoundLiteralExpr *cl, const MemRegion* sReg) : TypedValueRegion(sReg, CompoundLiteralRegionKind), CL(cl) {} static void ProfileRegion(llvm::FoldingSetNodeID& ID, const CompoundLiteralExpr *CL, const MemRegion* superRegion); public: QualType getValueType() const override { return CL->getType(); } bool isBoundable() const override { return !CL->isFileScope(); } void Profile(llvm::FoldingSetNodeID& ID) const override; void dumpToStream(raw_ostream &os) const override; const CompoundLiteralExpr *getLiteralExpr() const { return CL; } static bool classof(const MemRegion* R) { return R->getKind() == CompoundLiteralRegionKind; } }; class DeclRegion : public TypedValueRegion { protected: const Decl *D; DeclRegion(const Decl *d, const MemRegion* sReg, Kind k) : TypedValueRegion(sReg, k), D(d) {} static void ProfileRegion(llvm::FoldingSetNodeID& ID, const Decl *D, const MemRegion* superRegion, Kind k); public: const Decl *getDecl() const { return D; } void Profile(llvm::FoldingSetNodeID& ID) const override; static bool classof(const MemRegion* R) { unsigned k = R->getKind(); return k >= BEG_DECL_REGIONS && k <= END_DECL_REGIONS; } }; class VarRegion : public DeclRegion { friend class MemRegionManager; // Constructors and private methods. VarRegion(const VarDecl *vd, const MemRegion* sReg) : DeclRegion(vd, sReg, VarRegionKind) {} static void ProfileRegion(llvm::FoldingSetNodeID& ID, const VarDecl *VD, const MemRegion *superRegion) { DeclRegion::ProfileRegion(ID, VD, superRegion, VarRegionKind); } void Profile(llvm::FoldingSetNodeID& ID) const override; public: const VarDecl *getDecl() const { return cast<VarDecl>(D); } const StackFrameContext *getStackFrame() const; QualType getValueType() const override { // FIXME: We can cache this if needed. return getDecl()->getType(); } void dumpToStream(raw_ostream &os) const override; static bool classof(const MemRegion* R) { return R->getKind() == VarRegionKind; } bool canPrintPrettyAsExpr() const override; void printPrettyAsExpr(raw_ostream &os) const override; }; /// CXXThisRegion - Represents the region for the implicit 'this' parameter /// in a call to a C++ method. This region doesn't represent the object /// referred to by 'this', but rather 'this' itself. class CXXThisRegion : public TypedValueRegion { friend class MemRegionManager; CXXThisRegion(const PointerType *thisPointerTy, const MemRegion *sReg) : TypedValueRegion(sReg, CXXThisRegionKind), ThisPointerTy(thisPointerTy) {} static void ProfileRegion(llvm::FoldingSetNodeID &ID, const PointerType *PT, const MemRegion *sReg); void Profile(llvm::FoldingSetNodeID &ID) const override; public: QualType getValueType() const override { return QualType(ThisPointerTy, 0); } void dumpToStream(raw_ostream &os) const override; static bool classof(const MemRegion* R) { return R->getKind() == CXXThisRegionKind; } private: const PointerType *ThisPointerTy; }; class FieldRegion : public DeclRegion { friend class MemRegionManager; FieldRegion(const FieldDecl *fd, const MemRegion* sReg) : DeclRegion(fd, sReg, FieldRegionKind) {} public: const FieldDecl *getDecl() const { return cast<FieldDecl>(D); } QualType getValueType() const override { // FIXME: We can cache this if needed. return getDecl()->getType(); } DefinedOrUnknownSVal getExtent(SValBuilder &svalBuilder) const override; static void ProfileRegion(llvm::FoldingSetNodeID& ID, const FieldDecl *FD, const MemRegion* superRegion) { DeclRegion::ProfileRegion(ID, FD, superRegion, FieldRegionKind); } static bool classof(const MemRegion* R) { return R->getKind() == FieldRegionKind; } void dumpToStream(raw_ostream &os) const override; bool canPrintPretty() const override; void printPretty(raw_ostream &os) const override; bool canPrintPrettyAsExpr() const override; void printPrettyAsExpr(raw_ostream &os) const override; }; class ObjCIvarRegion : public DeclRegion { friend class MemRegionManager; ObjCIvarRegion(const ObjCIvarDecl *ivd, const MemRegion* sReg); static void ProfileRegion(llvm::FoldingSetNodeID& ID, const ObjCIvarDecl *ivd, const MemRegion* superRegion); public: const ObjCIvarDecl *getDecl() const; QualType getValueType() const override; bool canPrintPrettyAsExpr() const override; void printPrettyAsExpr(raw_ostream &os) const override; void dumpToStream(raw_ostream &os) const override; static bool classof(const MemRegion* R) { return R->getKind() == ObjCIvarRegionKind; } }; //===----------------------------------------------------------------------===// // Auxiliary data classes for use with MemRegions. //===----------------------------------------------------------------------===// class ElementRegion; class RegionRawOffset { private: friend class ElementRegion; const MemRegion *Region; CharUnits Offset; RegionRawOffset(const MemRegion* reg, CharUnits offset = CharUnits::Zero()) : Region(reg), Offset(offset) {} public: // FIXME: Eventually support symbolic offsets. CharUnits getOffset() const { return Offset; } const MemRegion *getRegion() const { return Region; } void dumpToStream(raw_ostream &os) const; void dump() const; }; /// \brief ElementRegin is used to represent both array elements and casts. class ElementRegion : public TypedValueRegion { friend class MemRegionManager; QualType ElementType; NonLoc Index; ElementRegion(QualType elementType, NonLoc Idx, const MemRegion* sReg) : TypedValueRegion(sReg, ElementRegionKind), ElementType(elementType), Index(Idx) { assert((!Idx.getAs<nonloc::ConcreteInt>() || Idx.castAs<nonloc::ConcreteInt>().getValue().isSigned()) && "The index must be signed"); } static void ProfileRegion(llvm::FoldingSetNodeID& ID, QualType elementType, SVal Idx, const MemRegion* superRegion); public: NonLoc getIndex() const { return Index; } QualType getValueType() const override { return ElementType; } QualType getElementType() const { return ElementType; } /// Compute the offset within the array. The array might also be a subobject. RegionRawOffset getAsArrayOffset() const; void dumpToStream(raw_ostream &os) const override; void Profile(llvm::FoldingSetNodeID& ID) const override; static bool classof(const MemRegion* R) { return R->getKind() == ElementRegionKind; } }; // C++ temporary object associated with an expression. class CXXTempObjectRegion : public TypedValueRegion { friend class MemRegionManager; Expr const *Ex; CXXTempObjectRegion(Expr const *E, MemRegion const *sReg) : TypedValueRegion(sReg, CXXTempObjectRegionKind), Ex(E) {} static void ProfileRegion(llvm::FoldingSetNodeID &ID, Expr const *E, const MemRegion *sReg); public: const Expr *getExpr() const { return Ex; } QualType getValueType() const override { return Ex->getType(); } void dumpToStream(raw_ostream &os) const override; void Profile(llvm::FoldingSetNodeID &ID) const override; static bool classof(const MemRegion* R) { return R->getKind() == CXXTempObjectRegionKind; } }; // CXXBaseObjectRegion represents a base object within a C++ object. It is // identified by the base class declaration and the region of its parent object. class CXXBaseObjectRegion : public TypedValueRegion { friend class MemRegionManager; llvm::PointerIntPair<const CXXRecordDecl *, 1, bool> Data; CXXBaseObjectRegion(const CXXRecordDecl *RD, bool IsVirtual, const MemRegion *SReg) : TypedValueRegion(SReg, CXXBaseObjectRegionKind), Data(RD, IsVirtual) {} static void ProfileRegion(llvm::FoldingSetNodeID &ID, const CXXRecordDecl *RD, bool IsVirtual, const MemRegion *SReg); public: const CXXRecordDecl *getDecl() const { return Data.getPointer(); } bool isVirtual() const { return Data.getInt(); } QualType getValueType() const override; void dumpToStream(raw_ostream &os) const override; void Profile(llvm::FoldingSetNodeID &ID) const override; static bool classof(const MemRegion *region) { return region->getKind() == CXXBaseObjectRegionKind; } bool canPrintPrettyAsExpr() const override; void printPrettyAsExpr(raw_ostream &os) const override; }; template<typename RegionTy> const RegionTy* MemRegion::getAs() const { if (const RegionTy* RT = dyn_cast<RegionTy>(this)) return RT; return nullptr; } //===----------------------------------------------------------------------===// // MemRegionManager - Factory object for creating regions. //===----------------------------------------------------------------------===// class MemRegionManager { ASTContext &C; llvm::BumpPtrAllocator& A; llvm::FoldingSet<MemRegion> Regions; GlobalInternalSpaceRegion *InternalGlobals; GlobalSystemSpaceRegion *SystemGlobals; GlobalImmutableSpaceRegion *ImmutableGlobals; llvm::DenseMap<const StackFrameContext *, StackLocalsSpaceRegion *> StackLocalsSpaceRegions; llvm::DenseMap<const StackFrameContext *, StackArgumentsSpaceRegion *> StackArgumentsSpaceRegions; llvm::DenseMap<const CodeTextRegion *, StaticGlobalSpaceRegion *> StaticsGlobalSpaceRegions; HeapSpaceRegion *heap; UnknownSpaceRegion *unknown; MemSpaceRegion *code; public: MemRegionManager(ASTContext &c, llvm::BumpPtrAllocator &a) : C(c), A(a), InternalGlobals(nullptr), SystemGlobals(nullptr), ImmutableGlobals(nullptr), heap(nullptr), unknown(nullptr), code(nullptr) {} ~MemRegionManager(); ASTContext &getContext() { return C; } llvm::BumpPtrAllocator &getAllocator() { return A; } /// getStackLocalsRegion - Retrieve the memory region associated with the /// specified stack frame. const StackLocalsSpaceRegion * getStackLocalsRegion(const StackFrameContext *STC); /// getStackArgumentsRegion - Retrieve the memory region associated with /// function/method arguments of the specified stack frame. const StackArgumentsSpaceRegion * getStackArgumentsRegion(const StackFrameContext *STC); /// getGlobalsRegion - Retrieve the memory region associated with /// global variables. const GlobalsSpaceRegion *getGlobalsRegion( MemRegion::Kind K = MemRegion::GlobalInternalSpaceRegionKind, const CodeTextRegion *R = nullptr); /// getHeapRegion - Retrieve the memory region associated with the /// generic "heap". const HeapSpaceRegion *getHeapRegion(); /// getUnknownRegion - Retrieve the memory region associated with unknown /// memory space. const MemSpaceRegion *getUnknownRegion(); const MemSpaceRegion *getCodeRegion(); /// getAllocaRegion - Retrieve a region associated with a call to alloca(). const AllocaRegion *getAllocaRegion(const Expr *Ex, unsigned Cnt, const LocationContext *LC); /// getCompoundLiteralRegion - Retrieve the region associated with a /// given CompoundLiteral. const CompoundLiteralRegion* getCompoundLiteralRegion(const CompoundLiteralExpr *CL, const LocationContext *LC); /// getCXXThisRegion - Retrieve the [artificial] region associated with the /// parameter 'this'. const CXXThisRegion *getCXXThisRegion(QualType thisPointerTy, const LocationContext *LC); /// \brief Retrieve or create a "symbolic" memory region. const SymbolicRegion* getSymbolicRegion(SymbolRef Sym); /// \brief Return a unique symbolic region belonging to heap memory space. const SymbolicRegion *getSymbolicHeapRegion(SymbolRef sym); const StringRegion *getStringRegion(const StringLiteral* Str); const ObjCStringRegion *getObjCStringRegion(const ObjCStringLiteral *Str); /// getVarRegion - Retrieve or create the memory region associated with /// a specified VarDecl and LocationContext. const VarRegion* getVarRegion(const VarDecl *D, const LocationContext *LC); /// getVarRegion - Retrieve or create the memory region associated with /// a specified VarDecl and super region. const VarRegion* getVarRegion(const VarDecl *D, const MemRegion *superR); /// getElementRegion - Retrieve the memory region associated with the /// associated element type, index, and super region. const ElementRegion *getElementRegion(QualType elementType, NonLoc Idx, const MemRegion *superRegion, ASTContext &Ctx); const ElementRegion *getElementRegionWithSuper(const ElementRegion *ER, const MemRegion *superRegion) { return getElementRegion(ER->getElementType(), ER->getIndex(), superRegion, ER->getContext()); } /// getFieldRegion - Retrieve or create the memory region associated with /// a specified FieldDecl. 'superRegion' corresponds to the containing /// memory region (which typically represents the memory representing /// a structure or class). const FieldRegion *getFieldRegion(const FieldDecl *fd, const MemRegion* superRegion); const FieldRegion *getFieldRegionWithSuper(const FieldRegion *FR, const MemRegion *superRegion) { return getFieldRegion(FR->getDecl(), superRegion); } /// getObjCIvarRegion - Retrieve or create the memory region associated with /// a specified Objective-c instance variable. 'superRegion' corresponds /// to the containing region (which typically represents the Objective-C /// object). const ObjCIvarRegion *getObjCIvarRegion(const ObjCIvarDecl *ivd, const MemRegion* superRegion); const CXXTempObjectRegion *getCXXTempObjectRegion(Expr const *Ex, LocationContext const *LC); /// Create a CXXBaseObjectRegion with the given base class for region /// \p Super. /// /// The type of \p Super is assumed be a class deriving from \p BaseClass. const CXXBaseObjectRegion * getCXXBaseObjectRegion(const CXXRecordDecl *BaseClass, const MemRegion *Super, bool IsVirtual); /// Create a CXXBaseObjectRegion with the same CXXRecordDecl but a different /// super region. const CXXBaseObjectRegion * getCXXBaseObjectRegionWithSuper(const CXXBaseObjectRegion *baseReg, const MemRegion *superRegion) { return getCXXBaseObjectRegion(baseReg->getDecl(), superRegion, baseReg->isVirtual()); } const FunctionTextRegion *getFunctionTextRegion(const NamedDecl *FD); const BlockTextRegion *getBlockTextRegion(const BlockDecl *BD, CanQualType locTy, AnalysisDeclContext *AC); /// getBlockDataRegion - Get the memory region associated with an instance /// of a block. Unlike many other MemRegions, the LocationContext* /// argument is allowed to be NULL for cases where we have no known /// context. const BlockDataRegion *getBlockDataRegion(const BlockTextRegion *bc, const LocationContext *lc, unsigned blockCount); /// Create a CXXTempObjectRegion for temporaries which are lifetime-extended /// by static references. This differs from getCXXTempObjectRegion in the /// super-region used. const CXXTempObjectRegion *getCXXStaticTempObjectRegion(const Expr *Ex); private: template <typename RegionTy, typename A1> RegionTy* getRegion(const A1 a1); template <typename RegionTy, typename A1> RegionTy* getSubRegion(const A1 a1, const MemRegion* superRegion); template <typename RegionTy, typename A1, typename A2> RegionTy* getRegion(const A1 a1, const A2 a2); template <typename RegionTy, typename A1, typename A2> RegionTy* getSubRegion(const A1 a1, const A2 a2, const MemRegion* superRegion); template <typename RegionTy, typename A1, typename A2, typename A3> RegionTy* getSubRegion(const A1 a1, const A2 a2, const A3 a3, const MemRegion* superRegion); template <typename REG> const REG* LazyAllocate(REG*& region); template <typename REG, typename ARG> const REG* LazyAllocate(REG*& region, ARG a); }; //===----------------------------------------------------------------------===// // Out-of-line member definitions. //===----------------------------------------------------------------------===// inline ASTContext &MemRegion::getContext() const { return getMemRegionManager()->getContext(); } //===----------------------------------------------------------------------===// // Means for storing region/symbol handling traits. //===----------------------------------------------------------------------===// /// Information about invalidation for a particular region/symbol. class RegionAndSymbolInvalidationTraits { typedef unsigned char StorageTypeForKinds; llvm::DenseMap<const MemRegion *, StorageTypeForKinds> MRTraitsMap; llvm::DenseMap<SymbolRef, StorageTypeForKinds> SymTraitsMap; typedef llvm::DenseMap<const MemRegion *, StorageTypeForKinds>::const_iterator const_region_iterator; typedef llvm::DenseMap<SymbolRef, StorageTypeForKinds>::const_iterator const_symbol_iterator; public: /// \brief Describes different invalidation traits. enum InvalidationKinds { /// Tells that a region's contents is not changed. TK_PreserveContents = 0x1, /// Suppress pointer-escaping of a region. TK_SuppressEscape = 0x2 // Do not forget to extend StorageTypeForKinds if number of traits exceed // the number of bits StorageTypeForKinds can store. }; void setTrait(SymbolRef Sym, InvalidationKinds IK); void setTrait(const MemRegion *MR, InvalidationKinds IK); bool hasTrait(SymbolRef Sym, InvalidationKinds IK); bool hasTrait(const MemRegion *MR, InvalidationKinds IK); }; } // end GR namespace } // end clang namespace //===----------------------------------------------------------------------===// // Pretty-printing regions. // // /////////////////////////////////////////////////////////////////////////////// namespace llvm { static inline raw_ostream &operator<<(raw_ostream &os, const clang::ento::MemRegion* R) { R->dumpToStream(os); return os; } } // end llvm namespace #endif
0
repos/DirectXShaderCompiler/tools/clang/include/clang/StaticAnalyzer/Core
repos/DirectXShaderCompiler/tools/clang/include/clang/StaticAnalyzer/Core/PathSensitive/Store.h
//== Store.h - Interface for maps from Locations to Values ------*- C++ -*--==// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defined the types Store and StoreManager. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_STORE_H #define LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_STORE_H #include "clang/StaticAnalyzer/Core/PathSensitive/MemRegion.h" #include "clang/StaticAnalyzer/Core/PathSensitive/SValBuilder.h" #include "clang/StaticAnalyzer/Core/PathSensitive/StoreRef.h" #include "llvm/ADT/DenseSet.h" #include "llvm/ADT/Optional.h" namespace clang { class Stmt; class Expr; class ObjCIvarDecl; class CXXBasePath; class StackFrameContext; namespace ento { class CallEvent; class ProgramState; class ProgramStateManager; class ScanReachableSymbols; typedef llvm::DenseSet<SymbolRef> InvalidatedSymbols; class StoreManager { protected: SValBuilder &svalBuilder; ProgramStateManager &StateMgr; /// MRMgr - Manages region objects associated with this StoreManager. MemRegionManager &MRMgr; ASTContext &Ctx; StoreManager(ProgramStateManager &stateMgr); public: virtual ~StoreManager() {} /// Return the value bound to specified location in a given state. /// \param[in] store The analysis state. /// \param[in] loc The symbolic memory location. /// \param[in] T An optional type that provides a hint indicating the /// expected type of the returned value. This is used if the value is /// lazily computed. /// \return The value bound to the location \c loc. virtual SVal getBinding(Store store, Loc loc, QualType T = QualType()) = 0; /// Return a state with the specified value bound to the given location. /// \param[in] store The analysis state. /// \param[in] loc The symbolic memory location. /// \param[in] val The value to bind to location \c loc. /// \return A pointer to a ProgramState object that contains the same /// bindings as \c state with the addition of having the value specified /// by \c val bound to the location given for \c loc. virtual StoreRef Bind(Store store, Loc loc, SVal val) = 0; virtual StoreRef BindDefault(Store store, const MemRegion *R, SVal V); /// \brief Create a new store with the specified binding removed. /// \param ST the original store, that is the basis for the new store. /// \param L the location whose binding should be removed. virtual StoreRef killBinding(Store ST, Loc L) = 0; /// getInitialStore - Returns the initial "empty" store representing the /// value bindings upon entry to an analyzed function. virtual StoreRef getInitialStore(const LocationContext *InitLoc) = 0; /// getRegionManager - Returns the internal RegionManager object that is /// used to query and manipulate MemRegion objects. MemRegionManager& getRegionManager() { return MRMgr; } virtual Loc getLValueVar(const VarDecl *VD, const LocationContext *LC) { return svalBuilder.makeLoc(MRMgr.getVarRegion(VD, LC)); } Loc getLValueCompoundLiteral(const CompoundLiteralExpr *CL, const LocationContext *LC) { return loc::MemRegionVal(MRMgr.getCompoundLiteralRegion(CL, LC)); } virtual SVal getLValueIvar(const ObjCIvarDecl *decl, SVal base); virtual SVal getLValueField(const FieldDecl *D, SVal Base) { return getLValueFieldOrIvar(D, Base); } virtual SVal getLValueElement(QualType elementType, NonLoc offset, SVal Base); // FIXME: This should soon be eliminated altogether; clients should deal with // region extents directly. virtual DefinedOrUnknownSVal getSizeInElements(ProgramStateRef state, const MemRegion *region, QualType EleTy) { return UnknownVal(); } /// ArrayToPointer - Used by ExprEngine::VistCast to handle implicit /// conversions between arrays and pointers. virtual SVal ArrayToPointer(Loc Array, QualType ElementTy) = 0; /// Evaluates a chain of derived-to-base casts through the path specified in /// \p Cast. SVal evalDerivedToBase(SVal Derived, const CastExpr *Cast); /// Evaluates a chain of derived-to-base casts through the specified path. SVal evalDerivedToBase(SVal Derived, const CXXBasePath &CastPath); /// Evaluates a derived-to-base cast through a single level of derivation. SVal evalDerivedToBase(SVal Derived, QualType DerivedPtrType, bool IsVirtual); /// \brief Evaluates C++ dynamic_cast cast. /// The callback may result in the following 3 scenarios: /// - Successful cast (ex: derived is subclass of base). /// - Failed cast (ex: derived is definitely not a subclass of base). /// - We don't know (base is a symbolic region and we don't have /// enough info to determine if the cast will succeed at run time). /// The function returns an SVal representing the derived class; it's /// valid only if Failed flag is set to false. SVal evalDynamicCast(SVal Base, QualType DerivedPtrType, bool &Failed); const ElementRegion *GetElementZeroRegion(const MemRegion *R, QualType T); /// castRegion - Used by ExprEngine::VisitCast to handle casts from /// a MemRegion* to a specific location type. 'R' is the region being /// casted and 'CastToTy' the result type of the cast. const MemRegion *castRegion(const MemRegion *region, QualType CastToTy); virtual StoreRef removeDeadBindings(Store store, const StackFrameContext *LCtx, SymbolReaper& SymReaper) = 0; virtual bool includedInBindings(Store store, const MemRegion *region) const = 0; /// If the StoreManager supports it, increment the reference count of /// the specified Store object. virtual void incrementReferenceCount(Store store) {} /// If the StoreManager supports it, decrement the reference count of /// the specified Store object. If the reference count hits 0, the memory /// associated with the object is recycled. virtual void decrementReferenceCount(Store store) {} typedef SmallVector<const MemRegion *, 8> InvalidatedRegions; /// invalidateRegions - Clears out the specified regions from the store, /// marking their values as unknown. Depending on the store, this may also /// invalidate additional regions that may have changed based on accessing /// the given regions. Optionally, invalidates non-static globals as well. /// \param[in] store The initial store /// \param[in] Values The values to invalidate. /// \param[in] E The current statement being evaluated. Used to conjure /// symbols to mark the values of invalidated regions. /// \param[in] Count The current block count. Used to conjure /// symbols to mark the values of invalidated regions. /// \param[in] Call The call expression which will be used to determine which /// globals should get invalidated. /// \param[in,out] IS A set to fill with any symbols that are no longer /// accessible. Pass \c NULL if this information will not be used. /// \param[in] ITraits Information about invalidation for a particular /// region/symbol. /// \param[in,out] InvalidatedTopLevel A vector to fill with regions //// explicitly being invalidated. Pass \c NULL if this /// information will not be used. /// \param[in,out] Invalidated A vector to fill with any regions being /// invalidated. This should include any regions explicitly invalidated /// even if they do not currently have bindings. Pass \c NULL if this /// information will not be used. virtual StoreRef invalidateRegions(Store store, ArrayRef<SVal> Values, const Expr *E, unsigned Count, const LocationContext *LCtx, const CallEvent *Call, InvalidatedSymbols &IS, RegionAndSymbolInvalidationTraits &ITraits, InvalidatedRegions *InvalidatedTopLevel, InvalidatedRegions *Invalidated) = 0; /// enterStackFrame - Let the StoreManager to do something when execution /// engine is about to execute into a callee. StoreRef enterStackFrame(Store store, const CallEvent &Call, const StackFrameContext *CalleeCtx); /// Finds the transitive closure of symbols within the given region. /// /// Returns false if the visitor aborted the scan. virtual bool scanReachableSymbols(Store S, const MemRegion *R, ScanReachableSymbols &Visitor) = 0; virtual void print(Store store, raw_ostream &Out, const char* nl, const char *sep) = 0; class BindingsHandler { public: virtual ~BindingsHandler(); virtual bool HandleBinding(StoreManager& SMgr, Store store, const MemRegion *region, SVal val) = 0; }; class FindUniqueBinding : public BindingsHandler { SymbolRef Sym; const MemRegion* Binding; bool First; public: FindUniqueBinding(SymbolRef sym) : Sym(sym), Binding(nullptr), First(true) {} bool HandleBinding(StoreManager& SMgr, Store store, const MemRegion* R, SVal val) override; explicit operator bool() { return First && Binding; } const MemRegion *getRegion() { return Binding; } }; /// iterBindings - Iterate over the bindings in the Store. virtual void iterBindings(Store store, BindingsHandler& f) = 0; protected: const MemRegion *MakeElementRegion(const MemRegion *baseRegion, QualType pointeeTy, uint64_t index = 0); /// CastRetrievedVal - Used by subclasses of StoreManager to implement /// implicit casts that arise from loads from regions that are reinterpreted /// as another region. SVal CastRetrievedVal(SVal val, const TypedValueRegion *region, QualType castTy, bool performTestOnly = true); private: SVal getLValueFieldOrIvar(const Decl *decl, SVal base); }; inline StoreRef::StoreRef(Store store, StoreManager & smgr) : store(store), mgr(smgr) { if (store) mgr.incrementReferenceCount(store); } inline StoreRef::StoreRef(const StoreRef &sr) : store(sr.store), mgr(sr.mgr) { if (store) mgr.incrementReferenceCount(store); } inline StoreRef::~StoreRef() { if (store) mgr.decrementReferenceCount(store); } inline StoreRef &StoreRef::operator=(StoreRef const &newStore) { assert(&newStore.mgr == &mgr); if (store != newStore.store) { mgr.incrementReferenceCount(newStore.store); mgr.decrementReferenceCount(store); store = newStore.getStore(); } return *this; } // FIXME: Do we need to pass ProgramStateManager anymore? std::unique_ptr<StoreManager> CreateRegionStoreManager(ProgramStateManager &StMgr); std::unique_ptr<StoreManager> CreateFieldsOnlyRegionStoreManager(ProgramStateManager &StMgr); } // end GR namespace } // end clang namespace #endif
0
repos/DirectXShaderCompiler/tools/clang/include/clang/StaticAnalyzer/Core
repos/DirectXShaderCompiler/tools/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h
//===- CallEvent.h - Wrapper for all function and method calls ----*- C++ -*--// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // /// \file This file defines CallEvent and its subclasses, which represent path- /// sensitive instances of different kinds of function and method calls /// (C, C++, and Objective-C). // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_CALLEVENT_H #define LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_CALLEVENT_H #include "clang/AST/DeclCXX.h" #include "clang/AST/ExprCXX.h" #include "clang/AST/ExprObjC.h" #include "clang/Analysis/AnalysisContext.h" #include "clang/Basic/SourceManager.h" #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h" #include "clang/StaticAnalyzer/Core/PathSensitive/SVals.h" #include "llvm/ADT/PointerIntPair.h" namespace clang { class ProgramPoint; class ProgramPointTag; namespace ento { enum CallEventKind { CE_Function, CE_CXXMember, CE_CXXMemberOperator, CE_CXXDestructor, CE_BEG_CXX_INSTANCE_CALLS = CE_CXXMember, CE_END_CXX_INSTANCE_CALLS = CE_CXXDestructor, CE_CXXConstructor, CE_CXXAllocator, CE_BEG_FUNCTION_CALLS = CE_Function, CE_END_FUNCTION_CALLS = CE_CXXAllocator, CE_Block, CE_ObjCMessage }; class CallEvent; class CallEventManager; template<typename T = CallEvent> class CallEventRef : public IntrusiveRefCntPtr<const T> { public: CallEventRef(const T *Call) : IntrusiveRefCntPtr<const T>(Call) {} CallEventRef(const CallEventRef &Orig) : IntrusiveRefCntPtr<const T>(Orig) {} CallEventRef<T> cloneWithState(ProgramStateRef State) const { return this->get()->template cloneWithState<T>(State); } // Allow implicit conversions to a superclass type, since CallEventRef // behaves like a pointer-to-const. template <typename SuperT> operator CallEventRef<SuperT> () const { return this->get(); } }; /// \class RuntimeDefinition /// \brief Defines the runtime definition of the called function. /// /// Encapsulates the information we have about which Decl will be used /// when the call is executed on the given path. When dealing with dynamic /// dispatch, the information is based on DynamicTypeInfo and might not be /// precise. class RuntimeDefinition { /// The Declaration of the function which could be called at runtime. /// NULL if not available. const Decl *D; /// The region representing an object (ObjC/C++) on which the method is /// called. With dynamic dispatch, the method definition depends on the /// runtime type of this object. NULL when the DynamicTypeInfo is /// precise. const MemRegion *R; public: RuntimeDefinition(): D(nullptr), R(nullptr) {} RuntimeDefinition(const Decl *InD): D(InD), R(nullptr) {} RuntimeDefinition(const Decl *InD, const MemRegion *InR): D(InD), R(InR) {} const Decl *getDecl() { return D; } /// \brief Check if the definition we have is precise. /// If not, it is possible that the call dispatches to another definition at /// execution time. bool mayHaveOtherDefinitions() { return R != nullptr; } /// When other definitions are possible, returns the region whose runtime type /// determines the method definition. const MemRegion *getDispatchRegion() { return R; } }; /// \brief Represents an abstract call to a function or method along a /// particular path. /// /// CallEvents are created through the factory methods of CallEventManager. /// /// CallEvents should always be cheap to create and destroy. In order for /// CallEventManager to be able to re-use CallEvent-sized memory blocks, /// subclasses of CallEvent may not add any data members to the base class. /// Use the "Data" and "Location" fields instead. class CallEvent { public: typedef CallEventKind Kind; private: ProgramStateRef State; const LocationContext *LCtx; llvm::PointerUnion<const Expr *, const Decl *> Origin; void operator=(const CallEvent &) = delete; protected: // This is user data for subclasses. const void *Data; // This is user data for subclasses. // This should come right before RefCount, so that the two fields can be // packed together on LP64 platforms. SourceLocation Location; private: mutable unsigned RefCount; template <typename T> friend struct llvm::IntrusiveRefCntPtrInfo; void Retain() const { ++RefCount; } void Release() const; protected: friend class CallEventManager; CallEvent(const Expr *E, ProgramStateRef state, const LocationContext *lctx) : State(state), LCtx(lctx), Origin(E), RefCount(0) {} CallEvent(const Decl *D, ProgramStateRef state, const LocationContext *lctx) : State(state), LCtx(lctx), Origin(D), RefCount(0) {} // DO NOT MAKE PUBLIC CallEvent(const CallEvent &Original) : State(Original.State), LCtx(Original.LCtx), Origin(Original.Origin), Data(Original.Data), Location(Original.Location), RefCount(0) {} /// Copies this CallEvent, with vtable intact, into a new block of memory. virtual void cloneTo(void *Dest) const = 0; /// \brief Get the value of arbitrary expressions at this point in the path. SVal getSVal(const Stmt *S) const { return getState()->getSVal(S, getLocationContext()); } typedef SmallVectorImpl<SVal> ValueList; /// \brief Used to specify non-argument regions that will be invalidated as a /// result of this call. virtual void getExtraInvalidatedValues(ValueList &Values) const {} public: virtual ~CallEvent() {} /// \brief Returns the kind of call this is. virtual Kind getKind() const = 0; /// \brief Returns the declaration of the function or method that will be /// called. May be null. virtual const Decl *getDecl() const { return Origin.dyn_cast<const Decl *>(); } /// \brief The state in which the call is being evaluated. const ProgramStateRef &getState() const { return State; } /// \brief The context in which the call is being evaluated. const LocationContext *getLocationContext() const { return LCtx; } /// \brief Returns the definition of the function or method that will be /// called. virtual RuntimeDefinition getRuntimeDefinition() const = 0; /// \brief Returns the expression whose value will be the result of this call. /// May be null. const Expr *getOriginExpr() const { return Origin.dyn_cast<const Expr *>(); } /// \brief Returns the number of arguments (explicit and implicit). /// /// Note that this may be greater than the number of parameters in the /// callee's declaration, and that it may include arguments not written in /// the source. virtual unsigned getNumArgs() const = 0; /// \brief Returns true if the callee is known to be from a system header. bool isInSystemHeader() const { const Decl *D = getDecl(); if (!D) return false; SourceLocation Loc = D->getLocation(); if (Loc.isValid()) { const SourceManager &SM = getState()->getStateManager().getContext().getSourceManager(); return SM.isInSystemHeader(D->getLocation()); } // Special case for implicitly-declared global operator new/delete. // These should be considered system functions. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) return FD->isOverloadedOperator() && FD->isImplicit() && FD->isGlobal(); return false; } /// \brief Returns a source range for the entire call, suitable for /// outputting in diagnostics. virtual SourceRange getSourceRange() const { return getOriginExpr()->getSourceRange(); } /// \brief Returns the value of a given argument at the time of the call. virtual SVal getArgSVal(unsigned Index) const; /// \brief Returns the expression associated with a given argument. /// May be null if this expression does not appear in the source. virtual const Expr *getArgExpr(unsigned Index) const { return nullptr; } /// \brief Returns the source range for errors associated with this argument. /// /// May be invalid if the argument is not written in the source. virtual SourceRange getArgSourceRange(unsigned Index) const; /// \brief Returns the result type, adjusted for references. QualType getResultType() const; /// \brief Returns the return value of the call. /// /// This should only be called if the CallEvent was created using a state in /// which the return value has already been bound to the origin expression. SVal getReturnValue() const; /// \brief Returns true if any of the arguments appear to represent callbacks. bool hasNonZeroCallbackArg() const; /// \brief Returns true if any of the arguments are known to escape to long- /// term storage, even if this method will not modify them. // NOTE: The exact semantics of this are still being defined! // We don't really want a list of hardcoded exceptions in the long run, // but we don't want duplicated lists of known APIs in the short term either. virtual bool argumentsMayEscape() const { return hasNonZeroCallbackArg(); } /// \brief Returns true if the callee is an externally-visible function in the /// top-level namespace, such as \c malloc. /// /// You can use this call to determine that a particular function really is /// a library function and not, say, a C++ member function with the same name. /// /// If a name is provided, the function must additionally match the given /// name. /// /// Note that this deliberately excludes C++ library functions in the \c std /// namespace, but will include C library functions accessed through the /// \c std namespace. This also does not check if the function is declared /// as 'extern "C"', or if it uses C++ name mangling. // FIXME: Add a helper for checking namespaces. // FIXME: Move this down to AnyFunctionCall once checkers have more // precise callbacks. bool isGlobalCFunction(StringRef SpecificName = StringRef()) const; /// \brief Returns the name of the callee, if its name is a simple identifier. /// /// Note that this will fail for Objective-C methods, blocks, and C++ /// overloaded operators. The former is named by a Selector rather than a /// simple identifier, and the latter two do not have names. // FIXME: Move this down to AnyFunctionCall once checkers have more // precise callbacks. const IdentifierInfo *getCalleeIdentifier() const { const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(getDecl()); if (!ND) return nullptr; return ND->getIdentifier(); } /// \brief Returns an appropriate ProgramPoint for this call. ProgramPoint getProgramPoint(bool IsPreVisit = false, const ProgramPointTag *Tag = nullptr) const; /// \brief Returns a new state with all argument regions invalidated. /// /// This accepts an alternate state in case some processing has already /// occurred. ProgramStateRef invalidateRegions(unsigned BlockCount, ProgramStateRef Orig = nullptr) const; typedef std::pair<Loc, SVal> FrameBindingTy; typedef SmallVectorImpl<FrameBindingTy> BindingsTy; /// Populates the given SmallVector with the bindings in the callee's stack /// frame at the start of this call. virtual void getInitialStackFrameContents(const StackFrameContext *CalleeCtx, BindingsTy &Bindings) const = 0; /// Returns a copy of this CallEvent, but using the given state. template <typename T> CallEventRef<T> cloneWithState(ProgramStateRef NewState) const; /// Returns a copy of this CallEvent, but using the given state. CallEventRef<> cloneWithState(ProgramStateRef NewState) const { return cloneWithState<CallEvent>(NewState); } /// \brief Returns true if this is a statement is a function or method call /// of some kind. static bool isCallStmt(const Stmt *S); /// \brief Returns the result type of a function or method declaration. /// /// This will return a null QualType if the result type cannot be determined. static QualType getDeclaredResultType(const Decl *D); /// \brief Returns true if the given decl is known to be variadic. /// /// \p D must not be null. static bool isVariadic(const Decl *D); // Iterator access to formal parameters and their types. private: typedef std::const_mem_fun_t<QualType, ParmVarDecl> get_type_fun; public: /// Return call's formal parameters. /// /// Remember that the number of formal parameters may not match the number /// of arguments for all calls. However, the first parameter will always /// correspond with the argument value returned by \c getArgSVal(0). virtual ArrayRef<ParmVarDecl*> parameters() const = 0; typedef llvm::mapped_iterator<ArrayRef<ParmVarDecl*>::iterator, get_type_fun> param_type_iterator; /// Returns an iterator over the types of the call's formal parameters. /// /// This uses the callee decl found by default name lookup rather than the /// definition because it represents a public interface, and probably has /// more annotations. param_type_iterator param_type_begin() const { return llvm::map_iterator(parameters().begin(), get_type_fun(&ParmVarDecl::getType)); } /// \sa param_type_begin() param_type_iterator param_type_end() const { return llvm::map_iterator(parameters().end(), get_type_fun(&ParmVarDecl::getType)); } // For debugging purposes only void dump(raw_ostream &Out) const; void dump() const; }; /// \brief Represents a call to any sort of function that might have a /// FunctionDecl. class AnyFunctionCall : public CallEvent { protected: AnyFunctionCall(const Expr *E, ProgramStateRef St, const LocationContext *LCtx) : CallEvent(E, St, LCtx) {} AnyFunctionCall(const Decl *D, ProgramStateRef St, const LocationContext *LCtx) : CallEvent(D, St, LCtx) {} AnyFunctionCall(const AnyFunctionCall &Other) : CallEvent(Other) {} public: // This function is overridden by subclasses, but they must return // a FunctionDecl. const FunctionDecl *getDecl() const override { return cast<FunctionDecl>(CallEvent::getDecl()); } RuntimeDefinition getRuntimeDefinition() const override { const FunctionDecl *FD = getDecl(); // Note that the AnalysisDeclContext will have the FunctionDecl with // the definition (if one exists). if (FD) { AnalysisDeclContext *AD = getLocationContext()->getAnalysisDeclContext()-> getManager()->getContext(FD); if (AD->getBody()) return RuntimeDefinition(AD->getDecl()); } return RuntimeDefinition(); } bool argumentsMayEscape() const override; void getInitialStackFrameContents(const StackFrameContext *CalleeCtx, BindingsTy &Bindings) const override; ArrayRef<ParmVarDecl *> parameters() const override; static bool classof(const CallEvent *CA) { return CA->getKind() >= CE_BEG_FUNCTION_CALLS && CA->getKind() <= CE_END_FUNCTION_CALLS; } }; /// \brief Represents a C function or static C++ member function call. /// /// Example: \c fun() class SimpleFunctionCall : public AnyFunctionCall { friend class CallEventManager; protected: SimpleFunctionCall(const CallExpr *CE, ProgramStateRef St, const LocationContext *LCtx) : AnyFunctionCall(CE, St, LCtx) {} SimpleFunctionCall(const SimpleFunctionCall &Other) : AnyFunctionCall(Other) {} void cloneTo(void *Dest) const override { new (Dest) SimpleFunctionCall(*this); } public: virtual const CallExpr *getOriginExpr() const { return cast<CallExpr>(AnyFunctionCall::getOriginExpr()); } const FunctionDecl *getDecl() const override; unsigned getNumArgs() const override { return getOriginExpr()->getNumArgs(); } const Expr *getArgExpr(unsigned Index) const override { return getOriginExpr()->getArg(Index); } Kind getKind() const override { return CE_Function; } static bool classof(const CallEvent *CA) { return CA->getKind() == CE_Function; } }; /// \brief Represents a call to a block. /// /// Example: <tt>^{ /* ... */ }()</tt> class BlockCall : public CallEvent { friend class CallEventManager; protected: BlockCall(const CallExpr *CE, ProgramStateRef St, const LocationContext *LCtx) : CallEvent(CE, St, LCtx) {} BlockCall(const BlockCall &Other) : CallEvent(Other) {} void cloneTo(void *Dest) const override { new (Dest) BlockCall(*this); } void getExtraInvalidatedValues(ValueList &Values) const override; public: virtual const CallExpr *getOriginExpr() const { return cast<CallExpr>(CallEvent::getOriginExpr()); } unsigned getNumArgs() const override { return getOriginExpr()->getNumArgs(); } const Expr *getArgExpr(unsigned Index) const override { return getOriginExpr()->getArg(Index); } /// \brief Returns the region associated with this instance of the block. /// /// This may be NULL if the block's origin is unknown. const BlockDataRegion *getBlockRegion() const; const BlockDecl *getDecl() const override { const BlockDataRegion *BR = getBlockRegion(); if (!BR) return nullptr; return BR->getDecl(); } RuntimeDefinition getRuntimeDefinition() const override { return RuntimeDefinition(getDecl()); } bool argumentsMayEscape() const override { return true; } void getInitialStackFrameContents(const StackFrameContext *CalleeCtx, BindingsTy &Bindings) const override; ArrayRef<ParmVarDecl*> parameters() const override; Kind getKind() const override { return CE_Block; } static bool classof(const CallEvent *CA) { return CA->getKind() == CE_Block; } }; /// \brief Represents a non-static C++ member function call, no matter how /// it is written. class CXXInstanceCall : public AnyFunctionCall { protected: void getExtraInvalidatedValues(ValueList &Values) const override; CXXInstanceCall(const CallExpr *CE, ProgramStateRef St, const LocationContext *LCtx) : AnyFunctionCall(CE, St, LCtx) {} CXXInstanceCall(const FunctionDecl *D, ProgramStateRef St, const LocationContext *LCtx) : AnyFunctionCall(D, St, LCtx) {} CXXInstanceCall(const CXXInstanceCall &Other) : AnyFunctionCall(Other) {} public: /// \brief Returns the expression representing the implicit 'this' object. virtual const Expr *getCXXThisExpr() const { return nullptr; } /// \brief Returns the value of the implicit 'this' object. virtual SVal getCXXThisVal() const; const FunctionDecl *getDecl() const override; RuntimeDefinition getRuntimeDefinition() const override; void getInitialStackFrameContents(const StackFrameContext *CalleeCtx, BindingsTy &Bindings) const override; static bool classof(const CallEvent *CA) { return CA->getKind() >= CE_BEG_CXX_INSTANCE_CALLS && CA->getKind() <= CE_END_CXX_INSTANCE_CALLS; } }; /// \brief Represents a non-static C++ member function call. /// /// Example: \c obj.fun() class CXXMemberCall : public CXXInstanceCall { friend class CallEventManager; protected: CXXMemberCall(const CXXMemberCallExpr *CE, ProgramStateRef St, const LocationContext *LCtx) : CXXInstanceCall(CE, St, LCtx) {} CXXMemberCall(const CXXMemberCall &Other) : CXXInstanceCall(Other) {} void cloneTo(void *Dest) const override { new (Dest) CXXMemberCall(*this); } public: virtual const CXXMemberCallExpr *getOriginExpr() const { return cast<CXXMemberCallExpr>(CXXInstanceCall::getOriginExpr()); } unsigned getNumArgs() const override { if (const CallExpr *CE = getOriginExpr()) return CE->getNumArgs(); return 0; } const Expr *getArgExpr(unsigned Index) const override { return getOriginExpr()->getArg(Index); } const Expr *getCXXThisExpr() const override; RuntimeDefinition getRuntimeDefinition() const override; Kind getKind() const override { return CE_CXXMember; } static bool classof(const CallEvent *CA) { return CA->getKind() == CE_CXXMember; } }; /// \brief Represents a C++ overloaded operator call where the operator is /// implemented as a non-static member function. /// /// Example: <tt>iter + 1</tt> class CXXMemberOperatorCall : public CXXInstanceCall { friend class CallEventManager; protected: CXXMemberOperatorCall(const CXXOperatorCallExpr *CE, ProgramStateRef St, const LocationContext *LCtx) : CXXInstanceCall(CE, St, LCtx) {} CXXMemberOperatorCall(const CXXMemberOperatorCall &Other) : CXXInstanceCall(Other) {} void cloneTo(void *Dest) const override { new (Dest) CXXMemberOperatorCall(*this); } public: virtual const CXXOperatorCallExpr *getOriginExpr() const { return cast<CXXOperatorCallExpr>(CXXInstanceCall::getOriginExpr()); } unsigned getNumArgs() const override { return getOriginExpr()->getNumArgs() - 1; } const Expr *getArgExpr(unsigned Index) const override { return getOriginExpr()->getArg(Index + 1); } const Expr *getCXXThisExpr() const override; Kind getKind() const override { return CE_CXXMemberOperator; } static bool classof(const CallEvent *CA) { return CA->getKind() == CE_CXXMemberOperator; } }; /// \brief Represents an implicit call to a C++ destructor. /// /// This can occur at the end of a scope (for automatic objects), at the end /// of a full-expression (for temporaries), or as part of a delete. class CXXDestructorCall : public CXXInstanceCall { friend class CallEventManager; protected: typedef llvm::PointerIntPair<const MemRegion *, 1, bool> DtorDataTy; /// Creates an implicit destructor. /// /// \param DD The destructor that will be called. /// \param Trigger The statement whose completion causes this destructor call. /// \param Target The object region to be destructed. /// \param St The path-sensitive state at this point in the program. /// \param LCtx The location context at this point in the program. CXXDestructorCall(const CXXDestructorDecl *DD, const Stmt *Trigger, const MemRegion *Target, bool IsBaseDestructor, ProgramStateRef St, const LocationContext *LCtx) : CXXInstanceCall(DD, St, LCtx) { Data = DtorDataTy(Target, IsBaseDestructor).getOpaqueValue(); Location = Trigger->getLocEnd(); } CXXDestructorCall(const CXXDestructorCall &Other) : CXXInstanceCall(Other) {} void cloneTo(void *Dest) const override {new (Dest) CXXDestructorCall(*this);} public: SourceRange getSourceRange() const override { return Location; } unsigned getNumArgs() const override { return 0; } RuntimeDefinition getRuntimeDefinition() const override; /// \brief Returns the value of the implicit 'this' object. SVal getCXXThisVal() const override; /// Returns true if this is a call to a base class destructor. bool isBaseDestructor() const { return DtorDataTy::getFromOpaqueValue(Data).getInt(); } Kind getKind() const override { return CE_CXXDestructor; } static bool classof(const CallEvent *CA) { return CA->getKind() == CE_CXXDestructor; } }; /// \brief Represents a call to a C++ constructor. /// /// Example: \c T(1) class CXXConstructorCall : public AnyFunctionCall { friend class CallEventManager; protected: /// Creates a constructor call. /// /// \param CE The constructor expression as written in the source. /// \param Target The region where the object should be constructed. If NULL, /// a new symbolic region will be used. /// \param St The path-sensitive state at this point in the program. /// \param LCtx The location context at this point in the program. CXXConstructorCall(const CXXConstructExpr *CE, const MemRegion *Target, ProgramStateRef St, const LocationContext *LCtx) : AnyFunctionCall(CE, St, LCtx) { Data = Target; } CXXConstructorCall(const CXXConstructorCall &Other) : AnyFunctionCall(Other){} void cloneTo(void *Dest) const override { new (Dest) CXXConstructorCall(*this); } void getExtraInvalidatedValues(ValueList &Values) const override; public: virtual const CXXConstructExpr *getOriginExpr() const { return cast<CXXConstructExpr>(AnyFunctionCall::getOriginExpr()); } const CXXConstructorDecl *getDecl() const override { return getOriginExpr()->getConstructor(); } unsigned getNumArgs() const override { return getOriginExpr()->getNumArgs(); } const Expr *getArgExpr(unsigned Index) const override { return getOriginExpr()->getArg(Index); } /// \brief Returns the value of the implicit 'this' object. SVal getCXXThisVal() const; void getInitialStackFrameContents(const StackFrameContext *CalleeCtx, BindingsTy &Bindings) const override; Kind getKind() const override { return CE_CXXConstructor; } static bool classof(const CallEvent *CA) { return CA->getKind() == CE_CXXConstructor; } }; /// \brief Represents the memory allocation call in a C++ new-expression. /// /// This is a call to "operator new". class CXXAllocatorCall : public AnyFunctionCall { friend class CallEventManager; protected: CXXAllocatorCall(const CXXNewExpr *E, ProgramStateRef St, const LocationContext *LCtx) : AnyFunctionCall(E, St, LCtx) {} CXXAllocatorCall(const CXXAllocatorCall &Other) : AnyFunctionCall(Other) {} void cloneTo(void *Dest) const override { new (Dest) CXXAllocatorCall(*this); } public: virtual const CXXNewExpr *getOriginExpr() const { return cast<CXXNewExpr>(AnyFunctionCall::getOriginExpr()); } const FunctionDecl *getDecl() const override { return getOriginExpr()->getOperatorNew(); } unsigned getNumArgs() const override { return getOriginExpr()->getNumPlacementArgs() + 1; } const Expr *getArgExpr(unsigned Index) const override { // The first argument of an allocator call is the size of the allocation. if (Index == 0) return nullptr; return getOriginExpr()->getPlacementArg(Index - 1); } Kind getKind() const override { return CE_CXXAllocator; } static bool classof(const CallEvent *CE) { return CE->getKind() == CE_CXXAllocator; } }; /// \brief Represents the ways an Objective-C message send can occur. // // Note to maintainers: OCM_Message should always be last, since it does not // need to fit in the Data field's low bits. enum ObjCMessageKind { OCM_PropertyAccess, OCM_Subscript, OCM_Message }; /// \brief Represents any expression that calls an Objective-C method. /// /// This includes all of the kinds listed in ObjCMessageKind. class ObjCMethodCall : public CallEvent { friend class CallEventManager; const PseudoObjectExpr *getContainingPseudoObjectExpr() const; protected: ObjCMethodCall(const ObjCMessageExpr *Msg, ProgramStateRef St, const LocationContext *LCtx) : CallEvent(Msg, St, LCtx) { Data = nullptr; } ObjCMethodCall(const ObjCMethodCall &Other) : CallEvent(Other) {} void cloneTo(void *Dest) const override { new (Dest) ObjCMethodCall(*this); } void getExtraInvalidatedValues(ValueList &Values) const override; /// Check if the selector may have multiple definitions (may have overrides). virtual bool canBeOverridenInSubclass(ObjCInterfaceDecl *IDecl, Selector Sel) const; public: virtual const ObjCMessageExpr *getOriginExpr() const { return cast<ObjCMessageExpr>(CallEvent::getOriginExpr()); } const ObjCMethodDecl *getDecl() const override { return getOriginExpr()->getMethodDecl(); } unsigned getNumArgs() const override { return getOriginExpr()->getNumArgs(); } const Expr *getArgExpr(unsigned Index) const override { return getOriginExpr()->getArg(Index); } bool isInstanceMessage() const { return getOriginExpr()->isInstanceMessage(); } ObjCMethodFamily getMethodFamily() const { return getOriginExpr()->getMethodFamily(); } Selector getSelector() const { return getOriginExpr()->getSelector(); } SourceRange getSourceRange() const override; /// \brief Returns the value of the receiver at the time of this call. SVal getReceiverSVal() const; /// \brief Return the value of 'self' if available. SVal getSelfSVal() const; /// \brief Get the interface for the receiver. /// /// This works whether this is an instance message or a class message. /// However, it currently just uses the static type of the receiver. const ObjCInterfaceDecl *getReceiverInterface() const { return getOriginExpr()->getReceiverInterface(); } /// \brief Checks if the receiver refers to 'self' or 'super'. bool isReceiverSelfOrSuper() const; /// Returns how the message was written in the source (property access, /// subscript, or explicit message send). ObjCMessageKind getMessageKind() const; /// Returns true if this property access or subscript is a setter (has the /// form of an assignment). bool isSetter() const { switch (getMessageKind()) { case OCM_Message: llvm_unreachable("This is not a pseudo-object access!"); case OCM_PropertyAccess: return getNumArgs() > 0; case OCM_Subscript: return getNumArgs() > 1; } llvm_unreachable("Unknown message kind"); } RuntimeDefinition getRuntimeDefinition() const override; bool argumentsMayEscape() const override; void getInitialStackFrameContents(const StackFrameContext *CalleeCtx, BindingsTy &Bindings) const override; ArrayRef<ParmVarDecl*> parameters() const override; Kind getKind() const override { return CE_ObjCMessage; } static bool classof(const CallEvent *CA) { return CA->getKind() == CE_ObjCMessage; } }; /// \brief Manages the lifetime of CallEvent objects. /// /// CallEventManager provides a way to create arbitrary CallEvents "on the /// stack" as if they were value objects by keeping a cache of CallEvent-sized /// memory blocks. The CallEvents created by CallEventManager are only valid /// for the lifetime of the OwnedCallEvent that holds them; right now these /// objects cannot be copied and ownership cannot be transferred. class CallEventManager { friend class CallEvent; llvm::BumpPtrAllocator &Alloc; SmallVector<void *, 8> Cache; typedef SimpleFunctionCall CallEventTemplateTy; void reclaim(const void *Memory) { Cache.push_back(const_cast<void *>(Memory)); } /// Returns memory that can be initialized as a CallEvent. void *allocate() { if (Cache.empty()) return Alloc.Allocate<CallEventTemplateTy>(); else return Cache.pop_back_val(); } template <typename T, typename Arg> T *create(Arg A, ProgramStateRef St, const LocationContext *LCtx) { static_assert(sizeof(T) == sizeof(CallEventTemplateTy), "CallEvent subclasses are not all the same size"); return new (allocate()) T(A, St, LCtx); } template <typename T, typename Arg1, typename Arg2> T *create(Arg1 A1, Arg2 A2, ProgramStateRef St, const LocationContext *LCtx) { static_assert(sizeof(T) == sizeof(CallEventTemplateTy), "CallEvent subclasses are not all the same size"); return new (allocate()) T(A1, A2, St, LCtx); } template <typename T, typename Arg1, typename Arg2, typename Arg3> T *create(Arg1 A1, Arg2 A2, Arg3 A3, ProgramStateRef St, const LocationContext *LCtx) { static_assert(sizeof(T) == sizeof(CallEventTemplateTy), "CallEvent subclasses are not all the same size"); return new (allocate()) T(A1, A2, A3, St, LCtx); } template <typename T, typename Arg1, typename Arg2, typename Arg3, typename Arg4> T *create(Arg1 A1, Arg2 A2, Arg3 A3, Arg4 A4, ProgramStateRef St, const LocationContext *LCtx) { static_assert(sizeof(T) == sizeof(CallEventTemplateTy), "CallEvent subclasses are not all the same size"); return new (allocate()) T(A1, A2, A3, A4, St, LCtx); } public: CallEventManager(llvm::BumpPtrAllocator &alloc) : Alloc(alloc) {} CallEventRef<> getCaller(const StackFrameContext *CalleeCtx, ProgramStateRef State); CallEventRef<> getSimpleCall(const CallExpr *E, ProgramStateRef State, const LocationContext *LCtx); CallEventRef<ObjCMethodCall> getObjCMethodCall(const ObjCMessageExpr *E, ProgramStateRef State, const LocationContext *LCtx) { return create<ObjCMethodCall>(E, State, LCtx); } CallEventRef<CXXConstructorCall> getCXXConstructorCall(const CXXConstructExpr *E, const MemRegion *Target, ProgramStateRef State, const LocationContext *LCtx) { return create<CXXConstructorCall>(E, Target, State, LCtx); } CallEventRef<CXXDestructorCall> getCXXDestructorCall(const CXXDestructorDecl *DD, const Stmt *Trigger, const MemRegion *Target, bool IsBase, ProgramStateRef State, const LocationContext *LCtx) { return create<CXXDestructorCall>(DD, Trigger, Target, IsBase, State, LCtx); } CallEventRef<CXXAllocatorCall> getCXXAllocatorCall(const CXXNewExpr *E, ProgramStateRef State, const LocationContext *LCtx) { return create<CXXAllocatorCall>(E, State, LCtx); } }; template <typename T> CallEventRef<T> CallEvent::cloneWithState(ProgramStateRef NewState) const { assert(isa<T>(*this) && "Cloning to unrelated type"); static_assert(sizeof(T) == sizeof(CallEvent), "Subclasses may not add fields"); if (NewState == State) return cast<T>(this); CallEventManager &Mgr = State->getStateManager().getCallEventManager(); T *Copy = static_cast<T *>(Mgr.allocate()); cloneTo(Copy); assert(Copy->getKind() == this->getKind() && "Bad copy"); Copy->State = NewState; return Copy; } inline void CallEvent::Release() const { assert(RefCount > 0 && "Reference count is already zero."); --RefCount; if (RefCount > 0) return; CallEventManager &Mgr = State->getStateManager().getCallEventManager(); Mgr.reclaim(this); this->~CallEvent(); } } // end namespace ento } // end namespace clang namespace llvm { // Support isa<>, cast<>, and dyn_cast<> for CallEventRef. template<class T> struct simplify_type< clang::ento::CallEventRef<T> > { typedef const T *SimpleType; static SimpleType getSimplifiedValue(clang::ento::CallEventRef<T> Val) { return Val.get(); } }; } #endif
0
repos/DirectXShaderCompiler/tools/clang/include/clang/StaticAnalyzer/Core
repos/DirectXShaderCompiler/tools/clang/include/clang/StaticAnalyzer/Core/PathSensitive/SValBuilder.h
// SValBuilder.h - Construction of SVals from evaluating expressions -*- C++ -*- // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines SValBuilder, a class that defines the interface for // "symbolical evaluators" which construct an SVal from an expression. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_SVALBUILDER_H #define LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_SVALBUILDER_H #include "clang/AST/ASTContext.h" #include "clang/AST/Expr.h" #include "clang/AST/ExprObjC.h" #include "clang/StaticAnalyzer/Core/PathSensitive/BasicValueFactory.h" #include "clang/StaticAnalyzer/Core/PathSensitive/MemRegion.h" #include "clang/StaticAnalyzer/Core/PathSensitive/SVals.h" namespace clang { class CXXBoolLiteralExpr; namespace ento { class SValBuilder { virtual void anchor(); protected: ASTContext &Context; /// Manager of APSInt values. BasicValueFactory BasicVals; /// Manages the creation of symbols. SymbolManager SymMgr; /// Manages the creation of memory regions. MemRegionManager MemMgr; ProgramStateManager &StateMgr; /// The scalar type to use for array indices. const QualType ArrayIndexTy; /// The width of the scalar type used for array indices. const unsigned ArrayIndexWidth; virtual SVal evalCastFromNonLoc(NonLoc val, QualType castTy) = 0; virtual SVal evalCastFromLoc(Loc val, QualType castTy) = 0; public: // FIXME: Make these protected again once RegionStoreManager correctly // handles loads from different bound value types. virtual SVal dispatchCast(SVal val, QualType castTy) = 0; public: SValBuilder(llvm::BumpPtrAllocator &alloc, ASTContext &context, ProgramStateManager &stateMgr) : Context(context), BasicVals(context, alloc), SymMgr(context, BasicVals, alloc), MemMgr(context, alloc), StateMgr(stateMgr), ArrayIndexTy(context.IntTy), ArrayIndexWidth(context.getTypeSize(ArrayIndexTy)) {} virtual ~SValBuilder() {} bool haveSameType(const SymExpr *Sym1, const SymExpr *Sym2) { return haveSameType(Sym1->getType(), Sym2->getType()); } bool haveSameType(QualType Ty1, QualType Ty2) { // FIXME: Remove the second disjunct when we support symbolic // truncation/extension. return (Context.getCanonicalType(Ty1) == Context.getCanonicalType(Ty2) || (Ty1->isIntegralOrEnumerationType() && Ty2->isIntegralOrEnumerationType())); } SVal evalCast(SVal val, QualType castTy, QualType originalType); virtual SVal evalMinus(NonLoc val) = 0; virtual SVal evalComplement(NonLoc val) = 0; /// Create a new value which represents a binary expression with two non- /// location operands. virtual SVal evalBinOpNN(ProgramStateRef state, BinaryOperator::Opcode op, NonLoc lhs, NonLoc rhs, QualType resultTy) = 0; /// Create a new value which represents a binary expression with two memory /// location operands. virtual SVal evalBinOpLL(ProgramStateRef state, BinaryOperator::Opcode op, Loc lhs, Loc rhs, QualType resultTy) = 0; /// Create a new value which represents a binary expression with a memory /// location and non-location operands. For example, this would be used to /// evaluate a pointer arithmetic operation. virtual SVal evalBinOpLN(ProgramStateRef state, BinaryOperator::Opcode op, Loc lhs, NonLoc rhs, QualType resultTy) = 0; /// Evaluates a given SVal. If the SVal has only one possible (integer) value, /// that value is returned. Otherwise, returns NULL. virtual const llvm::APSInt *getKnownValue(ProgramStateRef state, SVal val) = 0; /// Constructs a symbolic expression for two non-location values. SVal makeSymExprValNN(ProgramStateRef state, BinaryOperator::Opcode op, NonLoc lhs, NonLoc rhs, QualType resultTy); SVal evalBinOp(ProgramStateRef state, BinaryOperator::Opcode op, SVal lhs, SVal rhs, QualType type); DefinedOrUnknownSVal evalEQ(ProgramStateRef state, DefinedOrUnknownSVal lhs, DefinedOrUnknownSVal rhs); ASTContext &getContext() { return Context; } const ASTContext &getContext() const { return Context; } ProgramStateManager &getStateManager() { return StateMgr; } QualType getConditionType() const { return Context.getLangOpts().CPlusPlus ? Context.BoolTy : Context.IntTy; } QualType getArrayIndexType() const { return ArrayIndexTy; } BasicValueFactory &getBasicValueFactory() { return BasicVals; } const BasicValueFactory &getBasicValueFactory() const { return BasicVals; } SymbolManager &getSymbolManager() { return SymMgr; } const SymbolManager &getSymbolManager() const { return SymMgr; } MemRegionManager &getRegionManager() { return MemMgr; } const MemRegionManager &getRegionManager() const { return MemMgr; } // Forwarding methods to SymbolManager. const SymbolConjured* conjureSymbol(const Stmt *stmt, const LocationContext *LCtx, QualType type, unsigned visitCount, const void *symbolTag = nullptr) { return SymMgr.conjureSymbol(stmt, LCtx, type, visitCount, symbolTag); } const SymbolConjured* conjureSymbol(const Expr *expr, const LocationContext *LCtx, unsigned visitCount, const void *symbolTag = nullptr) { return SymMgr.conjureSymbol(expr, LCtx, visitCount, symbolTag); } /// Construct an SVal representing '0' for the specified type. DefinedOrUnknownSVal makeZeroVal(QualType type); /// Make a unique symbol for value of region. DefinedOrUnknownSVal getRegionValueSymbolVal(const TypedValueRegion *region); /// \brief Create a new symbol with a unique 'name'. /// /// We resort to conjured symbols when we cannot construct a derived symbol. /// The advantage of symbols derived/built from other symbols is that we /// preserve the relation between related(or even equivalent) expressions, so /// conjured symbols should be used sparingly. DefinedOrUnknownSVal conjureSymbolVal(const void *symbolTag, const Expr *expr, const LocationContext *LCtx, unsigned count); DefinedOrUnknownSVal conjureSymbolVal(const void *symbolTag, const Expr *expr, const LocationContext *LCtx, QualType type, unsigned count); DefinedOrUnknownSVal conjureSymbolVal(const Stmt *stmt, const LocationContext *LCtx, QualType type, unsigned visitCount); /// \brief Conjure a symbol representing heap allocated memory region. /// /// Note, the expression should represent a location. DefinedOrUnknownSVal getConjuredHeapSymbolVal(const Expr *E, const LocationContext *LCtx, unsigned Count); DefinedOrUnknownSVal getDerivedRegionValueSymbolVal( SymbolRef parentSymbol, const TypedValueRegion *region); DefinedSVal getMetadataSymbolVal( const void *symbolTag, const MemRegion *region, const Expr *expr, QualType type, unsigned count); DefinedSVal getFunctionPointer(const FunctionDecl *func); DefinedSVal getBlockPointer(const BlockDecl *block, CanQualType locTy, const LocationContext *locContext, unsigned blockCount); /// Returns the value of \p E, if it can be determined in a non-path-sensitive /// manner. /// /// If \p E is not a constant or cannot be modeled, returns \c None. Optional<SVal> getConstantVal(const Expr *E); NonLoc makeCompoundVal(QualType type, llvm::ImmutableList<SVal> vals) { return nonloc::CompoundVal(BasicVals.getCompoundValData(type, vals)); } NonLoc makeLazyCompoundVal(const StoreRef &store, const TypedValueRegion *region) { return nonloc::LazyCompoundVal( BasicVals.getLazyCompoundValData(store, region)); } NonLoc makeZeroArrayIndex() { return nonloc::ConcreteInt(BasicVals.getValue(0, ArrayIndexTy)); } NonLoc makeArrayIndex(uint64_t idx) { return nonloc::ConcreteInt(BasicVals.getValue(idx, ArrayIndexTy)); } SVal convertToArrayIndex(SVal val); nonloc::ConcreteInt makeIntVal(const IntegerLiteral* integer) { return nonloc::ConcreteInt( BasicVals.getValue(integer->getValue(), integer->getType()->isUnsignedIntegerOrEnumerationType())); } nonloc::ConcreteInt makeBoolVal(const ObjCBoolLiteralExpr *boolean) { return makeTruthVal(boolean->getValue(), boolean->getType()); } nonloc::ConcreteInt makeBoolVal(const CXXBoolLiteralExpr *boolean); nonloc::ConcreteInt makeIntVal(const llvm::APSInt& integer) { return nonloc::ConcreteInt(BasicVals.getValue(integer)); } loc::ConcreteInt makeIntLocVal(const llvm::APSInt &integer) { return loc::ConcreteInt(BasicVals.getValue(integer)); } NonLoc makeIntVal(const llvm::APInt& integer, bool isUnsigned) { return nonloc::ConcreteInt(BasicVals.getValue(integer, isUnsigned)); } DefinedSVal makeIntVal(uint64_t integer, QualType type) { if (Loc::isLocType(type)) return loc::ConcreteInt(BasicVals.getValue(integer, type)); return nonloc::ConcreteInt(BasicVals.getValue(integer, type)); } NonLoc makeIntVal(uint64_t integer, bool isUnsigned) { return nonloc::ConcreteInt(BasicVals.getIntValue(integer, isUnsigned)); } NonLoc makeIntValWithPtrWidth(uint64_t integer, bool isUnsigned) { return nonloc::ConcreteInt( BasicVals.getIntWithPtrWidth(integer, isUnsigned)); } NonLoc makeLocAsInteger(Loc loc, unsigned bits) { return nonloc::LocAsInteger(BasicVals.getPersistentSValWithData(loc, bits)); } NonLoc makeNonLoc(const SymExpr *lhs, BinaryOperator::Opcode op, const llvm::APSInt& rhs, QualType type); NonLoc makeNonLoc(const llvm::APSInt& rhs, BinaryOperator::Opcode op, const SymExpr *lhs, QualType type); NonLoc makeNonLoc(const SymExpr *lhs, BinaryOperator::Opcode op, const SymExpr *rhs, QualType type); /// \brief Create a NonLoc value for cast. NonLoc makeNonLoc(const SymExpr *operand, QualType fromTy, QualType toTy); nonloc::ConcreteInt makeTruthVal(bool b, QualType type) { return nonloc::ConcreteInt(BasicVals.getTruthValue(b, type)); } nonloc::ConcreteInt makeTruthVal(bool b) { return nonloc::ConcreteInt(BasicVals.getTruthValue(b)); } Loc makeNull() { return loc::ConcreteInt(BasicVals.getZeroWithPtrWidth()); } Loc makeLoc(SymbolRef sym) { return loc::MemRegionVal(MemMgr.getSymbolicRegion(sym)); } Loc makeLoc(const MemRegion* region) { return loc::MemRegionVal(region); } Loc makeLoc(const AddrLabelExpr *expr) { return loc::GotoLabel(expr->getLabel()); } Loc makeLoc(const llvm::APSInt& integer) { return loc::ConcreteInt(BasicVals.getValue(integer)); } /// Return a memory region for the 'this' object reference. loc::MemRegionVal getCXXThis(const CXXMethodDecl *D, const StackFrameContext *SFC); /// Return a memory region for the 'this' object reference. loc::MemRegionVal getCXXThis(const CXXRecordDecl *D, const StackFrameContext *SFC); }; SValBuilder* createSimpleSValBuilder(llvm::BumpPtrAllocator &alloc, ASTContext &context, ProgramStateManager &stateMgr); } // end GR namespace } // end clang namespace #endif
0
repos/DirectXShaderCompiler/tools/clang/include/clang/StaticAnalyzer/Core
repos/DirectXShaderCompiler/tools/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h
//ProgramStateTrait.h - Partial implementations of ProgramStateTrait -*- C++ -*- // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines partial implementations of template specializations of // the class ProgramStateTrait<>. ProgramStateTrait<> is used by ProgramState // to implement set/get methods for manipulating a ProgramState's // generic data map. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_PROGRAMSTATETRAIT_H #define LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_PROGRAMSTATETRAIT_H #include "llvm/Support/Allocator.h" #include "llvm/Support/DataTypes.h" namespace llvm { template <typename K, typename D, typename I> class ImmutableMap; template <typename K, typename I> class ImmutableSet; template <typename T> class ImmutableList; template <typename T> class ImmutableListImpl; } namespace clang { namespace ento { template <typename T> struct ProgramStatePartialTrait; /// Declares a program state trait for type \p Type called \p Name, and /// introduce a typedef named \c NameTy. /// The macro should not be used inside namespaces, or for traits that must /// be accessible from more than one translation unit. #define REGISTER_TRAIT_WITH_PROGRAMSTATE(Name, Type) \ namespace { \ class Name {}; \ typedef Type Name ## Ty; \ } \ namespace clang { \ namespace ento { \ template <> \ struct ProgramStateTrait<Name> \ : public ProgramStatePartialTrait<Name ## Ty> { \ static void *GDMIndex() { static int Index; return &Index; } \ }; \ } \ } // Partial-specialization for ImmutableMap. template <typename Key, typename Data, typename Info> struct ProgramStatePartialTrait< llvm::ImmutableMap<Key,Data,Info> > { typedef llvm::ImmutableMap<Key,Data,Info> data_type; typedef typename data_type::Factory& context_type; typedef Key key_type; typedef Data value_type; typedef const value_type* lookup_type; static inline data_type MakeData(void *const* p) { return p ? data_type((typename data_type::TreeTy*) *p) : data_type(nullptr); } static inline void *MakeVoidPtr(data_type B) { return B.getRoot(); } static lookup_type Lookup(data_type B, key_type K) { return B.lookup(K); } static data_type Set(data_type B, key_type K, value_type E,context_type F){ return F.add(B, K, E); } static data_type Remove(data_type B, key_type K, context_type F) { return F.remove(B, K); } static inline context_type MakeContext(void *p) { return *((typename data_type::Factory*) p); } static void *CreateContext(llvm::BumpPtrAllocator& Alloc) { return new typename data_type::Factory(Alloc); } static void DeleteContext(void *Ctx) { delete (typename data_type::Factory*) Ctx; } }; /// Helper for registering a map trait. /// /// If the map type were written directly in the invocation of /// REGISTER_TRAIT_WITH_PROGRAMSTATE, the comma in the template arguments /// would be treated as a macro argument separator, which is wrong. /// This allows the user to specify a map type in a way that the preprocessor /// can deal with. #define CLANG_ENTO_PROGRAMSTATE_MAP(Key, Value) llvm::ImmutableMap<Key, Value> // Partial-specialization for ImmutableSet. template <typename Key, typename Info> struct ProgramStatePartialTrait< llvm::ImmutableSet<Key,Info> > { typedef llvm::ImmutableSet<Key,Info> data_type; typedef typename data_type::Factory& context_type; typedef Key key_type; static inline data_type MakeData(void *const* p) { return p ? data_type((typename data_type::TreeTy*) *p) : data_type(nullptr); } static inline void *MakeVoidPtr(data_type B) { return B.getRoot(); } static data_type Add(data_type B, key_type K, context_type F) { return F.add(B, K); } static data_type Remove(data_type B, key_type K, context_type F) { return F.remove(B, K); } static bool Contains(data_type B, key_type K) { return B.contains(K); } static inline context_type MakeContext(void *p) { return *((typename data_type::Factory*) p); } static void *CreateContext(llvm::BumpPtrAllocator& Alloc) { return new typename data_type::Factory(Alloc); } static void DeleteContext(void *Ctx) { delete (typename data_type::Factory*) Ctx; } }; // Partial-specialization for ImmutableList. template <typename T> struct ProgramStatePartialTrait< llvm::ImmutableList<T> > { typedef llvm::ImmutableList<T> data_type; typedef T key_type; typedef typename data_type::Factory& context_type; static data_type Add(data_type L, key_type K, context_type F) { return F.add(K, L); } static bool Contains(data_type L, key_type K) { return L.contains(K); } static inline data_type MakeData(void *const* p) { return p ? data_type((const llvm::ImmutableListImpl<T>*) *p) : data_type(nullptr); } static inline void *MakeVoidPtr(data_type D) { return const_cast<llvm::ImmutableListImpl<T> *>(D.getInternalPointer()); } static inline context_type MakeContext(void *p) { return *((typename data_type::Factory*) p); } static void *CreateContext(llvm::BumpPtrAllocator& Alloc) { return new typename data_type::Factory(Alloc); } static void DeleteContext(void *Ctx) { delete (typename data_type::Factory*) Ctx; } }; // Partial specialization for bool. template <> struct ProgramStatePartialTrait<bool> { typedef bool data_type; static inline data_type MakeData(void *const* p) { return p ? (data_type) (uintptr_t) *p : data_type(); } static inline void *MakeVoidPtr(data_type d) { return (void*) (uintptr_t) d; } }; // Partial specialization for unsigned. template <> struct ProgramStatePartialTrait<unsigned> { typedef unsigned data_type; static inline data_type MakeData(void *const* p) { return p ? (data_type) (uintptr_t) *p : data_type(); } static inline void *MakeVoidPtr(data_type d) { return (void*) (uintptr_t) d; } }; // Partial specialization for void*. template <> struct ProgramStatePartialTrait<void*> { typedef void *data_type; static inline data_type MakeData(void *const* p) { return p ? *p : data_type(); } static inline void *MakeVoidPtr(data_type d) { return d; } }; // Partial specialization for const void *. template <> struct ProgramStatePartialTrait<const void *> { typedef const void *data_type; static inline data_type MakeData(void * const *p) { return p ? *p : data_type(); } static inline void *MakeVoidPtr(data_type d) { return const_cast<void *>(d); } }; } // end ento namespace } // end clang namespace #endif
0
repos/DirectXShaderCompiler/tools/clang/include/clang/StaticAnalyzer/Core
repos/DirectXShaderCompiler/tools/clang/include/clang/StaticAnalyzer/Core/PathSensitive/BlockCounter.h
//==- BlockCounter.h - ADT for counting block visits ---------------*- C++ -*-// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines BlockCounter, an abstract data type used to count // the number of times a given block has been visited along a path // analyzed by CoreEngine. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_BLOCKCOUNTER_H #define LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_BLOCKCOUNTER_H #include "llvm/Support/Allocator.h" namespace clang { class StackFrameContext; namespace ento { /// \class BlockCounter /// \brief An abstract data type used to count the number of times a given /// block has been visited along a path analyzed by CoreEngine. class BlockCounter { void *Data; BlockCounter(void *D) : Data(D) {} public: BlockCounter() : Data(nullptr) {} unsigned getNumVisited(const StackFrameContext *CallSite, unsigned BlockID) const; class Factory { void *F; public: Factory(llvm::BumpPtrAllocator& Alloc); ~Factory(); BlockCounter GetEmptyCounter(); BlockCounter IncrementCount(BlockCounter BC, const StackFrameContext *CallSite, unsigned BlockID); }; friend class Factory; }; } // end GR namespace } // end clang namespace #endif
0
repos/DirectXShaderCompiler/tools/clang/include/clang/StaticAnalyzer/Core
repos/DirectXShaderCompiler/tools/clang/include/clang/StaticAnalyzer/Core/BugReporter/CommonBugCategories.h
//=--- CommonBugCategories.h - Provides common issue categories -*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_STATICANALYZER_CORE_BUGREPORTER_COMMONBUGCATEGORIES_H #define LLVM_CLANG_STATICANALYZER_CORE_BUGREPORTER_COMMONBUGCATEGORIES_H // Common strings used for the "category" of many static analyzer issues. namespace clang { namespace ento { namespace categories { extern const char * const CoreFoundationObjectiveC; extern const char * const LogicError; extern const char * const MemoryCoreFoundationObjectiveC; extern const char * const UnixAPI; } } } #endif
0
repos/DirectXShaderCompiler/tools/clang/include/clang/StaticAnalyzer/Core
repos/DirectXShaderCompiler/tools/clang/include/clang/StaticAnalyzer/Core/BugReporter/BugReporter.h
//===--- BugReporter.h - Generate PathDiagnostics --------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines BugReporter, a utility class for generating // PathDiagnostics for analyses based on ProgramState. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_STATICANALYZER_CORE_BUGREPORTER_BUGREPORTER_H #define LLVM_CLANG_STATICANALYZER_CORE_BUGREPORTER_BUGREPORTER_H #include "clang/Basic/SourceLocation.h" #include "clang/StaticAnalyzer/Core/AnalyzerOptions.h" #include "clang/StaticAnalyzer/Core/BugReporter/BugReporterVisitor.h" #include "clang/StaticAnalyzer/Core/BugReporter/PathDiagnostic.h" #include "clang/StaticAnalyzer/Core/CheckerManager.h" #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h" #include "llvm/ADT/DenseSet.h" #include "llvm/ADT/FoldingSet.h" #include "llvm/ADT/ImmutableSet.h" #include "llvm/ADT/SmallSet.h" #include "llvm/ADT/ilist.h" #include "llvm/ADT/ilist_node.h" namespace clang { class ASTContext; class DiagnosticsEngine; class Stmt; class ParentMap; namespace ento { class PathDiagnostic; class ExplodedNode; class ExplodedGraph; class BugReport; class BugReporter; class BugReporterContext; class ExprEngine; class BugType; //===----------------------------------------------------------------------===// // Interface for individual bug reports. //===----------------------------------------------------------------------===// /// This class provides an interface through which checkers can create /// individual bug reports. class BugReport : public llvm::ilist_node<BugReport> { public: class NodeResolver { virtual void anchor(); public: virtual ~NodeResolver() {} virtual const ExplodedNode* getOriginalNode(const ExplodedNode *N) = 0; }; typedef const SourceRange *ranges_iterator; typedef SmallVector<std::unique_ptr<BugReporterVisitor>, 8> VisitorList; typedef VisitorList::iterator visitor_iterator; typedef SmallVector<StringRef, 2> ExtraTextList; protected: friend class BugReporter; friend class BugReportEquivClass; BugType& BT; const Decl *DeclWithIssue; std::string ShortDescription; std::string Description; PathDiagnosticLocation Location; PathDiagnosticLocation UniqueingLocation; const Decl *UniqueingDecl; const ExplodedNode *ErrorNode; SmallVector<SourceRange, 4> Ranges; ExtraTextList ExtraText; typedef llvm::DenseSet<SymbolRef> Symbols; typedef llvm::DenseSet<const MemRegion *> Regions; /// A (stack of) a set of symbols that are registered with this /// report as being "interesting", and thus used to help decide which /// diagnostics to include when constructing the final path diagnostic. /// The stack is largely used by BugReporter when generating PathDiagnostics /// for multiple PathDiagnosticConsumers. SmallVector<Symbols *, 2> interestingSymbols; /// A (stack of) set of regions that are registered with this report as being /// "interesting", and thus used to help decide which diagnostics /// to include when constructing the final path diagnostic. /// The stack is largely used by BugReporter when generating PathDiagnostics /// for multiple PathDiagnosticConsumers. SmallVector<Regions *, 2> interestingRegions; /// A set of location contexts that correspoind to call sites which should be /// considered "interesting". llvm::SmallSet<const LocationContext *, 2> InterestingLocationContexts; /// A set of custom visitors which generate "event" diagnostics at /// interesting points in the path. VisitorList Callbacks; /// Used for ensuring the visitors are only added once. llvm::FoldingSet<BugReporterVisitor> CallbacksSet; /// Used for clients to tell if the report's configuration has changed /// since the last time they checked. unsigned ConfigurationChangeToken; /// When set, this flag disables all callstack pruning from a diagnostic /// path. This is useful for some reports that want maximum fidelty /// when reporting an issue. bool DoNotPrunePath; /// Used to track unique reasons why a bug report might be invalid. /// /// \sa markInvalid /// \sa removeInvalidation typedef std::pair<const void *, const void *> InvalidationRecord; /// If non-empty, this bug report is likely a false positive and should not be /// shown to the user. /// /// \sa markInvalid /// \sa removeInvalidation llvm::SmallSet<InvalidationRecord, 4> Invalidations; private: // Used internally by BugReporter. Symbols &getInterestingSymbols(); Regions &getInterestingRegions(); void lazyInitializeInterestingSets(); void pushInterestingSymbolsAndRegions(); void popInterestingSymbolsAndRegions(); public: BugReport(BugType& bt, StringRef desc, const ExplodedNode *errornode) : BT(bt), DeclWithIssue(nullptr), Description(desc), ErrorNode(errornode), ConfigurationChangeToken(0), DoNotPrunePath(false) {} BugReport(BugType& bt, StringRef shortDesc, StringRef desc, const ExplodedNode *errornode) : BT(bt), DeclWithIssue(nullptr), ShortDescription(shortDesc), Description(desc), ErrorNode(errornode), ConfigurationChangeToken(0), DoNotPrunePath(false) {} BugReport(BugType &bt, StringRef desc, PathDiagnosticLocation l) : BT(bt), DeclWithIssue(nullptr), Description(desc), Location(l), ErrorNode(nullptr), ConfigurationChangeToken(0), DoNotPrunePath(false) {} /// \brief Create a BugReport with a custom uniqueing location. /// /// The reports that have the same report location, description, bug type, and /// ranges are uniqued - only one of the equivalent reports will be presented /// to the user. This method allows to rest the location which should be used /// for uniquing reports. For example, memory leaks checker, could set this to /// the allocation site, rather then the location where the bug is reported. BugReport(BugType& bt, StringRef desc, const ExplodedNode *errornode, PathDiagnosticLocation LocationToUnique, const Decl *DeclToUnique) : BT(bt), DeclWithIssue(nullptr), Description(desc), UniqueingLocation(LocationToUnique), UniqueingDecl(DeclToUnique), ErrorNode(errornode), ConfigurationChangeToken(0), DoNotPrunePath(false) {} virtual ~BugReport(); const BugType& getBugType() const { return BT; } BugType& getBugType() { return BT; } const ExplodedNode *getErrorNode() const { return ErrorNode; } StringRef getDescription() const { return Description; } StringRef getShortDescription(bool UseFallback = true) const { if (ShortDescription.empty() && UseFallback) return Description; return ShortDescription; } /// Indicates whether or not any path pruning should take place /// when generating a PathDiagnostic from this BugReport. bool shouldPrunePath() const { return !DoNotPrunePath; } /// Disable all path pruning when generating a PathDiagnostic. void disablePathPruning() { DoNotPrunePath = true; } void markInteresting(SymbolRef sym); void markInteresting(const MemRegion *R); void markInteresting(SVal V); void markInteresting(const LocationContext *LC); bool isInteresting(SymbolRef sym); bool isInteresting(const MemRegion *R); bool isInteresting(SVal V); bool isInteresting(const LocationContext *LC); unsigned getConfigurationChangeToken() const { return ConfigurationChangeToken; } /// Returns whether or not this report should be considered valid. /// /// Invalid reports are those that have been classified as likely false /// positives after the fact. bool isValid() const { return Invalidations.empty(); } /// Marks the current report as invalid, meaning that it is probably a false /// positive and should not be reported to the user. /// /// The \p Tag and \p Data arguments are intended to be opaque identifiers for /// this particular invalidation, where \p Tag represents the visitor /// responsible for invalidation, and \p Data represents the reason this /// visitor decided to invalidate the bug report. /// /// \sa removeInvalidation void markInvalid(const void *Tag, const void *Data) { Invalidations.insert(std::make_pair(Tag, Data)); } /// Reverses the effects of a previous invalidation. /// /// \sa markInvalid void removeInvalidation(const void *Tag, const void *Data) { Invalidations.erase(std::make_pair(Tag, Data)); } /// Return the canonical declaration, be it a method or class, where /// this issue semantically occurred. const Decl *getDeclWithIssue() const; /// Specifically set the Decl where an issue occurred. This isn't necessary /// for BugReports that cover a path as it will be automatically inferred. void setDeclWithIssue(const Decl *declWithIssue) { DeclWithIssue = declWithIssue; } /// \brief This allows for addition of meta data to the diagnostic. /// /// Currently, only the HTMLDiagnosticClient knows how to display it. void addExtraText(StringRef S) { ExtraText.push_back(S); } virtual const ExtraTextList &getExtraText() { return ExtraText; } /// \brief Return the "definitive" location of the reported bug. /// /// While a bug can span an entire path, usually there is a specific /// location that can be used to identify where the key issue occurred. /// This location is used by clients rendering diagnostics. virtual PathDiagnosticLocation getLocation(const SourceManager &SM) const; /// \brief Get the location on which the report should be uniqued. PathDiagnosticLocation getUniqueingLocation() const { return UniqueingLocation; } /// \brief Get the declaration containing the uniqueing location. const Decl *getUniqueingDecl() const { return UniqueingDecl; } const Stmt *getStmt() const; /// \brief Add a range to a bug report. /// /// Ranges are used to highlight regions of interest in the source code. /// They should be at the same source code line as the BugReport location. /// By default, the source range of the statement corresponding to the error /// node will be used; add a single invalid range to specify absence of /// ranges. void addRange(SourceRange R) { assert((R.isValid() || Ranges.empty()) && "Invalid range can only be used " "to specify that the report does not have a range."); Ranges.push_back(R); } /// \brief Get the SourceRanges associated with the report. virtual llvm::iterator_range<ranges_iterator> getRanges(); /// \brief Add custom or predefined bug report visitors to this report. /// /// The visitors should be used when the default trace is not sufficient. /// For example, they allow constructing a more elaborate trace. /// \sa registerConditionVisitor(), registerTrackNullOrUndefValue(), /// registerFindLastStore(), registerNilReceiverVisitor(), and /// registerVarDeclsLastStore(). void addVisitor(std::unique_ptr<BugReporterVisitor> visitor); /// Iterators through the custom diagnostic visitors. visitor_iterator visitor_begin() { return Callbacks.begin(); } visitor_iterator visitor_end() { return Callbacks.end(); } /// Profile to identify equivalent bug reports for error report coalescing. /// Reports are uniqued to ensure that we do not emit multiple diagnostics /// for each bug. virtual void Profile(llvm::FoldingSetNodeID& hash) const; }; } // end ento namespace } // end clang namespace namespace llvm { template<> struct ilist_traits<clang::ento::BugReport> : public ilist_default_traits<clang::ento::BugReport> { // HLSL Change Starts // Temporarily disable "downcast of address" UBSAN runtime error // https://github.com/microsoft/DirectXShaderCompiler/issues/6446 #ifdef __has_feature #if __has_feature(undefined_behavior_sanitizer) __attribute__((no_sanitize("undefined"))) #endif // __has_feature(address_sanitizer) #endif // defined(__has_feature) // HLSL Change Ends clang::ento::BugReport * createSentinel() const { return static_cast<clang::ento::BugReport *>(&Sentinel); } void destroySentinel(clang::ento::BugReport *) const {} clang::ento::BugReport *provideInitialHead() const { return createSentinel(); } clang::ento::BugReport *ensureHead(clang::ento::BugReport *) const { return createSentinel(); } private: mutable ilist_half_node<clang::ento::BugReport> Sentinel; }; } namespace clang { namespace ento { //===----------------------------------------------------------------------===// // BugTypes (collections of related reports). //===----------------------------------------------------------------------===// class BugReportEquivClass : public llvm::FoldingSetNode { /// List of *owned* BugReport objects. llvm::ilist<BugReport> Reports; friend class BugReporter; void AddReport(std::unique_ptr<BugReport> R) { Reports.push_back(R.release()); } public: BugReportEquivClass(std::unique_ptr<BugReport> R) { AddReport(std::move(R)); } ~BugReportEquivClass(); void Profile(llvm::FoldingSetNodeID& ID) const { assert(!Reports.empty()); Reports.front().Profile(ID); } typedef llvm::ilist<BugReport>::iterator iterator; typedef llvm::ilist<BugReport>::const_iterator const_iterator; iterator begin() { return Reports.begin(); } iterator end() { return Reports.end(); } const_iterator begin() const { return Reports.begin(); } const_iterator end() const { return Reports.end(); } }; //===----------------------------------------------------------------------===// // BugReporter and friends. // // /////////////////////////////////////////////////////////////////////////////// class BugReporterData { public: virtual ~BugReporterData(); virtual DiagnosticsEngine& getDiagnostic() = 0; virtual ArrayRef<PathDiagnosticConsumer*> getPathDiagnosticConsumers() = 0; virtual ASTContext &getASTContext() = 0; virtual SourceManager& getSourceManager() = 0; virtual AnalyzerOptions& getAnalyzerOptions() = 0; }; /// BugReporter is a utility class for generating PathDiagnostics for analysis. /// It collects the BugReports and BugTypes and knows how to generate /// and flush the corresponding diagnostics. class BugReporter { public: enum Kind { BaseBRKind, GRBugReporterKind }; private: typedef llvm::ImmutableSet<BugType*> BugTypesTy; BugTypesTy::Factory F; BugTypesTy BugTypes; const Kind kind; BugReporterData& D; /// Generate and flush the diagnostics for the given bug report. void FlushReport(BugReportEquivClass& EQ); /// Generate and flush the diagnostics for the given bug report /// and PathDiagnosticConsumer. void FlushReport(BugReport *exampleReport, PathDiagnosticConsumer &PD, ArrayRef<BugReport*> BugReports); /// The set of bug reports tracked by the BugReporter. llvm::FoldingSet<BugReportEquivClass> EQClasses; /// A vector of BugReports for tracking the allocated pointers and cleanup. std::vector<BugReportEquivClass *> EQClassesVector; protected: BugReporter(BugReporterData& d, Kind k) : BugTypes(F.getEmptySet()), kind(k), D(d) {} public: BugReporter(BugReporterData& d) : BugTypes(F.getEmptySet()), kind(BaseBRKind), D(d) {} virtual ~BugReporter(); /// \brief Generate and flush diagnostics for all bug reports. void FlushReports(); Kind getKind() const { return kind; } DiagnosticsEngine& getDiagnostic() { return D.getDiagnostic(); } ArrayRef<PathDiagnosticConsumer*> getPathDiagnosticConsumers() { return D.getPathDiagnosticConsumers(); } /// \brief Iterator over the set of BugTypes tracked by the BugReporter. typedef BugTypesTy::iterator iterator; iterator begin() { return BugTypes.begin(); } iterator end() { return BugTypes.end(); } /// \brief Iterator over the set of BugReports tracked by the BugReporter. typedef llvm::FoldingSet<BugReportEquivClass>::iterator EQClasses_iterator; EQClasses_iterator EQClasses_begin() { return EQClasses.begin(); } EQClasses_iterator EQClasses_end() { return EQClasses.end(); } ASTContext &getContext() { return D.getASTContext(); } SourceManager& getSourceManager() { return D.getSourceManager(); } AnalyzerOptions& getAnalyzerOptions() { return D.getAnalyzerOptions(); } virtual bool generatePathDiagnostic(PathDiagnostic& pathDiagnostic, PathDiagnosticConsumer &PC, ArrayRef<BugReport *> &bugReports) { return true; } bool RemoveUnneededCalls(PathPieces &pieces, BugReport *R); void Register(BugType *BT); /// \brief Add the given report to the set of reports tracked by BugReporter. /// /// The reports are usually generated by the checkers. Further, they are /// folded based on the profile value, which is done to coalesce similar /// reports. void emitReport(std::unique_ptr<BugReport> R); void EmitBasicReport(const Decl *DeclWithIssue, const CheckerBase *Checker, StringRef BugName, StringRef BugCategory, StringRef BugStr, PathDiagnosticLocation Loc, ArrayRef<SourceRange> Ranges = None); void EmitBasicReport(const Decl *DeclWithIssue, CheckName CheckName, StringRef BugName, StringRef BugCategory, StringRef BugStr, PathDiagnosticLocation Loc, ArrayRef<SourceRange> Ranges = None); private: llvm::StringMap<BugType *> StrBugTypes; /// \brief Returns a BugType that is associated with the given name and /// category. BugType *getBugTypeForName(CheckName CheckName, StringRef name, StringRef category); }; // FIXME: Get rid of GRBugReporter. It's the wrong abstraction. class GRBugReporter : public BugReporter { ExprEngine& Eng; public: GRBugReporter(BugReporterData& d, ExprEngine& eng) : BugReporter(d, GRBugReporterKind), Eng(eng) {} ~GRBugReporter() override; /// getEngine - Return the analysis engine used to analyze a given /// function or method. ExprEngine &getEngine() { return Eng; } /// getGraph - Get the exploded graph created by the analysis engine /// for the analyzed method or function. ExplodedGraph &getGraph(); /// getStateManager - Return the state manager used by the analysis /// engine. ProgramStateManager &getStateManager(); /// Generates a path corresponding to one of the given bug reports. /// /// Which report is used for path generation is not specified. The /// bug reporter will try to pick the shortest path, but this is not /// guaranteed. /// /// \return True if the report was valid and a path was generated, /// false if the reports should be considered invalid. bool generatePathDiagnostic(PathDiagnostic &PD, PathDiagnosticConsumer &PC, ArrayRef<BugReport*> &bugReports) override; /// classof - Used by isa<>, cast<>, and dyn_cast<>. static bool classof(const BugReporter* R) { return R->getKind() == GRBugReporterKind; } }; class BugReporterContext { virtual void anchor(); GRBugReporter &BR; public: BugReporterContext(GRBugReporter& br) : BR(br) {} virtual ~BugReporterContext() {} GRBugReporter& getBugReporter() { return BR; } ExplodedGraph &getGraph() { return BR.getGraph(); } ProgramStateManager& getStateManager() { return BR.getStateManager(); } SValBuilder& getSValBuilder() { return getStateManager().getSValBuilder(); } ASTContext &getASTContext() { return BR.getContext(); } SourceManager& getSourceManager() { return BR.getSourceManager(); } virtual BugReport::NodeResolver& getNodeResolver() = 0; }; } // end GR namespace } // end clang namespace #endif
0
repos/DirectXShaderCompiler/tools/clang/include/clang/StaticAnalyzer/Core
repos/DirectXShaderCompiler/tools/clang/include/clang/StaticAnalyzer/Core/BugReporter/PathDiagnostic.h
//===--- PathDiagnostic.h - Path-Specific Diagnostic Handling ---*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines the PathDiagnostic-related interfaces. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_STATICANALYZER_CORE_BUGREPORTER_PATHDIAGNOSTIC_H #define LLVM_CLANG_STATICANALYZER_CORE_BUGREPORTER_PATHDIAGNOSTIC_H #include "clang/Analysis/ProgramPoint.h" #include "clang/Basic/SourceLocation.h" #include "llvm/ADT/FoldingSet.h" #include "llvm/ADT/IntrusiveRefCntPtr.h" #include "llvm/ADT/Optional.h" #include "llvm/ADT/PointerUnion.h" #include <deque> #include <iterator> #include <list> #include <string> #include <vector> namespace clang { class ConditionalOperator; class AnalysisDeclContext; class BinaryOperator; class CompoundStmt; class Decl; class LocationContext; class MemberExpr; class ParentMap; class ProgramPoint; class SourceManager; class Stmt; class CallExpr; namespace ento { class ExplodedNode; class SymExpr; typedef const SymExpr* SymbolRef; //===----------------------------------------------------------------------===// // High-level interface for handlers of path-sensitive diagnostics. //===----------------------------------------------------------------------===// class PathDiagnostic; class PathDiagnosticConsumer { public: class PDFileEntry : public llvm::FoldingSetNode { public: PDFileEntry(llvm::FoldingSetNodeID &NodeID) : NodeID(NodeID) {} typedef std::vector<std::pair<StringRef, StringRef> > ConsumerFiles; /// \brief A vector of <consumer,file> pairs. ConsumerFiles files; /// \brief A precomputed hash tag used for uniquing PDFileEntry objects. const llvm::FoldingSetNodeID NodeID; /// \brief Used for profiling in the FoldingSet. void Profile(llvm::FoldingSetNodeID &ID) { ID = NodeID; } }; class FilesMade { llvm::BumpPtrAllocator Alloc; llvm::FoldingSet<PDFileEntry> Set; public: ~FilesMade(); bool empty() const { return Set.empty(); } void addDiagnostic(const PathDiagnostic &PD, StringRef ConsumerName, StringRef fileName); PDFileEntry::ConsumerFiles *getFiles(const PathDiagnostic &PD); }; private: virtual void anchor(); public: PathDiagnosticConsumer() : flushed(false) {} virtual ~PathDiagnosticConsumer(); void FlushDiagnostics(FilesMade *FilesMade); virtual void FlushDiagnosticsImpl(std::vector<const PathDiagnostic *> &Diags, FilesMade *filesMade) = 0; virtual StringRef getName() const = 0; void HandlePathDiagnostic(std::unique_ptr<PathDiagnostic> D); enum PathGenerationScheme { None, Minimal, Extensive, AlternateExtensive }; virtual PathGenerationScheme getGenerationScheme() const { return Minimal; } virtual bool supportsLogicalOpControlFlow() const { return false; } /// Return true if the PathDiagnosticConsumer supports individual /// PathDiagnostics that span multiple files. virtual bool supportsCrossFileDiagnostics() const { return false; } protected: bool flushed; llvm::FoldingSet<PathDiagnostic> Diags; }; //===----------------------------------------------------------------------===// // Path-sensitive diagnostics. //===----------------------------------------------------------------------===// class PathDiagnosticRange : public SourceRange { public: bool isPoint; PathDiagnosticRange(const SourceRange &R, bool isP = false) : SourceRange(R), isPoint(isP) {} PathDiagnosticRange() : isPoint(false) {} }; typedef llvm::PointerUnion<const LocationContext*, AnalysisDeclContext*> LocationOrAnalysisDeclContext; class PathDiagnosticLocation { private: enum Kind { RangeK, SingleLocK, StmtK, DeclK } K; const Stmt *S; const Decl *D; const SourceManager *SM; FullSourceLoc Loc; PathDiagnosticRange Range; PathDiagnosticLocation(SourceLocation L, const SourceManager &sm, Kind kind) : K(kind), S(nullptr), D(nullptr), SM(&sm), Loc(genLocation(L)), Range(genRange()) { } FullSourceLoc genLocation( SourceLocation L = SourceLocation(), LocationOrAnalysisDeclContext LAC = (AnalysisDeclContext *)nullptr) const; PathDiagnosticRange genRange( LocationOrAnalysisDeclContext LAC = (AnalysisDeclContext *)nullptr) const; public: /// Create an invalid location. PathDiagnosticLocation() : K(SingleLocK), S(nullptr), D(nullptr), SM(nullptr) {} /// Create a location corresponding to the given statement. PathDiagnosticLocation(const Stmt *s, const SourceManager &sm, LocationOrAnalysisDeclContext lac) : K(s->getLocStart().isValid() ? StmtK : SingleLocK), S(K == StmtK ? s : nullptr), D(nullptr), SM(&sm), Loc(genLocation(SourceLocation(), lac)), Range(genRange(lac)) { assert(K == SingleLocK || S); assert(K == SingleLocK || Loc.isValid()); assert(K == SingleLocK || Range.isValid()); } /// Create a location corresponding to the given declaration. PathDiagnosticLocation(const Decl *d, const SourceManager &sm) : K(DeclK), S(nullptr), D(d), SM(&sm), Loc(genLocation()), Range(genRange()) { assert(D); assert(Loc.isValid()); assert(Range.isValid()); } /// Create a location at an explicit offset in the source. /// /// This should only be used if there are no more appropriate constructors. PathDiagnosticLocation(SourceLocation loc, const SourceManager &sm) : K(SingleLocK), S(nullptr), D(nullptr), SM(&sm), Loc(loc, sm), Range(genRange()) { assert(Loc.isValid()); assert(Range.isValid()); } /// Create a location corresponding to the given declaration. static PathDiagnosticLocation create(const Decl *D, const SourceManager &SM) { return PathDiagnosticLocation(D, SM); } /// Create a location for the beginning of the declaration. static PathDiagnosticLocation createBegin(const Decl *D, const SourceManager &SM); /// Create a location for the beginning of the statement. static PathDiagnosticLocation createBegin(const Stmt *S, const SourceManager &SM, const LocationOrAnalysisDeclContext LAC); /// Create a location for the end of the statement. /// /// If the statement is a CompoundStatement, the location will point to the /// closing brace instead of following it. static PathDiagnosticLocation createEnd(const Stmt *S, const SourceManager &SM, const LocationOrAnalysisDeclContext LAC); /// Create the location for the operator of the binary expression. /// Assumes the statement has a valid location. static PathDiagnosticLocation createOperatorLoc(const BinaryOperator *BO, const SourceManager &SM); static PathDiagnosticLocation createConditionalColonLoc( const ConditionalOperator *CO, const SourceManager &SM); /// For member expressions, return the location of the '.' or '->'. /// Assumes the statement has a valid location. static PathDiagnosticLocation createMemberLoc(const MemberExpr *ME, const SourceManager &SM); /// Create a location for the beginning of the compound statement. /// Assumes the statement has a valid location. static PathDiagnosticLocation createBeginBrace(const CompoundStmt *CS, const SourceManager &SM); /// Create a location for the end of the compound statement. /// Assumes the statement has a valid location. static PathDiagnosticLocation createEndBrace(const CompoundStmt *CS, const SourceManager &SM); /// Create a location for the beginning of the enclosing declaration body. /// Defaults to the beginning of the first statement in the declaration body. static PathDiagnosticLocation createDeclBegin(const LocationContext *LC, const SourceManager &SM); /// Constructs a location for the end of the enclosing declaration body. /// Defaults to the end of brace. static PathDiagnosticLocation createDeclEnd(const LocationContext *LC, const SourceManager &SM); /// Create a location corresponding to the given valid ExplodedNode. static PathDiagnosticLocation create(const ProgramPoint& P, const SourceManager &SMng); /// Create a location corresponding to the next valid ExplodedNode as end /// of path location. static PathDiagnosticLocation createEndOfPath(const ExplodedNode* N, const SourceManager &SM); /// Convert the given location into a single kind location. static PathDiagnosticLocation createSingleLocation( const PathDiagnosticLocation &PDL); bool operator==(const PathDiagnosticLocation &X) const { return K == X.K && Loc == X.Loc && Range == X.Range; } bool operator!=(const PathDiagnosticLocation &X) const { return !(*this == X); } bool isValid() const { return SM != nullptr; } FullSourceLoc asLocation() const { return Loc; } PathDiagnosticRange asRange() const { return Range; } const Stmt *asStmt() const { assert(isValid()); return S; } const Decl *asDecl() const { assert(isValid()); return D; } bool hasRange() const { return K == StmtK || K == RangeK || K == DeclK; } void invalidate() { *this = PathDiagnosticLocation(); } void flatten(); const SourceManager& getManager() const { assert(isValid()); return *SM; } void Profile(llvm::FoldingSetNodeID &ID) const; void dump() const; /// \brief Given an exploded node, retrieve the statement that should be used /// for the diagnostic location. static const Stmt *getStmt(const ExplodedNode *N); /// \brief Retrieve the statement corresponding to the successor node. static const Stmt *getNextStmt(const ExplodedNode *N); }; class PathDiagnosticLocationPair { private: PathDiagnosticLocation Start, End; public: PathDiagnosticLocationPair(const PathDiagnosticLocation &start, const PathDiagnosticLocation &end) : Start(start), End(end) {} const PathDiagnosticLocation &getStart() const { return Start; } const PathDiagnosticLocation &getEnd() const { return End; } void setStart(const PathDiagnosticLocation &L) { Start = L; } void setEnd(const PathDiagnosticLocation &L) { End = L; } void flatten() { Start.flatten(); End.flatten(); } void Profile(llvm::FoldingSetNodeID &ID) const { Start.Profile(ID); End.Profile(ID); } }; //===----------------------------------------------------------------------===// // Path "pieces" for path-sensitive diagnostics. // // /////////////////////////////////////////////////////////////////////////////// class PathDiagnosticPiece : public RefCountedBaseVPTR { public: enum Kind { ControlFlow, Event, Macro, Call }; enum DisplayHint { Above, Below }; private: const std::string str; const Kind kind; const DisplayHint Hint; /// \brief In the containing bug report, this piece is the last piece from /// the main source file. bool LastInMainSourceFile; /// A constant string that can be used to tag the PathDiagnosticPiece, /// typically with the identification of the creator. The actual pointer /// value is meant to be an identifier; the string itself is useful for /// debugging. StringRef Tag; std::vector<SourceRange> ranges; PathDiagnosticPiece() = delete; PathDiagnosticPiece(const PathDiagnosticPiece &P) = delete; void operator=(const PathDiagnosticPiece &P) = delete; protected: PathDiagnosticPiece(StringRef s, Kind k, DisplayHint hint = Below); PathDiagnosticPiece(Kind k, DisplayHint hint = Below); public: ~PathDiagnosticPiece() override; StringRef getString() const { return str; } /// Tag this PathDiagnosticPiece with the given C-string. void setTag(const char *tag) { Tag = tag; } /// Return the opaque tag (if any) on the PathDiagnosticPiece. const void *getTag() const { return Tag.data(); } /// Return the string representation of the tag. This is useful /// for debugging. StringRef getTagStr() const { return Tag; } /// getDisplayHint - Return a hint indicating where the diagnostic should /// be displayed by the PathDiagnosticConsumer. DisplayHint getDisplayHint() const { return Hint; } virtual PathDiagnosticLocation getLocation() const = 0; virtual void flattenLocations() = 0; Kind getKind() const { return kind; } void addRange(SourceRange R) { if (!R.isValid()) return; ranges.push_back(R); } void addRange(SourceLocation B, SourceLocation E) { if (!B.isValid() || !E.isValid()) return; ranges.push_back(SourceRange(B,E)); } /// Return the SourceRanges associated with this PathDiagnosticPiece. ArrayRef<SourceRange> getRanges() const { return ranges; } virtual void Profile(llvm::FoldingSetNodeID &ID) const; void setAsLastInMainSourceFile() { LastInMainSourceFile = true; } bool isLastInMainSourceFile() const { return LastInMainSourceFile; } virtual void dump() const = 0; }; class PathPieces : public std::list<IntrusiveRefCntPtr<PathDiagnosticPiece> > { void flattenTo(PathPieces &Primary, PathPieces &Current, bool ShouldFlattenMacros) const; public: ~PathPieces(); PathPieces flatten(bool ShouldFlattenMacros) const { PathPieces Result; flattenTo(Result, Result, ShouldFlattenMacros); return Result; } void dump() const; }; class PathDiagnosticSpotPiece : public PathDiagnosticPiece { private: PathDiagnosticLocation Pos; public: PathDiagnosticSpotPiece(const PathDiagnosticLocation &pos, StringRef s, PathDiagnosticPiece::Kind k, bool addPosRange = true) : PathDiagnosticPiece(s, k), Pos(pos) { assert(Pos.isValid() && Pos.asLocation().isValid() && "PathDiagnosticSpotPiece's must have a valid location."); if (addPosRange && Pos.hasRange()) addRange(Pos.asRange()); } PathDiagnosticLocation getLocation() const override { return Pos; } void flattenLocations() override { Pos.flatten(); } void Profile(llvm::FoldingSetNodeID &ID) const override; static bool classof(const PathDiagnosticPiece *P) { return P->getKind() == Event || P->getKind() == Macro; } }; /// \brief Interface for classes constructing Stack hints. /// /// If a PathDiagnosticEvent occurs in a different frame than the final /// diagnostic the hints can be used to summarize the effect of the call. class StackHintGenerator { public: virtual ~StackHintGenerator() = 0; /// \brief Construct the Diagnostic message for the given ExplodedNode. virtual std::string getMessage(const ExplodedNode *N) = 0; }; /// \brief Constructs a Stack hint for the given symbol. /// /// The class knows how to construct the stack hint message based on /// traversing the CallExpr associated with the call and checking if the given /// symbol is returned or is one of the arguments. /// The hint can be customized by redefining 'getMessageForX()' methods. class StackHintGeneratorForSymbol : public StackHintGenerator { private: SymbolRef Sym; std::string Msg; public: StackHintGeneratorForSymbol(SymbolRef S, StringRef M) : Sym(S), Msg(M) {} ~StackHintGeneratorForSymbol() override {} /// \brief Search the call expression for the symbol Sym and dispatch the /// 'getMessageForX()' methods to construct a specific message. std::string getMessage(const ExplodedNode *N) override; /// Produces the message of the following form: /// 'Msg via Nth parameter' virtual std::string getMessageForArg(const Expr *ArgE, unsigned ArgIndex); virtual std::string getMessageForReturn(const CallExpr *CallExpr) { return Msg; } virtual std::string getMessageForSymbolNotFound() { return Msg; } }; class PathDiagnosticEventPiece : public PathDiagnosticSpotPiece { Optional<bool> IsPrunable; /// If the event occurs in a different frame than the final diagnostic, /// supply a message that will be used to construct an extra hint on the /// returns from all the calls on the stack from this event to the final /// diagnostic. std::unique_ptr<StackHintGenerator> CallStackHint; public: PathDiagnosticEventPiece(const PathDiagnosticLocation &pos, StringRef s, bool addPosRange = true, StackHintGenerator *stackHint = nullptr) : PathDiagnosticSpotPiece(pos, s, Event, addPosRange), CallStackHint(stackHint) {} ~PathDiagnosticEventPiece() override; /// Mark the diagnostic piece as being potentially prunable. This /// flag may have been previously set, at which point it will not /// be reset unless one specifies to do so. void setPrunable(bool isPrunable, bool override = false) { if (IsPrunable.hasValue() && !override) return; IsPrunable = isPrunable; } /// Return true if the diagnostic piece is prunable. bool isPrunable() const { return IsPrunable.hasValue() ? IsPrunable.getValue() : false; } bool hasCallStackHint() { return (bool)CallStackHint; } /// Produce the hint for the given node. The node contains /// information about the call for which the diagnostic can be generated. std::string getCallStackMessage(const ExplodedNode *N) { if (CallStackHint) return CallStackHint->getMessage(N); return ""; } void dump() const override; static inline bool classof(const PathDiagnosticPiece *P) { return P->getKind() == Event; } }; class PathDiagnosticCallPiece : public PathDiagnosticPiece { PathDiagnosticCallPiece(const Decl *callerD, const PathDiagnosticLocation &callReturnPos) : PathDiagnosticPiece(Call), Caller(callerD), Callee(nullptr), NoExit(false), callReturn(callReturnPos) {} PathDiagnosticCallPiece(PathPieces &oldPath, const Decl *caller) : PathDiagnosticPiece(Call), Caller(caller), Callee(nullptr), NoExit(true), path(oldPath) {} const Decl *Caller; const Decl *Callee; // Flag signifying that this diagnostic has only call enter and no matching // call exit. bool NoExit; // The custom string, which should appear after the call Return Diagnostic. // TODO: Should we allow multiple diagnostics? std::string CallStackMessage; public: PathDiagnosticLocation callEnter; PathDiagnosticLocation callEnterWithin; PathDiagnosticLocation callReturn; PathPieces path; ~PathDiagnosticCallPiece() override; const Decl *getCaller() const { return Caller; } const Decl *getCallee() const { return Callee; } void setCallee(const CallEnter &CE, const SourceManager &SM); bool hasCallStackMessage() { return !CallStackMessage.empty(); } void setCallStackMessage(StringRef st) { CallStackMessage = st; } PathDiagnosticLocation getLocation() const override { return callEnter; } IntrusiveRefCntPtr<PathDiagnosticEventPiece> getCallEnterEvent() const; IntrusiveRefCntPtr<PathDiagnosticEventPiece> getCallEnterWithinCallerEvent() const; IntrusiveRefCntPtr<PathDiagnosticEventPiece> getCallExitEvent() const; void flattenLocations() override { callEnter.flatten(); callReturn.flatten(); for (PathPieces::iterator I = path.begin(), E = path.end(); I != E; ++I) (*I)->flattenLocations(); } static PathDiagnosticCallPiece *construct(const ExplodedNode *N, const CallExitEnd &CE, const SourceManager &SM); static PathDiagnosticCallPiece *construct(PathPieces &pieces, const Decl *caller); void dump() const override; void Profile(llvm::FoldingSetNodeID &ID) const override; static inline bool classof(const PathDiagnosticPiece *P) { return P->getKind() == Call; } }; class PathDiagnosticControlFlowPiece : public PathDiagnosticPiece { std::vector<PathDiagnosticLocationPair> LPairs; public: PathDiagnosticControlFlowPiece(const PathDiagnosticLocation &startPos, const PathDiagnosticLocation &endPos, StringRef s) : PathDiagnosticPiece(s, ControlFlow) { LPairs.push_back(PathDiagnosticLocationPair(startPos, endPos)); } PathDiagnosticControlFlowPiece(const PathDiagnosticLocation &startPos, const PathDiagnosticLocation &endPos) : PathDiagnosticPiece(ControlFlow) { LPairs.push_back(PathDiagnosticLocationPair(startPos, endPos)); } ~PathDiagnosticControlFlowPiece() override; PathDiagnosticLocation getStartLocation() const { assert(!LPairs.empty() && "PathDiagnosticControlFlowPiece needs at least one location."); return LPairs[0].getStart(); } PathDiagnosticLocation getEndLocation() const { assert(!LPairs.empty() && "PathDiagnosticControlFlowPiece needs at least one location."); return LPairs[0].getEnd(); } void setStartLocation(const PathDiagnosticLocation &L) { LPairs[0].setStart(L); } void setEndLocation(const PathDiagnosticLocation &L) { LPairs[0].setEnd(L); } void push_back(const PathDiagnosticLocationPair &X) { LPairs.push_back(X); } PathDiagnosticLocation getLocation() const override { return getStartLocation(); } typedef std::vector<PathDiagnosticLocationPair>::iterator iterator; iterator begin() { return LPairs.begin(); } iterator end() { return LPairs.end(); } void flattenLocations() override { for (iterator I=begin(), E=end(); I!=E; ++I) I->flatten(); } typedef std::vector<PathDiagnosticLocationPair>::const_iterator const_iterator; const_iterator begin() const { return LPairs.begin(); } const_iterator end() const { return LPairs.end(); } static inline bool classof(const PathDiagnosticPiece *P) { return P->getKind() == ControlFlow; } void dump() const override; void Profile(llvm::FoldingSetNodeID &ID) const override; }; class PathDiagnosticMacroPiece : public PathDiagnosticSpotPiece { public: PathDiagnosticMacroPiece(const PathDiagnosticLocation &pos) : PathDiagnosticSpotPiece(pos, "", Macro) {} ~PathDiagnosticMacroPiece() override; PathPieces subPieces; bool containsEvent() const; void flattenLocations() override { PathDiagnosticSpotPiece::flattenLocations(); for (PathPieces::iterator I = subPieces.begin(), E = subPieces.end(); I != E; ++I) (*I)->flattenLocations(); } static inline bool classof(const PathDiagnosticPiece *P) { return P->getKind() == Macro; } void dump() const override; void Profile(llvm::FoldingSetNodeID &ID) const override; }; /// PathDiagnostic - PathDiagnostic objects represent a single path-sensitive /// diagnostic. It represents an ordered-collection of PathDiagnosticPieces, /// each which represent the pieces of the path. class PathDiagnostic : public llvm::FoldingSetNode { std::string CheckName; const Decl *DeclWithIssue; std::string BugType; std::string VerboseDesc; std::string ShortDesc; std::string Category; std::deque<std::string> OtherDesc; /// \brief Loc The location of the path diagnostic report. PathDiagnosticLocation Loc; PathPieces pathImpl; SmallVector<PathPieces *, 3> pathStack; /// \brief Important bug uniqueing location. /// The location info is useful to differentiate between bugs. PathDiagnosticLocation UniqueingLoc; const Decl *UniqueingDecl; PathDiagnostic() = delete; public: PathDiagnostic(StringRef CheckName, const Decl *DeclWithIssue, StringRef bugtype, StringRef verboseDesc, StringRef shortDesc, StringRef category, PathDiagnosticLocation LocationToUnique, const Decl *DeclToUnique); ~PathDiagnostic(); const PathPieces &path; /// Return the path currently used by builders for constructing the /// PathDiagnostic. PathPieces &getActivePath() { if (pathStack.empty()) return pathImpl; return *pathStack.back(); } /// Return a mutable version of 'path'. PathPieces &getMutablePieces() { return pathImpl; } /// Return the unrolled size of the path. unsigned full_size(); void pushActivePath(PathPieces *p) { pathStack.push_back(p); } void popActivePath() { if (!pathStack.empty()) pathStack.pop_back(); } bool isWithinCall() const { return !pathStack.empty(); } void setEndOfPath(std::unique_ptr<PathDiagnosticPiece> EndPiece) { assert(!Loc.isValid() && "End location already set!"); Loc = EndPiece->getLocation(); assert(Loc.isValid() && "Invalid location for end-of-path piece"); getActivePath().push_back(EndPiece.release()); } void appendToDesc(StringRef S) { if (!ShortDesc.empty()) ShortDesc.append(S); VerboseDesc.append(S); } void resetPath() { pathStack.clear(); pathImpl.clear(); Loc = PathDiagnosticLocation(); } /// \brief If the last piece of the report point to the header file, resets /// the location of the report to be the last location in the main source /// file. void resetDiagnosticLocationToMainFile(); StringRef getVerboseDescription() const { return VerboseDesc; } StringRef getShortDescription() const { return ShortDesc.empty() ? VerboseDesc : ShortDesc; } StringRef getCheckName() const { return CheckName; } StringRef getBugType() const { return BugType; } StringRef getCategory() const { return Category; } /// Return the semantic context where an issue occurred. If the /// issue occurs along a path, this represents the "central" area /// where the bug manifests. const Decl *getDeclWithIssue() const { return DeclWithIssue; } typedef std::deque<std::string>::const_iterator meta_iterator; meta_iterator meta_begin() const { return OtherDesc.begin(); } meta_iterator meta_end() const { return OtherDesc.end(); } void addMeta(StringRef s) { OtherDesc.push_back(s); } PathDiagnosticLocation getLocation() const { assert(Loc.isValid() && "No report location set yet!"); return Loc; } /// \brief Get the location on which the report should be uniqued. PathDiagnosticLocation getUniqueingLoc() const { return UniqueingLoc; } /// \brief Get the declaration containing the uniqueing location. const Decl *getUniqueingDecl() const { return UniqueingDecl; } void flattenLocations() { Loc.flatten(); for (PathPieces::iterator I = pathImpl.begin(), E = pathImpl.end(); I != E; ++I) (*I)->flattenLocations(); } /// Profiles the diagnostic, independent of the path it references. /// /// This can be used to merge diagnostics that refer to the same issue /// along different paths. void Profile(llvm::FoldingSetNodeID &ID) const; /// Profiles the diagnostic, including its path. /// /// Two diagnostics with the same issue along different paths will generate /// different profiles. void FullProfile(llvm::FoldingSetNodeID &ID) const; }; } // end GR namespace } //end clang namespace #endif
0
repos/DirectXShaderCompiler/tools/clang/include/clang/StaticAnalyzer/Core
repos/DirectXShaderCompiler/tools/clang/include/clang/StaticAnalyzer/Core/BugReporter/BugReporterVisitor.h
//===--- BugReporterVisitor.h - Generate PathDiagnostics -------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file declares BugReporterVisitors, which are used to generate enhanced // diagnostic traces. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_STATICANALYZER_CORE_BUGREPORTER_BUGREPORTERVISITOR_H #define LLVM_CLANG_STATICANALYZER_CORE_BUGREPORTER_BUGREPORTERVISITOR_H #include "clang/StaticAnalyzer/Core/PathSensitive/SVals.h" #include "llvm/ADT/FoldingSet.h" namespace clang { namespace ento { class BugReport; class BugReporterContext; class ExplodedNode; class MemRegion; class PathDiagnosticPiece; /// \brief BugReporterVisitors are used to add custom diagnostics along a path. /// /// Custom visitors should subclass the BugReporterVisitorImpl class for a /// default implementation of the clone() method. /// (Warning: if you have a deep subclass of BugReporterVisitorImpl, the /// default implementation of clone() will NOT do the right thing, and you /// will have to provide your own implementation.) class BugReporterVisitor : public llvm::FoldingSetNode { public: virtual ~BugReporterVisitor(); /// \brief Returns a copy of this BugReporter. /// /// Custom BugReporterVisitors should not override this method directly. /// Instead, they should inherit from BugReporterVisitorImpl and provide /// a protected or public copy constructor. /// /// (Warning: if you have a deep subclass of BugReporterVisitorImpl, the /// default implementation of clone() will NOT do the right thing, and you /// will have to provide your own implementation.) virtual std::unique_ptr<BugReporterVisitor> clone() const = 0; /// \brief Return a diagnostic piece which should be associated with the /// given node. /// /// The last parameter can be used to register a new visitor with the given /// BugReport while processing a node. virtual PathDiagnosticPiece *VisitNode(const ExplodedNode *Succ, const ExplodedNode *Pred, BugReporterContext &BRC, BugReport &BR) = 0; /// \brief Provide custom definition for the final diagnostic piece on the /// path - the piece, which is displayed before the path is expanded. /// /// If returns NULL the default implementation will be used. /// Also note that at most one visitor of a BugReport should generate a /// non-NULL end of path diagnostic piece. virtual std::unique_ptr<PathDiagnosticPiece> getEndPath(BugReporterContext &BRC, const ExplodedNode *N, BugReport &BR); virtual void Profile(llvm::FoldingSetNodeID &ID) const = 0; /// \brief Generates the default final diagnostic piece. static std::unique_ptr<PathDiagnosticPiece> getDefaultEndPath(BugReporterContext &BRC, const ExplodedNode *N, BugReport &BR); }; /// This class provides a convenience implementation for clone() using the /// Curiously-Recurring Template Pattern. If you are implementing a custom /// BugReporterVisitor, subclass BugReporterVisitorImpl and provide a public /// or protected copy constructor. /// /// (Warning: if you have a deep subclass of BugReporterVisitorImpl, the /// default implementation of clone() will NOT do the right thing, and you /// will have to provide your own implementation.) template <class DERIVED> class BugReporterVisitorImpl : public BugReporterVisitor { std::unique_ptr<BugReporterVisitor> clone() const override { return llvm::make_unique<DERIVED>(*static_cast<const DERIVED *>(this)); } }; class FindLastStoreBRVisitor : public BugReporterVisitorImpl<FindLastStoreBRVisitor> { const MemRegion *R; SVal V; bool Satisfied; /// If the visitor is tracking the value directly responsible for the /// bug, we are going to employ false positive suppression. bool EnableNullFPSuppression; public: /// Creates a visitor for every VarDecl inside a Stmt and registers it with /// the BugReport. static void registerStatementVarDecls(BugReport &BR, const Stmt *S, bool EnableNullFPSuppression); FindLastStoreBRVisitor(KnownSVal V, const MemRegion *R, bool InEnableNullFPSuppression) : R(R), V(V), Satisfied(false), EnableNullFPSuppression(InEnableNullFPSuppression) {} void Profile(llvm::FoldingSetNodeID &ID) const override; PathDiagnosticPiece *VisitNode(const ExplodedNode *N, const ExplodedNode *PrevN, BugReporterContext &BRC, BugReport &BR) override; }; class TrackConstraintBRVisitor : public BugReporterVisitorImpl<TrackConstraintBRVisitor> { DefinedSVal Constraint; bool Assumption; bool IsSatisfied; bool IsZeroCheck; /// We should start tracking from the last node along the path in which the /// value is constrained. bool IsTrackingTurnedOn; public: TrackConstraintBRVisitor(DefinedSVal constraint, bool assumption) : Constraint(constraint), Assumption(assumption), IsSatisfied(false), IsZeroCheck(!Assumption && Constraint.getAs<Loc>()), IsTrackingTurnedOn(false) {} void Profile(llvm::FoldingSetNodeID &ID) const override; /// Return the tag associated with this visitor. This tag will be used /// to make all PathDiagnosticPieces created by this visitor. static const char *getTag(); PathDiagnosticPiece *VisitNode(const ExplodedNode *N, const ExplodedNode *PrevN, BugReporterContext &BRC, BugReport &BR) override; private: /// Checks if the constraint is valid in the current state. bool isUnderconstrained(const ExplodedNode *N) const; }; /// \class NilReceiverBRVisitor /// \brief Prints path notes when a message is sent to a nil receiver. class NilReceiverBRVisitor : public BugReporterVisitorImpl<NilReceiverBRVisitor> { public: void Profile(llvm::FoldingSetNodeID &ID) const override { static int x = 0; ID.AddPointer(&x); } PathDiagnosticPiece *VisitNode(const ExplodedNode *N, const ExplodedNode *PrevN, BugReporterContext &BRC, BugReport &BR) override; /// If the statement is a message send expression with nil receiver, returns /// the receiver expression. Returns NULL otherwise. static const Expr *getNilReceiver(const Stmt *S, const ExplodedNode *N); }; /// Visitor that tries to report interesting diagnostics from conditions. class ConditionBRVisitor : public BugReporterVisitorImpl<ConditionBRVisitor> { public: void Profile(llvm::FoldingSetNodeID &ID) const override { static int x = 0; ID.AddPointer(&x); } /// Return the tag associated with this visitor. This tag will be used /// to make all PathDiagnosticPieces created by this visitor. static const char *getTag(); PathDiagnosticPiece *VisitNode(const ExplodedNode *N, const ExplodedNode *Prev, BugReporterContext &BRC, BugReport &BR) override; PathDiagnosticPiece *VisitNodeImpl(const ExplodedNode *N, const ExplodedNode *Prev, BugReporterContext &BRC, BugReport &BR); PathDiagnosticPiece *VisitTerminator(const Stmt *Term, const ExplodedNode *N, const CFGBlock *srcBlk, const CFGBlock *dstBlk, BugReport &R, BugReporterContext &BRC); PathDiagnosticPiece *VisitTrueTest(const Expr *Cond, bool tookTrue, BugReporterContext &BRC, BugReport &R, const ExplodedNode *N); PathDiagnosticPiece *VisitTrueTest(const Expr *Cond, const DeclRefExpr *DR, const bool tookTrue, BugReporterContext &BRC, BugReport &R, const ExplodedNode *N); PathDiagnosticPiece *VisitTrueTest(const Expr *Cond, const BinaryOperator *BExpr, const bool tookTrue, BugReporterContext &BRC, BugReport &R, const ExplodedNode *N); PathDiagnosticPiece *VisitConditionVariable(StringRef LhsString, const Expr *CondVarExpr, const bool tookTrue, BugReporterContext &BRC, BugReport &R, const ExplodedNode *N); bool patternMatch(const Expr *Ex, raw_ostream &Out, BugReporterContext &BRC, BugReport &R, const ExplodedNode *N, Optional<bool> &prunable); }; /// \brief Suppress reports that might lead to known false positives. /// /// Currently this suppresses reports based on locations of bugs. class LikelyFalsePositiveSuppressionBRVisitor : public BugReporterVisitorImpl<LikelyFalsePositiveSuppressionBRVisitor> { public: static void *getTag() { static int Tag = 0; return static_cast<void *>(&Tag); } void Profile(llvm::FoldingSetNodeID &ID) const override { ID.AddPointer(getTag()); } PathDiagnosticPiece *VisitNode(const ExplodedNode *N, const ExplodedNode *Prev, BugReporterContext &BRC, BugReport &BR) override { return nullptr; } std::unique_ptr<PathDiagnosticPiece> getEndPath(BugReporterContext &BRC, const ExplodedNode *N, BugReport &BR) override; }; /// \brief When a region containing undefined value or '0' value is passed /// as an argument in a call, marks the call as interesting. /// /// As a result, BugReporter will not prune the path through the function even /// if the region's contents are not modified/accessed by the call. class UndefOrNullArgVisitor : public BugReporterVisitorImpl<UndefOrNullArgVisitor> { /// The interesting memory region this visitor is tracking. const MemRegion *R; public: UndefOrNullArgVisitor(const MemRegion *InR) : R(InR) {} void Profile(llvm::FoldingSetNodeID &ID) const override { static int Tag = 0; ID.AddPointer(&Tag); ID.AddPointer(R); } PathDiagnosticPiece *VisitNode(const ExplodedNode *N, const ExplodedNode *PrevN, BugReporterContext &BRC, BugReport &BR) override; }; class SuppressInlineDefensiveChecksVisitor : public BugReporterVisitorImpl<SuppressInlineDefensiveChecksVisitor> { /// The symbolic value for which we are tracking constraints. /// This value is constrained to null in the end of path. DefinedSVal V; /// Track if we found the node where the constraint was first added. bool IsSatisfied; /// Since the visitors can be registered on nodes previous to the last /// node in the BugReport, but the path traversal always starts with the last /// node, the visitor invariant (that we start with a node in which V is null) /// might not hold when node visitation starts. We are going to start tracking /// from the last node in which the value is null. bool IsTrackingTurnedOn; public: SuppressInlineDefensiveChecksVisitor(DefinedSVal Val, const ExplodedNode *N); void Profile(llvm::FoldingSetNodeID &ID) const override; /// Return the tag associated with this visitor. This tag will be used /// to make all PathDiagnosticPieces created by this visitor. static const char *getTag(); PathDiagnosticPiece *VisitNode(const ExplodedNode *Succ, const ExplodedNode *Pred, BugReporterContext &BRC, BugReport &BR) override; }; namespace bugreporter { /// Attempts to add visitors to trace a null or undefined value back to its /// point of origin, whether it is a symbol constrained to null or an explicit /// assignment. /// /// \param N A node "downstream" from the evaluation of the statement. /// \param S The statement whose value is null or undefined. /// \param R The bug report to which visitors should be attached. /// \param IsArg Whether the statement is an argument to an inlined function. /// If this is the case, \p N \em must be the CallEnter node for /// the function. /// \param EnableNullFPSuppression Whether we should employ false positive /// suppression (inlined defensive checks, returned null). /// /// \return Whether or not the function was able to add visitors for this /// statement. Note that returning \c true does not actually imply /// that any visitors were added. bool trackNullOrUndefValue(const ExplodedNode *N, const Stmt *S, BugReport &R, bool IsArg = false, bool EnableNullFPSuppression = true); const Expr *getDerefExpr(const Stmt *S); const Stmt *GetDenomExpr(const ExplodedNode *N); const Stmt *GetRetValExpr(const ExplodedNode *N); bool isDeclRefExprToReference(const Expr *E); } // end namespace clang } // end namespace ento } // end namespace bugreporter #endif
0
repos/DirectXShaderCompiler/tools/clang/include/clang/StaticAnalyzer/Core
repos/DirectXShaderCompiler/tools/clang/include/clang/StaticAnalyzer/Core/BugReporter/BugType.h
//===--- BugType.h - Bug Information Desciption ----------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines BugType, a class representing a bug type. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_STATICANALYZER_CORE_BUGREPORTER_BUGTYPE_H #define LLVM_CLANG_STATICANALYZER_CORE_BUGREPORTER_BUGTYPE_H #include "clang/Basic/LLVM.h" #include "clang/StaticAnalyzer/Core/BugReporter/CommonBugCategories.h" #include "clang/StaticAnalyzer/Core/Checker.h" #include "llvm/ADT/FoldingSet.h" #include <string> namespace clang { namespace ento { class BugReporter; class ExplodedNode; class ExprEngine; class BugType { private: const CheckName Check; const std::string Name; const std::string Category; bool SuppressonSink; virtual void anchor(); public: BugType(class CheckName check, StringRef name, StringRef cat) : Check(check), Name(name), Category(cat), SuppressonSink(false) {} BugType(const CheckerBase *checker, StringRef name, StringRef cat) : Check(checker->getCheckName()), Name(name), Category(cat), SuppressonSink(false) {} virtual ~BugType() {} // FIXME: Should these be made strings as well? StringRef getName() const { return Name; } StringRef getCategory() const { return Category; } StringRef getCheckName() const { return Check.getName(); } /// isSuppressOnSink - Returns true if bug reports associated with this bug /// type should be suppressed if the end node of the report is post-dominated /// by a sink node. bool isSuppressOnSink() const { return SuppressonSink; } void setSuppressOnSink(bool x) { SuppressonSink = x; } virtual void FlushReports(BugReporter& BR); }; class BuiltinBug : public BugType { const std::string desc; void anchor() override; public: BuiltinBug(class CheckName check, const char *name, const char *description) : BugType(check, name, categories::LogicError), desc(description) {} BuiltinBug(const CheckerBase *checker, const char *name, const char *description) : BugType(checker, name, categories::LogicError), desc(description) {} BuiltinBug(const CheckerBase *checker, const char *name) : BugType(checker, name, categories::LogicError), desc(name) {} StringRef getDescription() const { return desc; } }; } // end GR namespace } // end clang namespace #endif
0
repos/DirectXShaderCompiler/tools/clang/include/clang
repos/DirectXShaderCompiler/tools/clang/include/clang/ASTMatchers/ASTMatchersMacros.h
//===--- ASTMatchersMacros.h - Structural query framework -------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // Defines macros that enable us to define new matchers in a single place. // Since a matcher is a function which returns a Matcher<T> object, where // T is the type of the actual implementation of the matcher, the macros allow // us to write matchers like functions and take care of the definition of the // class boilerplate. // // Note that when you define a matcher with an AST_MATCHER* macro, only the // function which creates the matcher goes into the current namespace - the // class that implements the actual matcher, which gets returned by the // generator function, is put into the 'internal' namespace. This allows us // to only have the functions (which is all the user cares about) in the // 'ast_matchers' namespace and hide the boilerplate. // // To define a matcher in user code, put it into your own namespace. This would // help to prevent ODR violations in case a matcher with the same name is // defined in multiple translation units: // // namespace my_matchers { // AST_MATCHER_P(clang::MemberExpr, Member, // clang::ast_matchers::internal::Matcher<clang::ValueDecl>, // InnerMatcher) { // return InnerMatcher.matches(*Node.getMemberDecl(), Finder, Builder); // } // } // namespace my_matchers // // Alternatively, an unnamed namespace may be used: // // namespace clang { // namespace ast_matchers { // namespace { // AST_MATCHER_P(MemberExpr, Member, // internal::Matcher<ValueDecl>, InnerMatcher) { // return InnerMatcher.matches(*Node.getMemberDecl(), Finder, Builder); // } // } // namespace // } // namespace ast_matchers // } // namespace clang // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_ASTMATCHERS_ASTMATCHERSMACROS_H #define LLVM_CLANG_ASTMATCHERS_ASTMATCHERSMACROS_H /// \brief AST_MATCHER_FUNCTION(ReturnType, DefineMatcher) { ... } /// defines a zero parameter function named DefineMatcher() that returns a /// ReturnType object. #define AST_MATCHER_FUNCTION(ReturnType, DefineMatcher) \ inline ReturnType DefineMatcher##_getInstance(); \ inline ReturnType DefineMatcher() { \ return ::clang::ast_matchers::internal::MemoizedMatcher< \ ReturnType, DefineMatcher##_getInstance>::getInstance(); \ } \ inline ReturnType DefineMatcher##_getInstance() /// \brief AST_MATCHER_FUNCTION_P(ReturnType, DefineMatcher, ParamType, Param) { /// ... } /// defines a single-parameter function named DefineMatcher() that returns a /// ReturnType object. /// /// The code between the curly braces has access to the following variables: /// /// Param: the parameter passed to the function; its type /// is ParamType. /// /// The code should return an instance of ReturnType. #define AST_MATCHER_FUNCTION_P(ReturnType, DefineMatcher, ParamType, Param) \ AST_MATCHER_FUNCTION_P_OVERLOAD(ReturnType, DefineMatcher, ParamType, Param, \ 0) #define AST_MATCHER_FUNCTION_P_OVERLOAD(ReturnType, DefineMatcher, ParamType, \ Param, OverloadId) \ inline ReturnType DefineMatcher(ParamType const &Param); \ typedef ReturnType (&DefineMatcher##_Type##OverloadId)(ParamType const &); \ inline ReturnType DefineMatcher(ParamType const &Param) /// \brief AST_MATCHER(Type, DefineMatcher) { ... } /// defines a zero parameter function named DefineMatcher() that returns a /// Matcher<Type> object. /// /// The code between the curly braces has access to the following variables: /// /// Node: the AST node being matched; its type is Type. /// Finder: an ASTMatchFinder*. /// Builder: a BoundNodesTreeBuilder*. /// /// The code should return true if 'Node' matches. #define AST_MATCHER(Type, DefineMatcher) \ namespace internal { \ class matcher_##DefineMatcher##Matcher \ : public ::clang::ast_matchers::internal::MatcherInterface<Type> { \ public: \ explicit matcher_##DefineMatcher##Matcher() {} \ bool matches(const Type &Node, \ ::clang::ast_matchers::internal::ASTMatchFinder *Finder, \ ::clang::ast_matchers::internal::BoundNodesTreeBuilder \ *Builder) const override; \ }; \ } \ inline ::clang::ast_matchers::internal::Matcher<Type> DefineMatcher() { \ return ::clang::ast_matchers::internal::makeMatcher( \ new internal::matcher_##DefineMatcher##Matcher()); \ } \ inline bool internal::matcher_##DefineMatcher##Matcher::matches( \ const Type &Node, \ ::clang::ast_matchers::internal::ASTMatchFinder *Finder, \ ::clang::ast_matchers::internal::BoundNodesTreeBuilder *Builder) const /// \brief AST_MATCHER_P(Type, DefineMatcher, ParamType, Param) { ... } /// defines a single-parameter function named DefineMatcher() that returns a /// Matcher<Type> object. /// /// The code between the curly braces has access to the following variables: /// /// Node: the AST node being matched; its type is Type. /// Param: the parameter passed to the function; its type /// is ParamType. /// Finder: an ASTMatchFinder*. /// Builder: a BoundNodesTreeBuilder*. /// /// The code should return true if 'Node' matches. #define AST_MATCHER_P(Type, DefineMatcher, ParamType, Param) \ AST_MATCHER_P_OVERLOAD(Type, DefineMatcher, ParamType, Param, 0) #define AST_MATCHER_P_OVERLOAD(Type, DefineMatcher, ParamType, Param, \ OverloadId) \ namespace internal { \ class matcher_##DefineMatcher##OverloadId##Matcher \ : public ::clang::ast_matchers::internal::MatcherInterface<Type> { \ public: \ explicit matcher_##DefineMatcher##OverloadId##Matcher( \ ParamType const &A##Param) \ : Param(A##Param) {} \ bool matches(const Type &Node, \ ::clang::ast_matchers::internal::ASTMatchFinder *Finder, \ ::clang::ast_matchers::internal::BoundNodesTreeBuilder \ *Builder) const override; \ \ private: \ ParamType const Param; \ }; \ } \ inline ::clang::ast_matchers::internal::Matcher<Type> DefineMatcher( \ ParamType const &Param) { \ return ::clang::ast_matchers::internal::makeMatcher( \ new internal::matcher_##DefineMatcher##OverloadId##Matcher(Param)); \ } \ typedef ::clang::ast_matchers::internal::Matcher<Type>( \ &DefineMatcher##_Type##OverloadId)(ParamType const &Param); \ inline bool internal::matcher_##DefineMatcher##OverloadId##Matcher::matches( \ const Type &Node, \ ::clang::ast_matchers::internal::ASTMatchFinder *Finder, \ ::clang::ast_matchers::internal::BoundNodesTreeBuilder *Builder) const /// \brief AST_MATCHER_P2( /// Type, DefineMatcher, ParamType1, Param1, ParamType2, Param2) { ... } /// defines a two-parameter function named DefineMatcher() that returns a /// Matcher<Type> object. /// /// The code between the curly braces has access to the following variables: /// /// Node: the AST node being matched; its type is Type. /// Param1, Param2: the parameters passed to the function; their types /// are ParamType1 and ParamType2. /// Finder: an ASTMatchFinder*. /// Builder: a BoundNodesTreeBuilder*. /// /// The code should return true if 'Node' matches. #define AST_MATCHER_P2(Type, DefineMatcher, ParamType1, Param1, ParamType2, \ Param2) \ AST_MATCHER_P2_OVERLOAD(Type, DefineMatcher, ParamType1, Param1, ParamType2, \ Param2, 0) #define AST_MATCHER_P2_OVERLOAD(Type, DefineMatcher, ParamType1, Param1, \ ParamType2, Param2, OverloadId) \ namespace internal { \ class matcher_##DefineMatcher##OverloadId##Matcher \ : public ::clang::ast_matchers::internal::MatcherInterface<Type> { \ public: \ matcher_##DefineMatcher##OverloadId##Matcher(ParamType1 const &A##Param1, \ ParamType2 const &A##Param2) \ : Param1(A##Param1), Param2(A##Param2) {} \ bool matches(const Type &Node, \ ::clang::ast_matchers::internal::ASTMatchFinder *Finder, \ ::clang::ast_matchers::internal::BoundNodesTreeBuilder \ *Builder) const override; \ \ private: \ ParamType1 const Param1; \ ParamType2 const Param2; \ }; \ } \ inline ::clang::ast_matchers::internal::Matcher<Type> DefineMatcher( \ ParamType1 const &Param1, ParamType2 const &Param2) { \ return ::clang::ast_matchers::internal::makeMatcher( \ new internal::matcher_##DefineMatcher##OverloadId##Matcher(Param1, \ Param2)); \ } \ typedef ::clang::ast_matchers::internal::Matcher<Type>( \ &DefineMatcher##_Type##OverloadId)(ParamType1 const &Param1, \ ParamType2 const &Param2); \ inline bool internal::matcher_##DefineMatcher##OverloadId##Matcher::matches( \ const Type &Node, \ ::clang::ast_matchers::internal::ASTMatchFinder *Finder, \ ::clang::ast_matchers::internal::BoundNodesTreeBuilder *Builder) const /// \brief Construct a type-list to be passed to the AST_POLYMORPHIC_MATCHER* /// macros. /// /// You can't pass something like \c TypeList<Foo, Bar> to a macro, because it /// will look at that as two arguments. However, you can pass /// \c void(TypeList<Foo, Bar>), which works thanks to the parenthesis. /// The \c PolymorphicMatcherWithParam* classes will unpack the function type to /// extract the TypeList object. #define AST_POLYMORPHIC_SUPPORTED_TYPES(...) \ void(::clang::ast_matchers::internal::TypeList<__VA_ARGS__>) /// \brief AST_POLYMORPHIC_MATCHER(DefineMatcher) { ... } /// defines a single-parameter function named DefineMatcher() that is /// polymorphic in the return type. /// /// The variables are the same as for AST_MATCHER, but NodeType will be deduced /// from the calling context. #define AST_POLYMORPHIC_MATCHER(DefineMatcher, ReturnTypesF) \ namespace internal { \ template <typename NodeType> \ class matcher_##DefineMatcher##Matcher \ : public ::clang::ast_matchers::internal::MatcherInterface<NodeType> { \ public: \ bool matches(const NodeType &Node, \ ::clang::ast_matchers::internal::ASTMatchFinder *Finder, \ ::clang::ast_matchers::internal::BoundNodesTreeBuilder \ *Builder) const override; \ }; \ } \ inline ::clang::ast_matchers::internal::PolymorphicMatcherWithParam0< \ internal::matcher_##DefineMatcher##Matcher, ReturnTypesF> \ DefineMatcher() { \ return ::clang::ast_matchers::internal::PolymorphicMatcherWithParam0< \ internal::matcher_##DefineMatcher##Matcher, ReturnTypesF>(); \ } \ template <typename NodeType> \ bool internal::matcher_##DefineMatcher##Matcher<NodeType>::matches( \ const NodeType &Node, \ ::clang::ast_matchers::internal::ASTMatchFinder *Finder, \ ::clang::ast_matchers::internal::BoundNodesTreeBuilder *Builder) const /// \brief AST_POLYMORPHIC_MATCHER_P(DefineMatcher, ParamType, Param) { ... } /// defines a single-parameter function named DefineMatcher() that is /// polymorphic in the return type. /// /// The variables are the same as for /// AST_MATCHER_P, with the addition of NodeType, which specifies the node type /// of the matcher Matcher<NodeType> returned by the function matcher(). /// /// FIXME: Pull out common code with above macro? #define AST_POLYMORPHIC_MATCHER_P(DefineMatcher, ReturnTypesF, ParamType, \ Param) \ AST_POLYMORPHIC_MATCHER_P_OVERLOAD(DefineMatcher, ReturnTypesF, ParamType, \ Param, 0) #define AST_POLYMORPHIC_MATCHER_P_OVERLOAD(DefineMatcher, ReturnTypesF, \ ParamType, Param, OverloadId) \ namespace internal { \ template <typename NodeType, typename ParamT> \ class matcher_##DefineMatcher##OverloadId##Matcher \ : public ::clang::ast_matchers::internal::MatcherInterface<NodeType> { \ public: \ explicit matcher_##DefineMatcher##OverloadId##Matcher( \ ParamType const &A##Param) \ : Param(A##Param) {} \ bool matches(const NodeType &Node, \ ::clang::ast_matchers::internal::ASTMatchFinder *Finder, \ ::clang::ast_matchers::internal::BoundNodesTreeBuilder \ *Builder) const override; \ \ private: \ ParamType const Param; \ }; \ } \ inline ::clang::ast_matchers::internal::PolymorphicMatcherWithParam1< \ internal::matcher_##DefineMatcher##OverloadId##Matcher, ParamType, \ ReturnTypesF> \ DefineMatcher(ParamType const &Param) { \ return ::clang::ast_matchers::internal::PolymorphicMatcherWithParam1< \ internal::matcher_##DefineMatcher##OverloadId##Matcher, ParamType, \ ReturnTypesF>(Param); \ } \ typedef ::clang::ast_matchers::internal::PolymorphicMatcherWithParam1< \ internal::matcher_##DefineMatcher##OverloadId##Matcher, ParamType, \ ReturnTypesF>(&DefineMatcher##_Type##OverloadId)( \ ParamType const &Param); \ template <typename NodeType, typename ParamT> \ bool internal:: \ matcher_##DefineMatcher##OverloadId##Matcher<NodeType, ParamT>::matches( \ const NodeType &Node, \ ::clang::ast_matchers::internal::ASTMatchFinder *Finder, \ ::clang::ast_matchers::internal::BoundNodesTreeBuilder *Builder) \ const /// \brief AST_POLYMORPHIC_MATCHER_P2( /// DefineMatcher, ParamType1, Param1, ParamType2, Param2) { ... } /// defines a two-parameter function named matcher() that is polymorphic in /// the return type. /// /// The variables are the same as for AST_MATCHER_P2, with the /// addition of NodeType, which specifies the node type of the matcher /// Matcher<NodeType> returned by the function DefineMatcher(). #define AST_POLYMORPHIC_MATCHER_P2(DefineMatcher, ReturnTypesF, ParamType1, \ Param1, ParamType2, Param2) \ AST_POLYMORPHIC_MATCHER_P2_OVERLOAD(DefineMatcher, ReturnTypesF, ParamType1, \ Param1, ParamType2, Param2, 0) #define AST_POLYMORPHIC_MATCHER_P2_OVERLOAD(DefineMatcher, ReturnTypesF, \ ParamType1, Param1, ParamType2, \ Param2, OverloadId) \ namespace internal { \ template <typename NodeType, typename ParamT1, typename ParamT2> \ class matcher_##DefineMatcher##OverloadId##Matcher \ : public ::clang::ast_matchers::internal::MatcherInterface<NodeType> { \ public: \ matcher_##DefineMatcher##OverloadId##Matcher(ParamType1 const &A##Param1, \ ParamType2 const &A##Param2) \ : Param1(A##Param1), Param2(A##Param2) {} \ bool matches(const NodeType &Node, \ ::clang::ast_matchers::internal::ASTMatchFinder *Finder, \ ::clang::ast_matchers::internal::BoundNodesTreeBuilder \ *Builder) const override; \ \ private: \ ParamType1 const Param1; \ ParamType2 const Param2; \ }; \ } \ inline ::clang::ast_matchers::internal::PolymorphicMatcherWithParam2< \ internal::matcher_##DefineMatcher##OverloadId##Matcher, ParamType1, \ ParamType2, ReturnTypesF> \ DefineMatcher(ParamType1 const &Param1, ParamType2 const &Param2) { \ return ::clang::ast_matchers::internal::PolymorphicMatcherWithParam2< \ internal::matcher_##DefineMatcher##OverloadId##Matcher, ParamType1, \ ParamType2, ReturnTypesF>(Param1, Param2); \ } \ typedef ::clang::ast_matchers::internal::PolymorphicMatcherWithParam2< \ internal::matcher_##DefineMatcher##OverloadId##Matcher, ParamType1, \ ParamType2, ReturnTypesF>(&DefineMatcher##_Type##OverloadId)( \ ParamType1 const &Param1, ParamType2 const &Param2); \ template <typename NodeType, typename ParamT1, typename ParamT2> \ bool internal::matcher_##DefineMatcher##OverloadId##Matcher< \ NodeType, ParamT1, ParamT2>:: \ matches(const NodeType &Node, \ ::clang::ast_matchers::internal::ASTMatchFinder *Finder, \ ::clang::ast_matchers::internal::BoundNodesTreeBuilder *Builder) \ const /// \brief Creates a variadic matcher for both a specific \c Type as well as /// the corresponding \c TypeLoc. #define AST_TYPE_MATCHER(NodeType, MatcherName) \ const ::clang::ast_matchers::internal::VariadicDynCastAllOfMatcher< \ Type, NodeType> MatcherName // FIXME: add a matcher for TypeLoc derived classes using its custom casting // API (no longer dyn_cast) if/when we need such matching /// \brief AST_TYPE_TRAVERSE_MATCHER(MatcherName, FunctionName) defines /// the matcher \c MatcherName that can be used to traverse from one \c Type /// to another. /// /// For a specific \c SpecificType, the traversal is done using /// \c SpecificType::FunctionName. The existence of such a function determines /// whether a corresponding matcher can be used on \c SpecificType. #define AST_TYPE_TRAVERSE_MATCHER(MatcherName, FunctionName, ReturnTypesF) \ namespace internal { \ template <typename T> struct TypeMatcher##MatcherName##Getter { \ static QualType (T::*value())() const { return &T::FunctionName; } \ }; \ } \ const ::clang::ast_matchers::internal::TypeTraversePolymorphicMatcher< \ QualType, \ ::clang::ast_matchers::internal::TypeMatcher##MatcherName##Getter, \ ::clang::ast_matchers::internal::TypeTraverseMatcher, \ ReturnTypesF>::Func MatcherName /// \brief AST_TYPELOC_TRAVERSE_MATCHER(MatcherName, FunctionName) works /// identical to \c AST_TYPE_TRAVERSE_MATCHER but operates on \c TypeLocs. #define AST_TYPELOC_TRAVERSE_MATCHER(MatcherName, FunctionName, ReturnTypesF) \ namespace internal { \ template <typename T> struct TypeLocMatcher##MatcherName##Getter { \ static TypeLoc (T::*value())() const { return &T::FunctionName##Loc; } \ }; \ } \ const ::clang::ast_matchers::internal::TypeTraversePolymorphicMatcher< \ TypeLoc, \ ::clang::ast_matchers::internal::TypeLocMatcher##MatcherName##Getter, \ ::clang::ast_matchers::internal::TypeLocTraverseMatcher, \ ReturnTypesF>::Func MatcherName##Loc; \ AST_TYPE_TRAVERSE_MATCHER(MatcherName, FunctionName##Type, ReturnTypesF) #endif
0
repos/DirectXShaderCompiler/tools/clang/include/clang
repos/DirectXShaderCompiler/tools/clang/include/clang/ASTMatchers/ASTMatchersInternal.h
//===--- ASTMatchersInternal.h - Structural query framework -----*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // Implements the base layer of the matcher framework. // // Matchers are methods that return a Matcher<T> which provides a method // Matches(...) which is a predicate on an AST node. The Matches method's // parameters define the context of the match, which allows matchers to recurse // or store the current node as bound to a specific string, so that it can be // retrieved later. // // In general, matchers have two parts: // 1. A function Matcher<T> MatcherName(<arguments>) which returns a Matcher<T> // based on the arguments and optionally on template type deduction based // on the arguments. Matcher<T>s form an implicit reverse hierarchy // to clang's AST class hierarchy, meaning that you can use a Matcher<Base> // everywhere a Matcher<Derived> is required. // 2. An implementation of a class derived from MatcherInterface<T>. // // The matcher functions are defined in ASTMatchers.h. To make it possible // to implement both the matcher function and the implementation of the matcher // interface in one place, ASTMatcherMacros.h defines macros that allow // implementing a matcher in a single place. // // This file contains the base classes needed to construct the actual matchers. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_ASTMATCHERS_ASTMATCHERSINTERNAL_H #define LLVM_CLANG_ASTMATCHERS_ASTMATCHERSINTERNAL_H #include "clang/AST/ASTTypeTraits.h" #include "clang/AST/Decl.h" #include "clang/AST/DeclCXX.h" #include "clang/AST/DeclObjC.h" #include "clang/AST/DeclTemplate.h" #include "clang/AST/ExprCXX.h" #include "clang/AST/ExprObjC.h" #include "clang/AST/Stmt.h" #include "clang/AST/StmtCXX.h" #include "clang/AST/StmtObjC.h" #include "clang/AST/Type.h" #include "llvm/ADT/Optional.h" #include "llvm/ADT/VariadicFunction.h" #include "llvm/Support/ManagedStatic.h" #include <map> #include <string> #include <vector> namespace clang { namespace ast_matchers { class BoundNodes; namespace internal { /// \brief Internal version of BoundNodes. Holds all the bound nodes. class BoundNodesMap { public: /// \brief Adds \c Node to the map with key \c ID. /// /// The node's base type should be in NodeBaseType or it will be unaccessible. void addNode(StringRef ID, const ast_type_traits::DynTypedNode& DynNode) { NodeMap[ID] = DynNode; } /// \brief Returns the AST node bound to \c ID. /// /// Returns NULL if there was no node bound to \c ID or if there is a node but /// it cannot be converted to the specified type. template <typename T> const T *getNodeAs(StringRef ID) const { IDToNodeMap::const_iterator It = NodeMap.find(ID); if (It == NodeMap.end()) { return nullptr; } return It->second.get<T>(); } ast_type_traits::DynTypedNode getNode(StringRef ID) const { IDToNodeMap::const_iterator It = NodeMap.find(ID); if (It == NodeMap.end()) { return ast_type_traits::DynTypedNode(); } return It->second; } /// \brief Imposes an order on BoundNodesMaps. bool operator<(const BoundNodesMap &Other) const { return NodeMap < Other.NodeMap; } /// \brief A map from IDs to the bound nodes. /// /// Note that we're using std::map here, as for memoization: /// - we need a comparison operator /// - we need an assignment operator typedef std::map<std::string, ast_type_traits::DynTypedNode> IDToNodeMap; const IDToNodeMap &getMap() const { return NodeMap; } /// \brief Returns \c true if this \c BoundNodesMap can be compared, i.e. all /// stored nodes have memoization data. bool isComparable() const { for (const auto &IDAndNode : NodeMap) { if (!IDAndNode.second.getMemoizationData()) return false; } return true; } private: IDToNodeMap NodeMap; }; /// \brief Creates BoundNodesTree objects. /// /// The tree builder is used during the matching process to insert the bound /// nodes from the Id matcher. class BoundNodesTreeBuilder { public: /// \brief A visitor interface to visit all BoundNodes results for a /// BoundNodesTree. class Visitor { public: virtual ~Visitor() {} /// \brief Called multiple times during a single call to VisitMatches(...). /// /// 'BoundNodesView' contains the bound nodes for a single match. virtual void visitMatch(const BoundNodes& BoundNodesView) = 0; }; /// \brief Add a binding from an id to a node. void setBinding(StringRef Id, const ast_type_traits::DynTypedNode &DynNode) { if (Bindings.empty()) Bindings.emplace_back(); for (BoundNodesMap &Binding : Bindings) Binding.addNode(Id, DynNode); } /// \brief Adds a branch in the tree. void addMatch(const BoundNodesTreeBuilder &Bindings); /// \brief Visits all matches that this BoundNodesTree represents. /// /// The ownership of 'ResultVisitor' remains at the caller. void visitMatches(Visitor* ResultVisitor); template <typename ExcludePredicate> bool removeBindings(const ExcludePredicate &Predicate) { Bindings.erase(std::remove_if(Bindings.begin(), Bindings.end(), Predicate), Bindings.end()); return !Bindings.empty(); } /// \brief Imposes an order on BoundNodesTreeBuilders. bool operator<(const BoundNodesTreeBuilder &Other) const { return Bindings < Other.Bindings; } /// \brief Returns \c true if this \c BoundNodesTreeBuilder can be compared, /// i.e. all stored node maps have memoization data. bool isComparable() const { for (const BoundNodesMap &NodesMap : Bindings) { if (!NodesMap.isComparable()) return false; } return true; } private: SmallVector<BoundNodesMap, 16> Bindings; }; class ASTMatchFinder; /// \brief Generic interface for all matchers. /// /// Used by the implementation of Matcher<T> and DynTypedMatcher. /// In general, implement MatcherInterface<T> or SingleNodeMatcherInterface<T> /// instead. class DynMatcherInterface : public RefCountedBaseVPTR { public: /// \brief Returns true if \p DynNode can be matched. /// /// May bind \p DynNode to an ID via \p Builder, or recurse into /// the AST via \p Finder. virtual bool dynMatches(const ast_type_traits::DynTypedNode &DynNode, ASTMatchFinder *Finder, BoundNodesTreeBuilder *Builder) const = 0; }; /// \brief Generic interface for matchers on an AST node of type T. /// /// Implement this if your matcher may need to inspect the children or /// descendants of the node or bind matched nodes to names. If you are /// writing a simple matcher that only inspects properties of the /// current node and doesn't care about its children or descendants, /// implement SingleNodeMatcherInterface instead. template <typename T> class MatcherInterface : public DynMatcherInterface { public: ~MatcherInterface() override {} /// \brief Returns true if 'Node' can be matched. /// /// May bind 'Node' to an ID via 'Builder', or recurse into /// the AST via 'Finder'. virtual bool matches(const T &Node, ASTMatchFinder *Finder, BoundNodesTreeBuilder *Builder) const = 0; bool dynMatches(const ast_type_traits::DynTypedNode &DynNode, ASTMatchFinder *Finder, BoundNodesTreeBuilder *Builder) const override { return matches(DynNode.getUnchecked<T>(), Finder, Builder); } }; /// \brief Interface for matchers that only evaluate properties on a single /// node. template <typename T> class SingleNodeMatcherInterface : public MatcherInterface<T> { public: /// \brief Returns true if the matcher matches the provided node. /// /// A subclass must implement this instead of Matches(). virtual bool matchesNode(const T &Node) const = 0; private: /// Implements MatcherInterface::Matches. bool matches(const T &Node, ASTMatchFinder * /* Finder */, BoundNodesTreeBuilder * /* Builder */) const override { return matchesNode(Node); } }; template <typename> class Matcher; /// \brief Matcher that works on a \c DynTypedNode. /// /// It is constructed from a \c Matcher<T> object and redirects most calls to /// underlying matcher. /// It checks whether the \c DynTypedNode is convertible into the type of the /// underlying matcher and then do the actual match on the actual node, or /// return false if it is not convertible. class DynTypedMatcher { public: /// \brief Takes ownership of the provided implementation pointer. template <typename T> DynTypedMatcher(MatcherInterface<T> *Implementation) : AllowBind(false), SupportedKind(ast_type_traits::ASTNodeKind::getFromNodeKind<T>()), RestrictKind(SupportedKind), Implementation(Implementation) {} /// \brief Construct from a variadic function. enum VariadicOperator { /// \brief Matches nodes for which all provided matchers match. VO_AllOf, /// \brief Matches nodes for which at least one of the provided matchers /// matches. VO_AnyOf, /// \brief Matches nodes for which at least one of the provided matchers /// matches, but doesn't stop at the first match. VO_EachOf, /// \brief Matches nodes that do not match the provided matcher. /// /// Uses the variadic matcher interface, but fails if /// InnerMatchers.size() != 1. VO_UnaryNot }; static DynTypedMatcher constructVariadic(VariadicOperator Op, std::vector<DynTypedMatcher> InnerMatchers); /// \brief Get a "true" matcher for \p NodeKind. /// /// It only checks that the node is of the right kind. static DynTypedMatcher trueMatcher(ast_type_traits::ASTNodeKind NodeKind); void setAllowBind(bool AB) { AllowBind = AB; } /// \brief Check whether this matcher could ever match a node of kind \p Kind. /// \return \c false if this matcher will never match such a node. Otherwise, /// return \c true. bool canMatchNodesOfKind(ast_type_traits::ASTNodeKind Kind) const; /// \brief Return a matcher that points to the same implementation, but /// restricts the node types for \p Kind. DynTypedMatcher dynCastTo(const ast_type_traits::ASTNodeKind Kind) const; /// \brief Returns true if the matcher matches the given \c DynNode. bool matches(const ast_type_traits::DynTypedNode &DynNode, ASTMatchFinder *Finder, BoundNodesTreeBuilder *Builder) const; /// \brief Same as matches(), but skips the kind check. /// /// It is faster, but the caller must ensure the node is valid for the /// kind of this matcher. bool matchesNoKindCheck(const ast_type_traits::DynTypedNode &DynNode, ASTMatchFinder *Finder, BoundNodesTreeBuilder *Builder) const; /// \brief Bind the specified \p ID to the matcher. /// \return A new matcher with the \p ID bound to it if this matcher supports /// binding. Otherwise, returns an empty \c Optional<>. llvm::Optional<DynTypedMatcher> tryBind(StringRef ID) const; /// \brief Returns a unique \p ID for the matcher. /// /// Casting a Matcher<T> to Matcher<U> creates a matcher that has the /// same \c Implementation pointer, but different \c RestrictKind. We need to /// include both in the ID to make it unique. /// /// \c MatcherIDType supports operator< and provides strict weak ordering. typedef std::pair<ast_type_traits::ASTNodeKind, uint64_t> MatcherIDType; MatcherIDType getID() const { /// FIXME: Document the requirements this imposes on matcher /// implementations (no new() implementation_ during a Matches()). return std::make_pair(RestrictKind, reinterpret_cast<uint64_t>(Implementation.get())); } /// \brief Returns the type this matcher works on. /// /// \c matches() will always return false unless the node passed is of this /// or a derived type. ast_type_traits::ASTNodeKind getSupportedKind() const { return SupportedKind; } /// \brief Returns \c true if the passed \c DynTypedMatcher can be converted /// to a \c Matcher<T>. /// /// This method verifies that the underlying matcher in \c Other can process /// nodes of types T. template <typename T> bool canConvertTo() const { return canConvertTo(ast_type_traits::ASTNodeKind::getFromNodeKind<T>()); } bool canConvertTo(ast_type_traits::ASTNodeKind To) const; /// \brief Construct a \c Matcher<T> interface around the dynamic matcher. /// /// This method asserts that \c canConvertTo() is \c true. Callers /// should call \c canConvertTo() first to make sure that \c this is /// compatible with T. template <typename T> Matcher<T> convertTo() const { assert(canConvertTo<T>()); return unconditionalConvertTo<T>(); } /// \brief Same as \c convertTo(), but does not check that the underlying /// matcher can handle a value of T. /// /// If it is not compatible, then this matcher will never match anything. template <typename T> Matcher<T> unconditionalConvertTo() const; private: DynTypedMatcher(ast_type_traits::ASTNodeKind SupportedKind, ast_type_traits::ASTNodeKind RestrictKind, IntrusiveRefCntPtr<DynMatcherInterface> Implementation) : AllowBind(false), SupportedKind(SupportedKind), RestrictKind(RestrictKind), Implementation(std::move(Implementation)) {} bool AllowBind; ast_type_traits::ASTNodeKind SupportedKind; /// \brief A potentially stricter node kind. /// /// It allows to perform implicit and dynamic cast of matchers without /// needing to change \c Implementation. ast_type_traits::ASTNodeKind RestrictKind; IntrusiveRefCntPtr<DynMatcherInterface> Implementation; }; /// \brief Wrapper base class for a wrapping matcher. /// /// This is just a container for a DynTypedMatcher that can be used as a base /// class for another matcher. template <typename T> class WrapperMatcherInterface : public MatcherInterface<T> { protected: explicit WrapperMatcherInterface(DynTypedMatcher &&InnerMatcher) : InnerMatcher(std::move(InnerMatcher)) {} const DynTypedMatcher InnerMatcher; }; /// \brief Wrapper of a MatcherInterface<T> *that allows copying. /// /// A Matcher<Base> can be used anywhere a Matcher<Derived> is /// required. This establishes an is-a relationship which is reverse /// to the AST hierarchy. In other words, Matcher<T> is contravariant /// with respect to T. The relationship is built via a type conversion /// operator rather than a type hierarchy to be able to templatize the /// type hierarchy instead of spelling it out. template <typename T> class Matcher { public: /// \brief Takes ownership of the provided implementation pointer. explicit Matcher(MatcherInterface<T> *Implementation) : Implementation(Implementation) {} /// \brief Implicitly converts \c Other to a Matcher<T>. /// /// Requires \c T to be derived from \c From. template <typename From> Matcher(const Matcher<From> &Other, typename std::enable_if<std::is_base_of<From, T>::value && !std::is_same<From, T>::value>::type * = 0) : Implementation(restrictMatcher(Other.Implementation)) { assert(Implementation.getSupportedKind().isSame( ast_type_traits::ASTNodeKind::getFromNodeKind<T>())); } /// \brief Implicitly converts \c Matcher<Type> to \c Matcher<QualType>. /// /// The resulting matcher is not strict, i.e. ignores qualifiers. template <typename TypeT> Matcher(const Matcher<TypeT> &Other, typename std::enable_if< std::is_same<T, QualType>::value && std::is_same<TypeT, Type>::value>::type* = 0) : Implementation(new TypeToQualType<TypeT>(Other)) {} /// \brief Convert \c this into a \c Matcher<T> by applying dyn_cast<> to the /// argument. /// \c To must be a base class of \c T. template <typename To> Matcher<To> dynCastTo() const { static_assert(std::is_base_of<To, T>::value, "Invalid dynCast call."); return Matcher<To>(Implementation); } /// \brief Forwards the call to the underlying MatcherInterface<T> pointer. bool matches(const T &Node, ASTMatchFinder *Finder, BoundNodesTreeBuilder *Builder) const { return Implementation.matches(ast_type_traits::DynTypedNode::create(Node), Finder, Builder); } /// \brief Returns an ID that uniquely identifies the matcher. DynTypedMatcher::MatcherIDType getID() const { return Implementation.getID(); } /// \brief Extract the dynamic matcher. /// /// The returned matcher keeps the same restrictions as \c this and remembers /// that it is meant to support nodes of type \c T. operator DynTypedMatcher() const { return Implementation; } /// \brief Allows the conversion of a \c Matcher<Type> to a \c /// Matcher<QualType>. /// /// Depending on the constructor argument, the matcher is either strict, i.e. /// does only matches in the absence of qualifiers, or not, i.e. simply /// ignores any qualifiers. template <typename TypeT> class TypeToQualType : public WrapperMatcherInterface<QualType> { public: TypeToQualType(const Matcher<TypeT> &InnerMatcher) : TypeToQualType::WrapperMatcherInterface(InnerMatcher) {} bool matches(const QualType &Node, ASTMatchFinder *Finder, BoundNodesTreeBuilder *Builder) const override { if (Node.isNull()) return false; return this->InnerMatcher.matches( ast_type_traits::DynTypedNode::create(*Node), Finder, Builder); } }; private: // For Matcher<T> <=> Matcher<U> conversions. template <typename U> friend class Matcher; // For DynTypedMatcher::unconditionalConvertTo<T>. friend class DynTypedMatcher; static DynTypedMatcher restrictMatcher(const DynTypedMatcher &Other) { return Other.dynCastTo(ast_type_traits::ASTNodeKind::getFromNodeKind<T>()); } explicit Matcher(const DynTypedMatcher &Implementation) : Implementation(restrictMatcher(Implementation)) { assert(this->Implementation.getSupportedKind() .isSame(ast_type_traits::ASTNodeKind::getFromNodeKind<T>())); } DynTypedMatcher Implementation; }; // class Matcher /// \brief A convenient helper for creating a Matcher<T> without specifying /// the template type argument. template <typename T> inline Matcher<T> makeMatcher(MatcherInterface<T> *Implementation) { return Matcher<T>(Implementation); } /// \brief Specialization of the conversion functions for QualType. /// /// This specialization provides the Matcher<Type>->Matcher<QualType> /// conversion that the static API does. template <> inline Matcher<QualType> DynTypedMatcher::convertTo<QualType>() const { assert(canConvertTo<QualType>()); const ast_type_traits::ASTNodeKind SourceKind = getSupportedKind(); if (SourceKind.isSame( ast_type_traits::ASTNodeKind::getFromNodeKind<Type>())) { // We support implicit conversion from Matcher<Type> to Matcher<QualType> return unconditionalConvertTo<Type>(); } return unconditionalConvertTo<QualType>(); } /// \brief Finds the first node in a range that matches the given matcher. template <typename MatcherT, typename IteratorT> bool matchesFirstInRange(const MatcherT &Matcher, IteratorT Start, IteratorT End, ASTMatchFinder *Finder, BoundNodesTreeBuilder *Builder) { for (IteratorT I = Start; I != End; ++I) { BoundNodesTreeBuilder Result(*Builder); if (Matcher.matches(*I, Finder, &Result)) { *Builder = std::move(Result); return true; } } return false; } /// \brief Finds the first node in a pointer range that matches the given /// matcher. template <typename MatcherT, typename IteratorT> bool matchesFirstInPointerRange(const MatcherT &Matcher, IteratorT Start, IteratorT End, ASTMatchFinder *Finder, BoundNodesTreeBuilder *Builder) { for (IteratorT I = Start; I != End; ++I) { BoundNodesTreeBuilder Result(*Builder); if (Matcher.matches(**I, Finder, &Result)) { *Builder = std::move(Result); return true; } } return false; } /// \brief Metafunction to determine if type T has a member called getDecl. template <typename T> struct has_getDecl { struct Default { int getDecl; }; struct Derived : T, Default { }; template<typename C, C> struct CheckT; // If T::getDecl exists, an ambiguity arises and CheckT will // not be instantiable. This makes f(...) the only available // overload. template<typename C> static char (&f(CheckT<int Default::*, &C::getDecl>*))[1]; template<typename C> static char (&f(...))[2]; static bool const value = sizeof(f<Derived>(nullptr)) == 2; }; /// \brief Matches overloaded operators with a specific name. /// /// The type argument ArgT is not used by this matcher but is used by /// PolymorphicMatcherWithParam1 and should be StringRef. template <typename T, typename ArgT> class HasOverloadedOperatorNameMatcher : public SingleNodeMatcherInterface<T> { static_assert(std::is_same<T, CXXOperatorCallExpr>::value || std::is_base_of<FunctionDecl, T>::value, "unsupported class for matcher"); static_assert(std::is_same<ArgT, StringRef>::value, "argument type must be StringRef"); public: explicit HasOverloadedOperatorNameMatcher(const StringRef Name) : SingleNodeMatcherInterface<T>(), Name(Name) {} bool matchesNode(const T &Node) const override { return matchesSpecialized(Node); } private: /// \brief CXXOperatorCallExpr exist only for calls to overloaded operators /// so this function returns true if the call is to an operator of the given /// name. bool matchesSpecialized(const CXXOperatorCallExpr &Node) const { return getOperatorSpelling(Node.getOperator()) == Name; } /// \brief Returns true only if CXXMethodDecl represents an overloaded /// operator and has the given operator name. bool matchesSpecialized(const FunctionDecl &Node) const { return Node.isOverloadedOperator() && getOperatorSpelling(Node.getOverloadedOperator()) == Name; } std::string Name; }; /// \brief Matches named declarations with a specific name. /// /// See \c hasName() in ASTMatchers.h for details. class HasNameMatcher : public SingleNodeMatcherInterface<NamedDecl> { public: explicit HasNameMatcher(StringRef Name); bool matchesNode(const NamedDecl &Node) const override; private: /// \brief Unqualified match routine. /// /// It is much faster than the full match, but it only works for unqualified /// matches. bool matchesNodeUnqualified(const NamedDecl &Node) const; /// \brief Full match routine /// /// It generates the fully qualified name of the declaration (which is /// expensive) before trying to match. /// It is slower but simple and works on all cases. bool matchesNodeFull(const NamedDecl &Node) const; const bool UseUnqualifiedMatch; const std::string Name; }; /// \brief Matches declarations for QualType and CallExpr. /// /// Type argument DeclMatcherT is required by PolymorphicMatcherWithParam1 but /// not actually used. template <typename T, typename DeclMatcherT> class HasDeclarationMatcher : public WrapperMatcherInterface<T> { static_assert(std::is_same<DeclMatcherT, Matcher<Decl>>::value, "instantiated with wrong types"); public: explicit HasDeclarationMatcher(const Matcher<Decl> &InnerMatcher) : HasDeclarationMatcher::WrapperMatcherInterface(InnerMatcher) {} bool matches(const T &Node, ASTMatchFinder *Finder, BoundNodesTreeBuilder *Builder) const override { return matchesSpecialized(Node, Finder, Builder); } private: /// \brief If getDecl exists as a member of U, returns whether the inner /// matcher matches Node.getDecl(). template <typename U> bool matchesSpecialized( const U &Node, ASTMatchFinder *Finder, BoundNodesTreeBuilder *Builder, typename std::enable_if<has_getDecl<U>::value, int>::type = 0) const { return matchesDecl(Node.getDecl(), Finder, Builder); } /// \brief Extracts the CXXRecordDecl or EnumDecl of a QualType and returns /// whether the inner matcher matches on it. bool matchesSpecialized(const QualType &Node, ASTMatchFinder *Finder, BoundNodesTreeBuilder *Builder) const { /// FIXME: Add other ways to convert... if (Node.isNull()) return false; if (const EnumType *AsEnum = dyn_cast<EnumType>(Node.getTypePtr())) return matchesDecl(AsEnum->getDecl(), Finder, Builder); return matchesDecl(Node->getAsCXXRecordDecl(), Finder, Builder); } /// \brief Gets the TemplateDecl from a TemplateSpecializationType /// and returns whether the inner matches on it. bool matchesSpecialized(const TemplateSpecializationType &Node, ASTMatchFinder *Finder, BoundNodesTreeBuilder *Builder) const { return matchesDecl(Node.getTemplateName().getAsTemplateDecl(), Finder, Builder); } /// \brief Extracts the Decl of the callee of a CallExpr and returns whether /// the inner matcher matches on it. bool matchesSpecialized(const CallExpr &Node, ASTMatchFinder *Finder, BoundNodesTreeBuilder *Builder) const { return matchesDecl(Node.getCalleeDecl(), Finder, Builder); } /// \brief Extracts the Decl of the constructor call and returns whether the /// inner matcher matches on it. bool matchesSpecialized(const CXXConstructExpr &Node, ASTMatchFinder *Finder, BoundNodesTreeBuilder *Builder) const { return matchesDecl(Node.getConstructor(), Finder, Builder); } /// \brief Extracts the \c ValueDecl a \c MemberExpr refers to and returns /// whether the inner matcher matches on it. bool matchesSpecialized(const MemberExpr &Node, ASTMatchFinder *Finder, BoundNodesTreeBuilder *Builder) const { return matchesDecl(Node.getMemberDecl(), Finder, Builder); } /// \brief Returns whether the inner matcher \c Node. Returns false if \c Node /// is \c NULL. bool matchesDecl(const Decl *Node, ASTMatchFinder *Finder, BoundNodesTreeBuilder *Builder) const { return Node != nullptr && this->InnerMatcher.matches( ast_type_traits::DynTypedNode::create(*Node), Finder, Builder); } }; /// \brief IsBaseType<T>::value is true if T is a "base" type in the AST /// node class hierarchies. template <typename T> struct IsBaseType { static const bool value = std::is_same<T, Decl>::value || std::is_same<T, Stmt>::value || std::is_same<T, QualType>::value || std::is_same<T, Type>::value || std::is_same<T, TypeLoc>::value || std::is_same<T, NestedNameSpecifier>::value || std::is_same<T, NestedNameSpecifierLoc>::value || std::is_same<T, CXXCtorInitializer>::value; }; template <typename T> const bool IsBaseType<T>::value; /// \brief Interface that allows matchers to traverse the AST. /// FIXME: Find a better name. /// /// This provides three entry methods for each base node type in the AST: /// - \c matchesChildOf: /// Matches a matcher on every child node of the given node. Returns true /// if at least one child node could be matched. /// - \c matchesDescendantOf: /// Matches a matcher on all descendant nodes of the given node. Returns true /// if at least one descendant matched. /// - \c matchesAncestorOf: /// Matches a matcher on all ancestors of the given node. Returns true if /// at least one ancestor matched. /// /// FIXME: Currently we only allow Stmt and Decl nodes to start a traversal. /// In the future, we wan to implement this for all nodes for which it makes /// sense. In the case of matchesAncestorOf, we'll want to implement it for /// all nodes, as all nodes have ancestors. class ASTMatchFinder { public: /// \brief Defines how we descend a level in the AST when we pass /// through expressions. enum TraversalKind { /// Will traverse any child nodes. TK_AsIs, /// Will not traverse implicit casts and parentheses. TK_IgnoreImplicitCastsAndParentheses }; /// \brief Defines how bindings are processed on recursive matches. enum BindKind { /// Stop at the first match and only bind the first match. BK_First, /// Create results for all combinations of bindings that match. BK_All }; /// \brief Defines which ancestors are considered for a match. enum AncestorMatchMode { /// All ancestors. AMM_All, /// Direct parent only. AMM_ParentOnly }; virtual ~ASTMatchFinder() {} /// \brief Returns true if the given class is directly or indirectly derived /// from a base type matching \c base. /// /// A class is considered to be also derived from itself. virtual bool classIsDerivedFrom(const CXXRecordDecl *Declaration, const Matcher<NamedDecl> &Base, BoundNodesTreeBuilder *Builder) = 0; template <typename T> bool matchesChildOf(const T &Node, const DynTypedMatcher &Matcher, BoundNodesTreeBuilder *Builder, TraversalKind Traverse, BindKind Bind) { static_assert(std::is_base_of<Decl, T>::value || std::is_base_of<Stmt, T>::value || std::is_base_of<NestedNameSpecifier, T>::value || std::is_base_of<NestedNameSpecifierLoc, T>::value || std::is_base_of<TypeLoc, T>::value || std::is_base_of<QualType, T>::value, "unsupported type for recursive matching"); return matchesChildOf(ast_type_traits::DynTypedNode::create(Node), Matcher, Builder, Traverse, Bind); } template <typename T> bool matchesDescendantOf(const T &Node, const DynTypedMatcher &Matcher, BoundNodesTreeBuilder *Builder, BindKind Bind) { static_assert(std::is_base_of<Decl, T>::value || std::is_base_of<Stmt, T>::value || std::is_base_of<NestedNameSpecifier, T>::value || std::is_base_of<NestedNameSpecifierLoc, T>::value || std::is_base_of<TypeLoc, T>::value || std::is_base_of<QualType, T>::value, "unsupported type for recursive matching"); return matchesDescendantOf(ast_type_traits::DynTypedNode::create(Node), Matcher, Builder, Bind); } // FIXME: Implement support for BindKind. template <typename T> bool matchesAncestorOf(const T &Node, const DynTypedMatcher &Matcher, BoundNodesTreeBuilder *Builder, AncestorMatchMode MatchMode) { static_assert(std::is_base_of<Decl, T>::value || std::is_base_of<Stmt, T>::value, "only Decl or Stmt allowed for recursive matching"); return matchesAncestorOf(ast_type_traits::DynTypedNode::create(Node), Matcher, Builder, MatchMode); } virtual ASTContext &getASTContext() const = 0; protected: virtual bool matchesChildOf(const ast_type_traits::DynTypedNode &Node, const DynTypedMatcher &Matcher, BoundNodesTreeBuilder *Builder, TraversalKind Traverse, BindKind Bind) = 0; virtual bool matchesDescendantOf(const ast_type_traits::DynTypedNode &Node, const DynTypedMatcher &Matcher, BoundNodesTreeBuilder *Builder, BindKind Bind) = 0; virtual bool matchesAncestorOf(const ast_type_traits::DynTypedNode &Node, const DynTypedMatcher &Matcher, BoundNodesTreeBuilder *Builder, AncestorMatchMode MatchMode) = 0; }; /// \brief A type-list implementation. /// /// A "linked list" of types, accessible by using the ::head and ::tail /// typedefs. template <typename... Ts> struct TypeList {}; // Empty sentinel type list. template <typename T1, typename... Ts> struct TypeList<T1, Ts...> { /// \brief The first type on the list. typedef T1 head; /// \brief A sublist with the tail. ie everything but the head. /// /// This type is used to do recursion. TypeList<>/EmptyTypeList indicates the /// end of the list. typedef TypeList<Ts...> tail; }; /// \brief The empty type list. typedef TypeList<> EmptyTypeList; /// \brief Helper meta-function to determine if some type \c T is present or /// a parent type in the list. template <typename AnyTypeList, typename T> struct TypeListContainsSuperOf { static const bool value = std::is_base_of<typename AnyTypeList::head, T>::value || TypeListContainsSuperOf<typename AnyTypeList::tail, T>::value; }; template <typename T> struct TypeListContainsSuperOf<EmptyTypeList, T> { static const bool value = false; }; /// \brief A "type list" that contains all types. /// /// Useful for matchers like \c anything and \c unless. typedef TypeList<Decl, Stmt, NestedNameSpecifier, NestedNameSpecifierLoc, QualType, Type, TypeLoc, CXXCtorInitializer> AllNodeBaseTypes; /// \brief Helper meta-function to extract the argument out of a function of /// type void(Arg). /// /// See AST_POLYMORPHIC_SUPPORTED_TYPES for details. template <class T> struct ExtractFunctionArgMeta; template <class T> struct ExtractFunctionArgMeta<void(T)> { typedef T type; }; /// \brief Default type lists for ArgumentAdaptingMatcher matchers. typedef AllNodeBaseTypes AdaptativeDefaultFromTypes; typedef TypeList<Decl, Stmt, NestedNameSpecifier, NestedNameSpecifierLoc, TypeLoc, QualType> AdaptativeDefaultToTypes; /// \brief All types that are supported by HasDeclarationMatcher above. typedef TypeList<CallExpr, CXXConstructExpr, DeclRefExpr, EnumType, InjectedClassNameType, LabelStmt, MemberExpr, QualType, RecordType, TagType, TemplateSpecializationType, TemplateTypeParmType, TypedefType, UnresolvedUsingType> HasDeclarationSupportedTypes; /// \brief Converts a \c Matcher<T> to a matcher of desired type \c To by /// "adapting" a \c To into a \c T. /// /// The \c ArgumentAdapterT argument specifies how the adaptation is done. /// /// For example: /// \c ArgumentAdaptingMatcher<HasMatcher, T>(InnerMatcher); /// Given that \c InnerMatcher is of type \c Matcher<T>, this returns a matcher /// that is convertible into any matcher of type \c To by constructing /// \c HasMatcher<To, T>(InnerMatcher). /// /// If a matcher does not need knowledge about the inner type, prefer to use /// PolymorphicMatcherWithParam1. template <template <typename ToArg, typename FromArg> class ArgumentAdapterT, typename FromTypes = AdaptativeDefaultFromTypes, typename ToTypes = AdaptativeDefaultToTypes> struct ArgumentAdaptingMatcherFunc { template <typename T> class Adaptor { public: explicit Adaptor(const Matcher<T> &InnerMatcher) : InnerMatcher(InnerMatcher) {} typedef ToTypes ReturnTypes; template <typename To> operator Matcher<To>() const { return Matcher<To>(new ArgumentAdapterT<To, T>(InnerMatcher)); } private: const Matcher<T> InnerMatcher; }; template <typename T> static Adaptor<T> create(const Matcher<T> &InnerMatcher) { return Adaptor<T>(InnerMatcher); } template <typename T> Adaptor<T> operator()(const Matcher<T> &InnerMatcher) const { return create(InnerMatcher); } }; /// \brief A PolymorphicMatcherWithParamN<MatcherT, P1, ..., PN> object can be /// created from N parameters p1, ..., pN (of type P1, ..., PN) and /// used as a Matcher<T> where a MatcherT<T, P1, ..., PN>(p1, ..., pN) /// can be constructed. /// /// For example: /// - PolymorphicMatcherWithParam0<IsDefinitionMatcher>() /// creates an object that can be used as a Matcher<T> for any type T /// where an IsDefinitionMatcher<T>() can be constructed. /// - PolymorphicMatcherWithParam1<ValueEqualsMatcher, int>(42) /// creates an object that can be used as a Matcher<T> for any type T /// where a ValueEqualsMatcher<T, int>(42) can be constructed. template <template <typename T> class MatcherT, typename ReturnTypesF = void(AllNodeBaseTypes)> class PolymorphicMatcherWithParam0 { public: typedef typename ExtractFunctionArgMeta<ReturnTypesF>::type ReturnTypes; template <typename T> operator Matcher<T>() const { static_assert(TypeListContainsSuperOf<ReturnTypes, T>::value, "right polymorphic conversion"); return Matcher<T>(new MatcherT<T>()); } }; template <template <typename T, typename P1> class MatcherT, typename P1, typename ReturnTypesF = void(AllNodeBaseTypes)> class PolymorphicMatcherWithParam1 { public: explicit PolymorphicMatcherWithParam1(const P1 &Param1) : Param1(Param1) {} typedef typename ExtractFunctionArgMeta<ReturnTypesF>::type ReturnTypes; template <typename T> operator Matcher<T>() const { static_assert(TypeListContainsSuperOf<ReturnTypes, T>::value, "right polymorphic conversion"); return Matcher<T>(new MatcherT<T, P1>(Param1)); } private: const P1 Param1; }; template <template <typename T, typename P1, typename P2> class MatcherT, typename P1, typename P2, typename ReturnTypesF = void(AllNodeBaseTypes)> class PolymorphicMatcherWithParam2 { public: PolymorphicMatcherWithParam2(const P1 &Param1, const P2 &Param2) : Param1(Param1), Param2(Param2) {} typedef typename ExtractFunctionArgMeta<ReturnTypesF>::type ReturnTypes; template <typename T> operator Matcher<T>() const { static_assert(TypeListContainsSuperOf<ReturnTypes, T>::value, "right polymorphic conversion"); return Matcher<T>(new MatcherT<T, P1, P2>(Param1, Param2)); } private: const P1 Param1; const P2 Param2; }; /// \brief Matches any instance of the given NodeType. /// /// This is useful when a matcher syntactically requires a child matcher, /// but the context doesn't care. See for example: anything(). class TrueMatcher { public: typedef AllNodeBaseTypes ReturnTypes; template <typename T> operator Matcher<T>() const { return DynTypedMatcher::trueMatcher( ast_type_traits::ASTNodeKind::getFromNodeKind<T>()) .template unconditionalConvertTo<T>(); } }; /// \brief A Matcher that allows binding the node it matches to an id. /// /// BindableMatcher provides a \a bind() method that allows binding the /// matched node to an id if the match was successful. template <typename T> class BindableMatcher : public Matcher<T> { public: explicit BindableMatcher(const Matcher<T> &M) : Matcher<T>(M) {} explicit BindableMatcher(MatcherInterface<T> *Implementation) : Matcher<T>(Implementation) {} /// \brief Returns a matcher that will bind the matched node on a match. /// /// The returned matcher is equivalent to this matcher, but will /// bind the matched node on a match. Matcher<T> bind(StringRef ID) const { return DynTypedMatcher(*this) .tryBind(ID) ->template unconditionalConvertTo<T>(); } /// \brief Same as Matcher<T>'s conversion operator, but enables binding on /// the returned matcher. operator DynTypedMatcher() const { DynTypedMatcher Result = static_cast<const Matcher<T>&>(*this); Result.setAllowBind(true); return Result; } }; /// \brief Matches nodes of type T that have child nodes of type ChildT for /// which a specified child matcher matches. /// /// ChildT must be an AST base type. template <typename T, typename ChildT> class HasMatcher : public WrapperMatcherInterface<T> { static_assert(IsBaseType<ChildT>::value, "has only accepts base type matcher"); public: explicit HasMatcher(const Matcher<ChildT> &ChildMatcher) : HasMatcher::WrapperMatcherInterface(ChildMatcher) {} bool matches(const T &Node, ASTMatchFinder *Finder, BoundNodesTreeBuilder *Builder) const override { return Finder->matchesChildOf( Node, this->InnerMatcher, Builder, ASTMatchFinder::TK_IgnoreImplicitCastsAndParentheses, ASTMatchFinder::BK_First); } }; /// \brief Matches nodes of type T that have child nodes of type ChildT for /// which a specified child matcher matches. ChildT must be an AST base /// type. /// As opposed to the HasMatcher, the ForEachMatcher will produce a match /// for each child that matches. template <typename T, typename ChildT> class ForEachMatcher : public WrapperMatcherInterface<T> { static_assert(IsBaseType<ChildT>::value, "for each only accepts base type matcher"); public: explicit ForEachMatcher(const Matcher<ChildT> &ChildMatcher) : ForEachMatcher::WrapperMatcherInterface(ChildMatcher) {} bool matches(const T& Node, ASTMatchFinder* Finder, BoundNodesTreeBuilder* Builder) const override { return Finder->matchesChildOf( Node, this->InnerMatcher, Builder, ASTMatchFinder::TK_IgnoreImplicitCastsAndParentheses, ASTMatchFinder::BK_All); } }; /// \brief VariadicOperatorMatcher related types. /// @{ /// \brief Polymorphic matcher object that uses a \c /// DynTypedMatcher::VariadicOperator operator. /// /// Input matchers can have any type (including other polymorphic matcher /// types), and the actual Matcher<T> is generated on demand with an implicit /// coversion operator. template <typename... Ps> class VariadicOperatorMatcher { public: VariadicOperatorMatcher(DynTypedMatcher::VariadicOperator Op, Ps &&... Params) : Op(Op), Params(std::forward<Ps>(Params)...) {} template <typename T> operator Matcher<T>() const { return DynTypedMatcher::constructVariadic( Op, getMatchers<T>(llvm::index_sequence_for<Ps...>())) .template unconditionalConvertTo<T>(); } private: // Helper method to unpack the tuple into a vector. template <typename T, std::size_t... Is> std::vector<DynTypedMatcher> getMatchers(llvm::index_sequence<Is...>) const { return {Matcher<T>(std::get<Is>(Params))...}; } const DynTypedMatcher::VariadicOperator Op; std::tuple<Ps...> Params; }; /// \brief Overloaded function object to generate VariadicOperatorMatcher /// objects from arbitrary matchers. template <unsigned MinCount, unsigned MaxCount> struct VariadicOperatorMatcherFunc { DynTypedMatcher::VariadicOperator Op; template <typename... Ms> VariadicOperatorMatcher<Ms...> operator()(Ms &&... Ps) const { static_assert(MinCount <= sizeof...(Ms) && sizeof...(Ms) <= MaxCount, "invalid number of parameters for variadic matcher"); return VariadicOperatorMatcher<Ms...>(Op, std::forward<Ms>(Ps)...); } }; /// @} template <typename T> inline Matcher<T> DynTypedMatcher::unconditionalConvertTo() const { return Matcher<T>(*this); } /// \brief Creates a Matcher<T> that matches if all inner matchers match. template<typename T> BindableMatcher<T> makeAllOfComposite( ArrayRef<const Matcher<T> *> InnerMatchers) { // For the size() == 0 case, we return a "true" matcher. if (InnerMatchers.size() == 0) { return BindableMatcher<T>(TrueMatcher()); } // For the size() == 1 case, we simply return that one matcher. // No need to wrap it in a variadic operation. if (InnerMatchers.size() == 1) { return BindableMatcher<T>(*InnerMatchers[0]); } typedef llvm::pointee_iterator<const Matcher<T> *const *> PI; std::vector<DynTypedMatcher> DynMatchers(PI(InnerMatchers.begin()), PI(InnerMatchers.end())); return BindableMatcher<T>( DynTypedMatcher::constructVariadic(DynTypedMatcher::VO_AllOf, std::move(DynMatchers)) .template unconditionalConvertTo<T>()); } /// \brief Creates a Matcher<T> that matches if /// T is dyn_cast'able into InnerT and all inner matchers match. /// /// Returns BindableMatcher, as matchers that use dyn_cast have /// the same object both to match on and to run submatchers on, /// so there is no ambiguity with what gets bound. template<typename T, typename InnerT> BindableMatcher<T> makeDynCastAllOfComposite( ArrayRef<const Matcher<InnerT> *> InnerMatchers) { return BindableMatcher<T>( makeAllOfComposite(InnerMatchers).template dynCastTo<T>()); } /// \brief Matches nodes of type T that have at least one descendant node of /// type DescendantT for which the given inner matcher matches. /// /// DescendantT must be an AST base type. template <typename T, typename DescendantT> class HasDescendantMatcher : public WrapperMatcherInterface<T> { static_assert(IsBaseType<DescendantT>::value, "has descendant only accepts base type matcher"); public: explicit HasDescendantMatcher(const Matcher<DescendantT> &DescendantMatcher) : HasDescendantMatcher::WrapperMatcherInterface(DescendantMatcher) {} bool matches(const T &Node, ASTMatchFinder *Finder, BoundNodesTreeBuilder *Builder) const override { return Finder->matchesDescendantOf(Node, this->InnerMatcher, Builder, ASTMatchFinder::BK_First); } }; /// \brief Matches nodes of type \c T that have a parent node of type \c ParentT /// for which the given inner matcher matches. /// /// \c ParentT must be an AST base type. template <typename T, typename ParentT> class HasParentMatcher : public WrapperMatcherInterface<T> { static_assert(IsBaseType<ParentT>::value, "has parent only accepts base type matcher"); public: explicit HasParentMatcher(const Matcher<ParentT> &ParentMatcher) : HasParentMatcher::WrapperMatcherInterface(ParentMatcher) {} bool matches(const T &Node, ASTMatchFinder *Finder, BoundNodesTreeBuilder *Builder) const override { return Finder->matchesAncestorOf(Node, this->InnerMatcher, Builder, ASTMatchFinder::AMM_ParentOnly); } }; /// \brief Matches nodes of type \c T that have at least one ancestor node of /// type \c AncestorT for which the given inner matcher matches. /// /// \c AncestorT must be an AST base type. template <typename T, typename AncestorT> class HasAncestorMatcher : public WrapperMatcherInterface<T> { static_assert(IsBaseType<AncestorT>::value, "has ancestor only accepts base type matcher"); public: explicit HasAncestorMatcher(const Matcher<AncestorT> &AncestorMatcher) : HasAncestorMatcher::WrapperMatcherInterface(AncestorMatcher) {} bool matches(const T &Node, ASTMatchFinder *Finder, BoundNodesTreeBuilder *Builder) const override { return Finder->matchesAncestorOf(Node, this->InnerMatcher, Builder, ASTMatchFinder::AMM_All); } }; /// \brief Matches nodes of type T that have at least one descendant node of /// type DescendantT for which the given inner matcher matches. /// /// DescendantT must be an AST base type. /// As opposed to HasDescendantMatcher, ForEachDescendantMatcher will match /// for each descendant node that matches instead of only for the first. template <typename T, typename DescendantT> class ForEachDescendantMatcher : public WrapperMatcherInterface<T> { static_assert(IsBaseType<DescendantT>::value, "for each descendant only accepts base type matcher"); public: explicit ForEachDescendantMatcher( const Matcher<DescendantT> &DescendantMatcher) : ForEachDescendantMatcher::WrapperMatcherInterface(DescendantMatcher) {} bool matches(const T &Node, ASTMatchFinder *Finder, BoundNodesTreeBuilder *Builder) const override { return Finder->matchesDescendantOf(Node, this->InnerMatcher, Builder, ASTMatchFinder::BK_All); } }; /// \brief Matches on nodes that have a getValue() method if getValue() equals /// the value the ValueEqualsMatcher was constructed with. template <typename T, typename ValueT> class ValueEqualsMatcher : public SingleNodeMatcherInterface<T> { static_assert(std::is_base_of<CharacterLiteral, T>::value || std::is_base_of<CXXBoolLiteralExpr, T>::value || std::is_base_of<FloatingLiteral, T>::value || std::is_base_of<IntegerLiteral, T>::value, "the node must have a getValue method"); public: explicit ValueEqualsMatcher(const ValueT &ExpectedValue) : ExpectedValue(ExpectedValue) {} bool matchesNode(const T &Node) const override { return Node.getValue() == ExpectedValue; } private: const ValueT ExpectedValue; }; /// \brief Template specializations to easily write matchers for floating point /// literals. template <> inline bool ValueEqualsMatcher<FloatingLiteral, double>::matchesNode( const FloatingLiteral &Node) const { if ((&Node.getSemantics()) == &llvm::APFloat::IEEEsingle) return Node.getValue().convertToFloat() == ExpectedValue; if ((&Node.getSemantics()) == &llvm::APFloat::IEEEdouble) return Node.getValue().convertToDouble() == ExpectedValue; return false; } template <> inline bool ValueEqualsMatcher<FloatingLiteral, float>::matchesNode( const FloatingLiteral &Node) const { if ((&Node.getSemantics()) == &llvm::APFloat::IEEEsingle) return Node.getValue().convertToFloat() == ExpectedValue; if ((&Node.getSemantics()) == &llvm::APFloat::IEEEdouble) return Node.getValue().convertToDouble() == ExpectedValue; return false; } template <> inline bool ValueEqualsMatcher<FloatingLiteral, llvm::APFloat>::matchesNode( const FloatingLiteral &Node) const { return ExpectedValue.compare(Node.getValue()) == llvm::APFloat::cmpEqual; } /// \brief A VariadicDynCastAllOfMatcher<SourceT, TargetT> object is a /// variadic functor that takes a number of Matcher<TargetT> and returns a /// Matcher<SourceT> that matches TargetT nodes that are matched by all of the /// given matchers, if SourceT can be dynamically casted into TargetT. /// /// For example: /// const VariadicDynCastAllOfMatcher< /// Decl, CXXRecordDecl> record; /// Creates a functor record(...) that creates a Matcher<Decl> given /// a variable number of arguments of type Matcher<CXXRecordDecl>. /// The returned matcher matches if the given Decl can by dynamically /// casted to CXXRecordDecl and all given matchers match. template <typename SourceT, typename TargetT> class VariadicDynCastAllOfMatcher : public llvm::VariadicFunction< BindableMatcher<SourceT>, Matcher<TargetT>, makeDynCastAllOfComposite<SourceT, TargetT> > { public: VariadicDynCastAllOfMatcher() {} }; /// \brief A \c VariadicAllOfMatcher<T> object is a variadic functor that takes /// a number of \c Matcher<T> and returns a \c Matcher<T> that matches \c T /// nodes that are matched by all of the given matchers. /// /// For example: /// const VariadicAllOfMatcher<NestedNameSpecifier> nestedNameSpecifier; /// Creates a functor nestedNameSpecifier(...) that creates a /// \c Matcher<NestedNameSpecifier> given a variable number of arguments of type /// \c Matcher<NestedNameSpecifier>. /// The returned matcher matches if all given matchers match. template <typename T> class VariadicAllOfMatcher : public llvm::VariadicFunction< BindableMatcher<T>, Matcher<T>, makeAllOfComposite<T> > { public: VariadicAllOfMatcher() {} }; /// \brief Matches nodes of type \c TLoc for which the inner /// \c Matcher<T> matches. template <typename TLoc, typename T> class LocMatcher : public WrapperMatcherInterface<TLoc> { public: explicit LocMatcher(const Matcher<T> &InnerMatcher) : LocMatcher::WrapperMatcherInterface(InnerMatcher) {} bool matches(const TLoc &Node, ASTMatchFinder *Finder, BoundNodesTreeBuilder *Builder) const override { if (!Node) return false; return this->InnerMatcher.matches(extract(Node), Finder, Builder); } private: static ast_type_traits::DynTypedNode extract(const NestedNameSpecifierLoc &Loc) { return ast_type_traits::DynTypedNode::create(*Loc.getNestedNameSpecifier()); } }; /// \brief Matches \c TypeLocs based on an inner matcher matching a certain /// \c QualType. /// /// Used to implement the \c loc() matcher. class TypeLocTypeMatcher : public WrapperMatcherInterface<TypeLoc> { public: explicit TypeLocTypeMatcher(const Matcher<QualType> &InnerMatcher) : TypeLocTypeMatcher::WrapperMatcherInterface(InnerMatcher) {} bool matches(const TypeLoc &Node, ASTMatchFinder *Finder, BoundNodesTreeBuilder *Builder) const override { if (!Node) return false; return this->InnerMatcher.matches( ast_type_traits::DynTypedNode::create(Node.getType()), Finder, Builder); } }; /// \brief Matches nodes of type \c T for which the inner matcher matches on a /// another node of type \c T that can be reached using a given traverse /// function. template <typename T> class TypeTraverseMatcher : public WrapperMatcherInterface<T> { public: explicit TypeTraverseMatcher(const Matcher<QualType> &InnerMatcher, QualType (T::*TraverseFunction)() const) : TypeTraverseMatcher::WrapperMatcherInterface(InnerMatcher), TraverseFunction(TraverseFunction) {} bool matches(const T &Node, ASTMatchFinder *Finder, BoundNodesTreeBuilder *Builder) const override { QualType NextNode = (Node.*TraverseFunction)(); if (NextNode.isNull()) return false; return this->InnerMatcher.matches( ast_type_traits::DynTypedNode::create(NextNode), Finder, Builder); } private: QualType (T::*TraverseFunction)() const; }; /// \brief Matches nodes of type \c T in a ..Loc hierarchy, for which the inner /// matcher matches on a another node of type \c T that can be reached using a /// given traverse function. template <typename T> class TypeLocTraverseMatcher : public WrapperMatcherInterface<T> { public: explicit TypeLocTraverseMatcher(const Matcher<TypeLoc> &InnerMatcher, TypeLoc (T::*TraverseFunction)() const) : TypeLocTraverseMatcher::WrapperMatcherInterface(InnerMatcher), TraverseFunction(TraverseFunction) {} bool matches(const T &Node, ASTMatchFinder *Finder, BoundNodesTreeBuilder *Builder) const override { TypeLoc NextNode = (Node.*TraverseFunction)(); if (!NextNode) return false; return this->InnerMatcher.matches( ast_type_traits::DynTypedNode::create(NextNode), Finder, Builder); } private: TypeLoc (T::*TraverseFunction)() const; }; /// \brief Converts a \c Matcher<InnerT> to a \c Matcher<OuterT>, where /// \c OuterT is any type that is supported by \c Getter. /// /// \code Getter<OuterT>::value() \endcode returns a /// \code InnerTBase (OuterT::*)() \endcode, which is used to adapt a \c OuterT /// object into a \c InnerT template <typename InnerTBase, template <typename OuterT> class Getter, template <typename OuterT> class MatcherImpl, typename ReturnTypesF> class TypeTraversePolymorphicMatcher { private: typedef TypeTraversePolymorphicMatcher<InnerTBase, Getter, MatcherImpl, ReturnTypesF> Self; static Self create(ArrayRef<const Matcher<InnerTBase> *> InnerMatchers); public: typedef typename ExtractFunctionArgMeta<ReturnTypesF>::type ReturnTypes; explicit TypeTraversePolymorphicMatcher( ArrayRef<const Matcher<InnerTBase> *> InnerMatchers) : InnerMatcher(makeAllOfComposite(InnerMatchers)) {} template <typename OuterT> operator Matcher<OuterT>() const { return Matcher<OuterT>( new MatcherImpl<OuterT>(InnerMatcher, Getter<OuterT>::value())); } struct Func : public llvm::VariadicFunction<Self, Matcher<InnerTBase>, &Self::create> { Func() {} }; private: const Matcher<InnerTBase> InnerMatcher; }; /// \brief A simple memoizer of T(*)() functions. /// /// It will call the passed 'Func' template parameter at most once. /// Used to support AST_MATCHER_FUNCTION() macro. template <typename Matcher, Matcher (*Func)()> class MemoizedMatcher { struct Wrapper { Wrapper() : M(Func()) {} Matcher M; }; public: static const Matcher &getInstance() { static llvm::ManagedStatic<Wrapper> Instance; return Instance->M; } }; // Define the create() method out of line to silence a GCC warning about // the struct "Func" having greater visibility than its base, which comes from // using the flag -fvisibility-inlines-hidden. template <typename InnerTBase, template <typename OuterT> class Getter, template <typename OuterT> class MatcherImpl, typename ReturnTypesF> TypeTraversePolymorphicMatcher<InnerTBase, Getter, MatcherImpl, ReturnTypesF> TypeTraversePolymorphicMatcher< InnerTBase, Getter, MatcherImpl, ReturnTypesF>::create(ArrayRef<const Matcher<InnerTBase> *> InnerMatchers) { return Self(InnerMatchers); } // FIXME: unify ClassTemplateSpecializationDecl and TemplateSpecializationType's // APIs for accessing the template argument list. inline ArrayRef<TemplateArgument> getTemplateSpecializationArgs(const ClassTemplateSpecializationDecl &D) { return D.getTemplateArgs().asArray(); } inline ArrayRef<TemplateArgument> getTemplateSpecializationArgs(const TemplateSpecializationType &T) { return llvm::makeArrayRef(T.getArgs(), T.getNumArgs()); } struct NotEqualsBoundNodePredicate { bool operator()(const internal::BoundNodesMap &Nodes) const { return Nodes.getNode(ID) != Node; } std::string ID; ast_type_traits::DynTypedNode Node; }; } // end namespace internal } // end namespace ast_matchers } // end namespace clang #endif
0
repos/DirectXShaderCompiler/tools/clang/include/clang
repos/DirectXShaderCompiler/tools/clang/include/clang/ASTMatchers/ASTMatchFinder.h
//===--- ASTMatchFinder.h - Structural query framework ----------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // Provides a way to construct an ASTConsumer that runs given matchers // over the AST and invokes a given callback on every match. // // The general idea is to construct a matcher expression that describes a // subtree match on the AST. Next, a callback that is executed every time the // expression matches is registered, and the matcher is run over the AST of // some code. Matched subexpressions can be bound to string IDs and easily // be accessed from the registered callback. The callback can than use the // AST nodes that the subexpressions matched on to output information about // the match or construct changes that can be applied to the code. // // Example: // class HandleMatch : public MatchFinder::MatchCallback { // public: // virtual void Run(const MatchFinder::MatchResult &Result) { // const CXXRecordDecl *Class = // Result.Nodes.GetDeclAs<CXXRecordDecl>("id"); // ... // } // }; // // int main(int argc, char **argv) { // ClangTool Tool(argc, argv); // MatchFinder finder; // finder.AddMatcher(Id("id", record(hasName("::a_namespace::AClass"))), // new HandleMatch); // return Tool.Run(newFrontendActionFactory(&finder)); // } // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_ASTMATCHERS_ASTMATCHFINDER_H #define LLVM_CLANG_ASTMATCHERS_ASTMATCHFINDER_H #include "clang/ASTMatchers/ASTMatchers.h" #include "llvm/ADT/StringMap.h" #include "llvm/Support/Timer.h" namespace clang { namespace ast_matchers { /// \brief A class to allow finding matches over the Clang AST. /// /// After creation, you can add multiple matchers to the MatchFinder via /// calls to addMatcher(...). /// /// Once all matchers are added, newASTConsumer() returns an ASTConsumer /// that will trigger the callbacks specified via addMatcher(...) when a match /// is found. /// /// The order of matches is guaranteed to be equivalent to doing a pre-order /// traversal on the AST, and applying the matchers in the order in which they /// were added to the MatchFinder. /// /// See ASTMatchers.h for more information about how to create matchers. /// /// Not intended to be subclassed. class MatchFinder { public: /// \brief Contains all information for a given match. /// /// Every time a match is found, the MatchFinder will invoke the registered /// MatchCallback with a MatchResult containing information about the match. struct MatchResult { MatchResult(const BoundNodes &Nodes, clang::ASTContext *Context); /// \brief Contains the nodes bound on the current match. /// /// This allows user code to easily extract matched AST nodes. const BoundNodes Nodes; /// \brief Utilities for interpreting the matched AST structures. /// @{ clang::ASTContext * const Context; clang::SourceManager * const SourceManager; /// @} }; /// \brief Called when the Match registered for it was successfully found /// in the AST. class MatchCallback { public: virtual ~MatchCallback(); /// \brief Called on every match by the \c MatchFinder. virtual void run(const MatchResult &Result) = 0; /// \brief Called at the start of each translation unit. /// /// Optionally override to do per translation unit tasks. virtual void onStartOfTranslationUnit() {} /// \brief Called at the end of each translation unit. /// /// Optionally override to do per translation unit tasks. virtual void onEndOfTranslationUnit() {} /// \brief An id used to group the matchers. /// /// This id is used, for example, for the profiling output. /// It defaults to "<unknown>". virtual StringRef getID() const; }; /// \brief Called when parsing is finished. Intended for testing only. class ParsingDoneTestCallback { public: virtual ~ParsingDoneTestCallback(); virtual void run() = 0; }; struct MatchFinderOptions { struct Profiling { Profiling(llvm::StringMap<llvm::TimeRecord> &Records) : Records(Records) {} /// \brief Per bucket timing information. llvm::StringMap<llvm::TimeRecord> &Records; }; /// \brief Enables per-check timers. /// /// It prints a report after match. llvm::Optional<Profiling> CheckProfiling; }; MatchFinder(MatchFinderOptions Options = MatchFinderOptions()); ~MatchFinder(); /// \brief Adds a matcher to execute when running over the AST. /// /// Calls 'Action' with the BoundNodes on every match. /// Adding more than one 'NodeMatch' allows finding different matches in a /// single pass over the AST. /// /// Does not take ownership of 'Action'. /// @{ void addMatcher(const DeclarationMatcher &NodeMatch, MatchCallback *Action); void addMatcher(const TypeMatcher &NodeMatch, MatchCallback *Action); void addMatcher(const StatementMatcher &NodeMatch, MatchCallback *Action); void addMatcher(const NestedNameSpecifierMatcher &NodeMatch, MatchCallback *Action); void addMatcher(const NestedNameSpecifierLocMatcher &NodeMatch, MatchCallback *Action); void addMatcher(const TypeLocMatcher &NodeMatch, MatchCallback *Action); /// @} /// \brief Adds a matcher to execute when running over the AST. /// /// This is similar to \c addMatcher(), but it uses the dynamic interface. It /// is more flexible, but the lost type information enables a caller to pass /// a matcher that cannot match anything. /// /// \returns \c true if the matcher is a valid top-level matcher, \c false /// otherwise. bool addDynamicMatcher(const internal::DynTypedMatcher &NodeMatch, MatchCallback *Action); /// \brief Creates a clang ASTConsumer that finds all matches. std::unique_ptr<clang::ASTConsumer> newASTConsumer(); /// \brief Calls the registered callbacks on all matches on the given \p Node. /// /// Note that there can be multiple matches on a single node, for /// example when using decl(forEachDescendant(stmt())). /// /// @{ template <typename T> void match(const T &Node, ASTContext &Context) { match(clang::ast_type_traits::DynTypedNode::create(Node), Context); } void match(const clang::ast_type_traits::DynTypedNode &Node, ASTContext &Context); /// @} /// \brief Finds all matches in the given AST. void matchAST(ASTContext &Context); /// \brief Registers a callback to notify the end of parsing. /// /// The provided closure is called after parsing is done, before the AST is /// traversed. Useful for benchmarking. /// Each call to FindAll(...) will call the closure once. void registerTestCallbackAfterParsing(ParsingDoneTestCallback *ParsingDone); /// \brief For each \c Matcher<> a \c MatchCallback that will be called /// when it matches. struct MatchersByType { std::vector<std::pair<internal::DynTypedMatcher, MatchCallback *>> DeclOrStmt; std::vector<std::pair<TypeMatcher, MatchCallback *>> Type; std::vector<std::pair<NestedNameSpecifierMatcher, MatchCallback *>> NestedNameSpecifier; std::vector<std::pair<NestedNameSpecifierLocMatcher, MatchCallback *>> NestedNameSpecifierLoc; std::vector<std::pair<TypeLocMatcher, MatchCallback *>> TypeLoc; /// \brief All the callbacks in one container to simplify iteration. std::vector<MatchCallback *> AllCallbacks; }; private: MatchersByType Matchers; MatchFinderOptions Options; /// \brief Called when parsing is done. ParsingDoneTestCallback *ParsingDone; }; /// \brief Returns the results of matching \p Matcher on \p Node. /// /// Collects the \c BoundNodes of all callback invocations when matching /// \p Matcher on \p Node and returns the collected results. /// /// Multiple results occur when using matchers like \c forEachDescendant, /// which generate a result for each sub-match. /// /// \see selectFirst /// @{ template <typename MatcherT, typename NodeT> SmallVector<BoundNodes, 1> match(MatcherT Matcher, const NodeT &Node, ASTContext &Context); template <typename MatcherT> SmallVector<BoundNodes, 1> match(MatcherT Matcher, const ast_type_traits::DynTypedNode &Node, ASTContext &Context); /// @} /// \brief Returns the first result of type \c NodeT bound to \p BoundTo. /// /// Returns \c NULL if there is no match, or if the matching node cannot be /// casted to \c NodeT. /// /// This is useful in combanation with \c match(): /// \code /// const Decl *D = selectFirst<Decl>("id", match(Matcher.bind("id"), /// Node, Context)); /// \endcode template <typename NodeT> const NodeT * selectFirst(StringRef BoundTo, const SmallVectorImpl<BoundNodes> &Results) { for (const BoundNodes &N : Results) { if (const NodeT *Node = N.getNodeAs<NodeT>(BoundTo)) return Node; } return nullptr; } namespace internal { class CollectMatchesCallback : public MatchFinder::MatchCallback { public: void run(const MatchFinder::MatchResult &Result) override { Nodes.push_back(Result.Nodes); } SmallVector<BoundNodes, 1> Nodes; }; } template <typename MatcherT> SmallVector<BoundNodes, 1> match(MatcherT Matcher, const ast_type_traits::DynTypedNode &Node, ASTContext &Context) { internal::CollectMatchesCallback Callback; MatchFinder Finder; Finder.addMatcher(Matcher, &Callback); Finder.match(Node, Context); return std::move(Callback.Nodes); } template <typename MatcherT, typename NodeT> SmallVector<BoundNodes, 1> match(MatcherT Matcher, const NodeT &Node, ASTContext &Context) { return match(Matcher, ast_type_traits::DynTypedNode::create(Node), Context); } } // end namespace ast_matchers } // end namespace clang #endif
0
repos/DirectXShaderCompiler/tools/clang/include/clang
repos/DirectXShaderCompiler/tools/clang/include/clang/ASTMatchers/ASTMatchers.h
//===--- ASTMatchers.h - Structural query framework -------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements matchers to be used together with the MatchFinder to // match AST nodes. // // Matchers are created by generator functions, which can be combined in // a functional in-language DSL to express queries over the C++ AST. // // For example, to match a class with a certain name, one would call: // recordDecl(hasName("MyClass")) // which returns a matcher that can be used to find all AST nodes that declare // a class named 'MyClass'. // // For more complicated match expressions we're often interested in accessing // multiple parts of the matched AST nodes once a match is found. In that case, // use the id(...) matcher around the match expressions that match the nodes // you want to access. // // For example, when we're interested in child classes of a certain class, we // would write: // recordDecl(hasName("MyClass"), hasChild(id("child", recordDecl()))) // When the match is found via the MatchFinder, a user provided callback will // be called with a BoundNodes instance that contains a mapping from the // strings that we provided for the id(...) calls to the nodes that were // matched. // In the given example, each time our matcher finds a match we get a callback // where "child" is bound to the CXXRecordDecl node of the matching child // class declaration. // // See ASTMatchersInternal.h for a more in-depth explanation of the // implementation details of the matcher framework. // // See ASTMatchFinder.h for how to use the generated matchers to run over // an AST. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_ASTMATCHERS_ASTMATCHERS_H #define LLVM_CLANG_ASTMATCHERS_ASTMATCHERS_H #include "clang/AST/ASTContext.h" #include "clang/AST/DeclFriend.h" #include "clang/AST/DeclObjC.h" #include "clang/AST/DeclTemplate.h" #include "clang/ASTMatchers/ASTMatchersInternal.h" #include "clang/ASTMatchers/ASTMatchersMacros.h" #include "llvm/ADT/Twine.h" #include "llvm/Support/Regex.h" #include <iterator> namespace clang { namespace ast_matchers { /// \brief Maps string IDs to AST nodes matched by parts of a matcher. /// /// The bound nodes are generated by calling \c bind("id") on the node matchers /// of the nodes we want to access later. /// /// The instances of BoundNodes are created by \c MatchFinder when the user's /// callbacks are executed every time a match is found. class BoundNodes { public: /// \brief Returns the AST node bound to \c ID. /// /// Returns NULL if there was no node bound to \c ID or if there is a node but /// it cannot be converted to the specified type. template <typename T> const T *getNodeAs(StringRef ID) const { return MyBoundNodes.getNodeAs<T>(ID); } /// \brief Deprecated. Please use \c getNodeAs instead. /// @{ template <typename T> const T *getDeclAs(StringRef ID) const { return getNodeAs<T>(ID); } template <typename T> const T *getStmtAs(StringRef ID) const { return getNodeAs<T>(ID); } /// @} /// \brief Type of mapping from binding identifiers to bound nodes. This type /// is an associative container with a key type of \c std::string and a value /// type of \c clang::ast_type_traits::DynTypedNode typedef internal::BoundNodesMap::IDToNodeMap IDToNodeMap; /// \brief Retrieve mapping from binding identifiers to bound nodes. const IDToNodeMap &getMap() const { return MyBoundNodes.getMap(); } private: /// \brief Create BoundNodes from a pre-filled map of bindings. BoundNodes(internal::BoundNodesMap &MyBoundNodes) : MyBoundNodes(MyBoundNodes) {} internal::BoundNodesMap MyBoundNodes; friend class internal::BoundNodesTreeBuilder; }; /// \brief If the provided matcher matches a node, binds the node to \c ID. /// /// FIXME: Do we want to support this now that we have bind()? template <typename T> internal::Matcher<T> id(StringRef ID, const internal::BindableMatcher<T> &InnerMatcher) { return InnerMatcher.bind(ID); } /// \brief Types of matchers for the top-level classes in the AST class /// hierarchy. /// @{ typedef internal::Matcher<Decl> DeclarationMatcher; typedef internal::Matcher<Stmt> StatementMatcher; typedef internal::Matcher<QualType> TypeMatcher; typedef internal::Matcher<TypeLoc> TypeLocMatcher; typedef internal::Matcher<NestedNameSpecifier> NestedNameSpecifierMatcher; typedef internal::Matcher<NestedNameSpecifierLoc> NestedNameSpecifierLocMatcher; /// @} /// \brief Matches any node. /// /// Useful when another matcher requires a child matcher, but there's no /// additional constraint. This will often be used with an explicit conversion /// to an \c internal::Matcher<> type such as \c TypeMatcher. /// /// Example: \c DeclarationMatcher(anything()) matches all declarations, e.g., /// \code /// "int* p" and "void f()" in /// int* p; /// void f(); /// \endcode /// /// Usable as: Any Matcher inline internal::TrueMatcher anything() { return internal::TrueMatcher(); } /// \brief Matches the top declaration context. /// /// Given /// \code /// int X; /// namespace NS { /// int Y; /// } // namespace NS /// \endcode /// decl(hasDeclContext(translationUnitDecl())) /// matches "int X", but not "int Y". const internal::VariadicDynCastAllOfMatcher<Decl, TranslationUnitDecl> translationUnitDecl; /// \brief Matches typedef declarations. /// /// Given /// \code /// typedef int X; /// \endcode /// typedefDecl() /// matches "typedef int X" const internal::VariadicDynCastAllOfMatcher<Decl, TypedefDecl> typedefDecl; /// \brief Matches AST nodes that were expanded within the main-file. /// /// Example matches X but not Y (matcher = recordDecl(isExpansionInMainFile()) /// \code /// #include <Y.h> /// class X {}; /// \endcode /// Y.h: /// \code /// class Y {}; /// \endcode /// /// Usable as: Matcher<Decl>, Matcher<Stmt>, Matcher<TypeLoc> AST_POLYMORPHIC_MATCHER(isExpansionInMainFile, AST_POLYMORPHIC_SUPPORTED_TYPES(Decl, Stmt, TypeLoc)) { auto &SourceManager = Finder->getASTContext().getSourceManager(); return SourceManager.isInMainFile( SourceManager.getExpansionLoc(Node.getLocStart())); } /// \brief Matches AST nodes that were expanded within system-header-files. /// /// Example matches Y but not X /// (matcher = recordDecl(isExpansionInSystemHeader()) /// \code /// #include <SystemHeader.h> /// class X {}; /// \endcode /// SystemHeader.h: /// \code /// class Y {}; /// \endcode /// /// Usable as: Matcher<Decl>, Matcher<Stmt>, Matcher<TypeLoc> AST_POLYMORPHIC_MATCHER(isExpansionInSystemHeader, AST_POLYMORPHIC_SUPPORTED_TYPES(Decl, Stmt, TypeLoc)) { auto &SourceManager = Finder->getASTContext().getSourceManager(); auto ExpansionLoc = SourceManager.getExpansionLoc(Node.getLocStart()); if (ExpansionLoc.isInvalid()) { return false; } return SourceManager.isInSystemHeader(ExpansionLoc); } /// \brief Matches AST nodes that were expanded within files whose name is /// partially matching a given regex. /// /// Example matches Y but not X /// (matcher = recordDecl(isExpansionInFileMatching("AST.*")) /// \code /// #include "ASTMatcher.h" /// class X {}; /// \endcode /// ASTMatcher.h: /// \code /// class Y {}; /// \endcode /// /// Usable as: Matcher<Decl>, Matcher<Stmt>, Matcher<TypeLoc> AST_POLYMORPHIC_MATCHER_P(isExpansionInFileMatching, AST_POLYMORPHIC_SUPPORTED_TYPES(Decl, Stmt, TypeLoc), std::string, RegExp) { auto &SourceManager = Finder->getASTContext().getSourceManager(); auto ExpansionLoc = SourceManager.getExpansionLoc(Node.getLocStart()); if (ExpansionLoc.isInvalid()) { return false; } auto FileEntry = SourceManager.getFileEntryForID(SourceManager.getFileID(ExpansionLoc)); if (!FileEntry) { return false; } auto Filename = FileEntry->getName(); llvm::Regex RE(RegExp); return RE.match(Filename); } /// \brief Matches declarations. /// /// Examples matches \c X, \c C, and the friend declaration inside \c C; /// \code /// void X(); /// class C { /// friend X; /// }; /// \endcode const internal::VariadicAllOfMatcher<Decl> decl; /// \brief Matches a declaration of a linkage specification. /// /// Given /// \code /// extern "C" {} /// \endcode /// linkageSpecDecl() /// matches "extern "C" {}" const internal::VariadicDynCastAllOfMatcher<Decl, LinkageSpecDecl> linkageSpecDecl; /// \brief Matches a declaration of anything that could have a name. /// /// Example matches \c X, \c S, the anonymous union type, \c i, and \c U; /// \code /// typedef int X; /// struct S { /// union { /// int i; /// } U; /// }; /// \endcode const internal::VariadicDynCastAllOfMatcher<Decl, NamedDecl> namedDecl; /// \brief Matches a declaration of a namespace. /// /// Given /// \code /// namespace {} /// namespace test {} /// \endcode /// namespaceDecl() /// matches "namespace {}" and "namespace test {}" const internal::VariadicDynCastAllOfMatcher<Decl, NamespaceDecl> namespaceDecl; /// \brief Matches C++ class declarations. /// /// Example matches \c X, \c Z /// \code /// class X; /// template<class T> class Z {}; /// \endcode const internal::VariadicDynCastAllOfMatcher< Decl, CXXRecordDecl> recordDecl; /// \brief Matches C++ class template declarations. /// /// Example matches \c Z /// \code /// template<class T> class Z {}; /// \endcode const internal::VariadicDynCastAllOfMatcher< Decl, ClassTemplateDecl> classTemplateDecl; /// \brief Matches C++ class template specializations. /// /// Given /// \code /// template<typename T> class A {}; /// template<> class A<double> {}; /// A<int> a; /// \endcode /// classTemplateSpecializationDecl() /// matches the specializations \c A<int> and \c A<double> const internal::VariadicDynCastAllOfMatcher< Decl, ClassTemplateSpecializationDecl> classTemplateSpecializationDecl; /// \brief Matches declarator declarations (field, variable, function /// and non-type template parameter declarations). /// /// Given /// \code /// class X { int y; }; /// \endcode /// declaratorDecl() /// matches \c int y. const internal::VariadicDynCastAllOfMatcher<Decl, DeclaratorDecl> declaratorDecl; /// \brief Matches parameter variable declarations. /// /// Given /// \code /// void f(int x); /// \endcode /// parmVarDecl() /// matches \c int x. const internal::VariadicDynCastAllOfMatcher<Decl, ParmVarDecl> parmVarDecl; /// \brief Matches C++ access specifier declarations. /// /// Given /// \code /// class C { /// public: /// int a; /// }; /// \endcode /// accessSpecDecl() /// matches 'public:' const internal::VariadicDynCastAllOfMatcher< Decl, AccessSpecDecl> accessSpecDecl; /// \brief Matches constructor initializers. /// /// Examples matches \c i(42). /// \code /// class C { /// C() : i(42) {} /// int i; /// }; /// \endcode const internal::VariadicAllOfMatcher<CXXCtorInitializer> ctorInitializer; /// \brief Matches template arguments. /// /// Given /// \code /// template <typename T> struct C {}; /// C<int> c; /// \endcode /// templateArgument() /// matches 'int' in C<int>. const internal::VariadicAllOfMatcher<TemplateArgument> templateArgument; /// \brief Matches public C++ declarations. /// /// Given /// \code /// class C { /// public: int a; /// protected: int b; /// private: int c; /// }; /// \endcode /// fieldDecl(isPublic()) /// matches 'int a;' AST_MATCHER(Decl, isPublic) { return Node.getAccess() == AS_public; } /// \brief Matches protected C++ declarations. /// /// Given /// \code /// class C { /// public: int a; /// protected: int b; /// private: int c; /// }; /// \endcode /// fieldDecl(isProtected()) /// matches 'int b;' AST_MATCHER(Decl, isProtected) { return Node.getAccess() == AS_protected; } /// \brief Matches private C++ declarations. /// /// Given /// \code /// class C { /// public: int a; /// protected: int b; /// private: int c; /// }; /// \endcode /// fieldDecl(isPrivate()) /// matches 'int c;' AST_MATCHER(Decl, isPrivate) { return Node.getAccess() == AS_private; } /// \brief Matches a declaration that has been implicitly added /// by the compiler (eg. implicit default/copy constructors). AST_MATCHER(Decl, isImplicit) { return Node.isImplicit(); } /// \brief Matches classTemplateSpecializations that have at least one /// TemplateArgument matching the given InnerMatcher. /// /// Given /// \code /// template<typename T> class A {}; /// template<> class A<double> {}; /// A<int> a; /// \endcode /// classTemplateSpecializationDecl(hasAnyTemplateArgument( /// refersToType(asString("int")))) /// matches the specialization \c A<int> AST_POLYMORPHIC_MATCHER_P( hasAnyTemplateArgument, AST_POLYMORPHIC_SUPPORTED_TYPES(ClassTemplateSpecializationDecl, TemplateSpecializationType), internal::Matcher<TemplateArgument>, InnerMatcher) { ArrayRef<TemplateArgument> List = internal::getTemplateSpecializationArgs(Node); return matchesFirstInRange(InnerMatcher, List.begin(), List.end(), Finder, Builder); } /// \brief Matches expressions that match InnerMatcher after any implicit casts /// are stripped off. /// /// Parentheses and explicit casts are not discarded. /// Given /// \code /// int arr[5]; /// int a = 0; /// char b = 0; /// const int c = a; /// int *d = arr; /// long e = (long) 0l; /// \endcode /// The matchers /// \code /// varDecl(hasInitializer(ignoringImpCasts(integerLiteral()))) /// varDecl(hasInitializer(ignoringImpCasts(declRefExpr()))) /// \endcode /// would match the declarations for a, b, c, and d, but not e. /// While /// \code /// varDecl(hasInitializer(integerLiteral())) /// varDecl(hasInitializer(declRefExpr())) /// \endcode /// only match the declarations for b, c, and d. AST_MATCHER_P(Expr, ignoringImpCasts, internal::Matcher<Expr>, InnerMatcher) { return InnerMatcher.matches(*Node.IgnoreImpCasts(), Finder, Builder); } /// \brief Matches expressions that match InnerMatcher after parentheses and /// casts are stripped off. /// /// Implicit and non-C Style casts are also discarded. /// Given /// \code /// int a = 0; /// char b = (0); /// void* c = reinterpret_cast<char*>(0); /// char d = char(0); /// \endcode /// The matcher /// varDecl(hasInitializer(ignoringParenCasts(integerLiteral()))) /// would match the declarations for a, b, c, and d. /// while /// varDecl(hasInitializer(integerLiteral())) /// only match the declaration for a. AST_MATCHER_P(Expr, ignoringParenCasts, internal::Matcher<Expr>, InnerMatcher) { return InnerMatcher.matches(*Node.IgnoreParenCasts(), Finder, Builder); } /// \brief Matches expressions that match InnerMatcher after implicit casts and /// parentheses are stripped off. /// /// Explicit casts are not discarded. /// Given /// \code /// int arr[5]; /// int a = 0; /// char b = (0); /// const int c = a; /// int *d = (arr); /// long e = ((long) 0l); /// \endcode /// The matchers /// varDecl(hasInitializer(ignoringParenImpCasts(integerLiteral()))) /// varDecl(hasInitializer(ignoringParenImpCasts(declRefExpr()))) /// would match the declarations for a, b, c, and d, but not e. /// while /// varDecl(hasInitializer(integerLiteral())) /// varDecl(hasInitializer(declRefExpr())) /// would only match the declaration for a. AST_MATCHER_P(Expr, ignoringParenImpCasts, internal::Matcher<Expr>, InnerMatcher) { return InnerMatcher.matches(*Node.IgnoreParenImpCasts(), Finder, Builder); } /// \brief Matches classTemplateSpecializations where the n'th TemplateArgument /// matches the given InnerMatcher. /// /// Given /// \code /// template<typename T, typename U> class A {}; /// A<bool, int> b; /// A<int, bool> c; /// \endcode /// classTemplateSpecializationDecl(hasTemplateArgument( /// 1, refersToType(asString("int")))) /// matches the specialization \c A<bool, int> AST_POLYMORPHIC_MATCHER_P2( hasTemplateArgument, AST_POLYMORPHIC_SUPPORTED_TYPES(ClassTemplateSpecializationDecl, TemplateSpecializationType), unsigned, N, internal::Matcher<TemplateArgument>, InnerMatcher) { ArrayRef<TemplateArgument> List = internal::getTemplateSpecializationArgs(Node); if (List.size() <= N) return false; return InnerMatcher.matches(List[N], Finder, Builder); } /// \brief Matches if the number of template arguments equals \p N. /// /// Given /// \code /// template<typename T> struct C {}; /// C<int> c; /// \endcode /// classTemplateSpecializationDecl(templateArgumentCountIs(1)) /// matches C<int>. AST_POLYMORPHIC_MATCHER_P( templateArgumentCountIs, AST_POLYMORPHIC_SUPPORTED_TYPES(ClassTemplateSpecializationDecl, TemplateSpecializationType), unsigned, N) { return internal::getTemplateSpecializationArgs(Node).size() == N; } /// \brief Matches a TemplateArgument that refers to a certain type. /// /// Given /// \code /// struct X {}; /// template<typename T> struct A {}; /// A<X> a; /// \endcode /// classTemplateSpecializationDecl(hasAnyTemplateArgument( /// refersToType(class(hasName("X"))))) /// matches the specialization \c A<X> AST_MATCHER_P(TemplateArgument, refersToType, internal::Matcher<QualType>, InnerMatcher) { if (Node.getKind() != TemplateArgument::Type) return false; return InnerMatcher.matches(Node.getAsType(), Finder, Builder); } /// \brief Matches a canonical TemplateArgument that refers to a certain /// declaration. /// /// Given /// \code /// template<typename T> struct A {}; /// struct B { B* next; }; /// A<&B::next> a; /// \endcode /// classTemplateSpecializationDecl(hasAnyTemplateArgument( /// refersToDeclaration(fieldDecl(hasName("next")))) /// matches the specialization \c A<&B::next> with \c fieldDecl(...) matching /// \c B::next AST_MATCHER_P(TemplateArgument, refersToDeclaration, internal::Matcher<Decl>, InnerMatcher) { if (Node.getKind() == TemplateArgument::Declaration) return InnerMatcher.matches(*Node.getAsDecl(), Finder, Builder); return false; } /// \brief Matches a sugar TemplateArgument that refers to a certain expression. /// /// Given /// \code /// template<typename T> struct A {}; /// struct B { B* next; }; /// A<&B::next> a; /// \endcode /// templateSpecializationType(hasAnyTemplateArgument( /// isExpr(hasDescendant(declRefExpr(to(fieldDecl(hasName("next")))))))) /// matches the specialization \c A<&B::next> with \c fieldDecl(...) matching /// \c B::next AST_MATCHER_P(TemplateArgument, isExpr, internal::Matcher<Expr>, InnerMatcher) { if (Node.getKind() == TemplateArgument::Expression) return InnerMatcher.matches(*Node.getAsExpr(), Finder, Builder); return false; } /// \brief Matches a TemplateArgument that is an integral value. /// /// Given /// \code /// template<int T> struct A {}; /// C<42> c; /// \endcode /// classTemplateSpecializationDecl( /// hasAnyTemplateArgument(isIntegral())) /// matches the implicit instantiation of C in C<42> /// with isIntegral() matching 42. AST_MATCHER(TemplateArgument, isIntegral) { return Node.getKind() == TemplateArgument::Integral; } /// \brief Matches a TemplateArgument that referes to an integral type. /// /// Given /// \code /// template<int T> struct A {}; /// C<42> c; /// \endcode /// classTemplateSpecializationDecl( /// hasAnyTemplateArgument(refersToIntegralType(asString("int")))) /// matches the implicit instantiation of C in C<42>. AST_MATCHER_P(TemplateArgument, refersToIntegralType, internal::Matcher<QualType>, InnerMatcher) { if (Node.getKind() != TemplateArgument::Integral) return false; return InnerMatcher.matches(Node.getIntegralType(), Finder, Builder); } /// \brief Matches a TemplateArgument of integral type with a given value. /// /// Note that 'Value' is a string as the template argument's value is /// an arbitrary precision integer. 'Value' must be euqal to the canonical /// representation of that integral value in base 10. /// /// Given /// \code /// template<int T> struct A {}; /// C<42> c; /// \endcode /// classTemplateSpecializationDecl( /// hasAnyTemplateArgument(equalsIntegralValue("42"))) /// matches the implicit instantiation of C in C<42>. AST_MATCHER_P(TemplateArgument, equalsIntegralValue, std::string, Value) { if (Node.getKind() != TemplateArgument::Integral) return false; return Node.getAsIntegral().toString(10) == Value; } /// \brief Matches any value declaration. /// /// Example matches A, B, C and F /// \code /// enum X { A, B, C }; /// void F(); /// \endcode const internal::VariadicDynCastAllOfMatcher<Decl, ValueDecl> valueDecl; /// \brief Matches C++ constructor declarations. /// /// Example matches Foo::Foo() and Foo::Foo(int) /// \code /// class Foo { /// public: /// Foo(); /// Foo(int); /// int DoSomething(); /// }; /// \endcode const internal::VariadicDynCastAllOfMatcher< Decl, CXXConstructorDecl> constructorDecl; /// \brief Matches explicit C++ destructor declarations. /// /// Example matches Foo::~Foo() /// \code /// class Foo { /// public: /// virtual ~Foo(); /// }; /// \endcode const internal::VariadicDynCastAllOfMatcher< Decl, CXXDestructorDecl> destructorDecl; /// \brief Matches enum declarations. /// /// Example matches X /// \code /// enum X { /// A, B, C /// }; /// \endcode const internal::VariadicDynCastAllOfMatcher<Decl, EnumDecl> enumDecl; /// \brief Matches enum constants. /// /// Example matches A, B, C /// \code /// enum X { /// A, B, C /// }; /// \endcode const internal::VariadicDynCastAllOfMatcher< Decl, EnumConstantDecl> enumConstantDecl; /// \brief Matches method declarations. /// /// Example matches y /// \code /// class X { void y(); }; /// \endcode const internal::VariadicDynCastAllOfMatcher<Decl, CXXMethodDecl> methodDecl; /// \brief Matches conversion operator declarations. /// /// Example matches the operator. /// \code /// class X { operator int() const; }; /// \endcode const internal::VariadicDynCastAllOfMatcher<Decl, CXXConversionDecl> conversionDecl; /// \brief Matches variable declarations. /// /// Note: this does not match declarations of member variables, which are /// "field" declarations in Clang parlance. /// /// Example matches a /// \code /// int a; /// \endcode const internal::VariadicDynCastAllOfMatcher<Decl, VarDecl> varDecl; /// \brief Matches field declarations. /// /// Given /// \code /// class X { int m; }; /// \endcode /// fieldDecl() /// matches 'm'. const internal::VariadicDynCastAllOfMatcher<Decl, FieldDecl> fieldDecl; /// \brief Matches function declarations. /// /// Example matches f /// \code /// void f(); /// \endcode const internal::VariadicDynCastAllOfMatcher<Decl, FunctionDecl> functionDecl; /// \brief Matches C++ function template declarations. /// /// Example matches f /// \code /// template<class T> void f(T t) {} /// \endcode const internal::VariadicDynCastAllOfMatcher< Decl, FunctionTemplateDecl> functionTemplateDecl; /// \brief Matches friend declarations. /// /// Given /// \code /// class X { friend void foo(); }; /// \endcode /// friendDecl() /// matches 'friend void foo()'. const internal::VariadicDynCastAllOfMatcher<Decl, FriendDecl> friendDecl; /// \brief Matches statements. /// /// Given /// \code /// { ++a; } /// \endcode /// stmt() /// matches both the compound statement '{ ++a; }' and '++a'. const internal::VariadicAllOfMatcher<Stmt> stmt; /// \brief Matches declaration statements. /// /// Given /// \code /// int a; /// \endcode /// declStmt() /// matches 'int a'. const internal::VariadicDynCastAllOfMatcher< Stmt, DeclStmt> declStmt; /// \brief Matches member expressions. /// /// Given /// \code /// class Y { /// void x() { this->x(); x(); Y y; y.x(); a; this->b; Y::b; } /// int a; static int b; /// }; /// \endcode /// memberExpr() /// matches this->x, x, y.x, a, this->b const internal::VariadicDynCastAllOfMatcher<Stmt, MemberExpr> memberExpr; /// \brief Matches call expressions. /// /// Example matches x.y() and y() /// \code /// X x; /// x.y(); /// y(); /// \endcode const internal::VariadicDynCastAllOfMatcher<Stmt, CallExpr> callExpr; /// \brief Matches lambda expressions. /// /// Example matches [&](){return 5;} /// \code /// [&](){return 5;} /// \endcode const internal::VariadicDynCastAllOfMatcher<Stmt, LambdaExpr> lambdaExpr; /// \brief Matches member call expressions. /// /// Example matches x.y() /// \code /// X x; /// x.y(); /// \endcode const internal::VariadicDynCastAllOfMatcher< Stmt, CXXMemberCallExpr> memberCallExpr; /// \brief Matches ObjectiveC Message invocation expressions. /// /// The innermost message send invokes the "alloc" class method on the /// NSString class, while the outermost message send invokes the /// "initWithString" instance method on the object returned from /// NSString's "alloc". This matcher should match both message sends. /// \code /// [[NSString alloc] initWithString:@"Hello"] /// \endcode const internal::VariadicDynCastAllOfMatcher< Stmt, ObjCMessageExpr> objcMessageExpr; /// \brief Matches expressions that introduce cleanups to be run at the end /// of the sub-expression's evaluation. /// /// Example matches std::string() /// \code /// const std::string str = std::string(); /// \endcode const internal::VariadicDynCastAllOfMatcher<Stmt, ExprWithCleanups> exprWithCleanups; /// \brief Matches init list expressions. /// /// Given /// \code /// int a[] = { 1, 2 }; /// struct B { int x, y; }; /// B b = { 5, 6 }; /// \endcode /// initListExpr() /// matches "{ 1, 2 }" and "{ 5, 6 }" const internal::VariadicDynCastAllOfMatcher<Stmt, InitListExpr> initListExpr; /// \brief Matches substitutions of non-type template parameters. /// /// Given /// \code /// template <int N> /// struct A { static const int n = N; }; /// struct B : public A<42> {}; /// \endcode /// substNonTypeTemplateParmExpr() /// matches "N" in the right-hand side of "static const int n = N;" const internal::VariadicDynCastAllOfMatcher<Stmt, SubstNonTypeTemplateParmExpr> substNonTypeTemplateParmExpr; /// \brief Matches using declarations. /// /// Given /// \code /// namespace X { int x; } /// using X::x; /// \endcode /// usingDecl() /// matches \code using X::x \endcode const internal::VariadicDynCastAllOfMatcher<Decl, UsingDecl> usingDecl; /// \brief Matches using namespace declarations. /// /// Given /// \code /// namespace X { int x; } /// using namespace X; /// \endcode /// usingDirectiveDecl() /// matches \code using namespace X \endcode const internal::VariadicDynCastAllOfMatcher<Decl, UsingDirectiveDecl> usingDirectiveDecl; /// \brief Matches unresolved using value declarations. /// /// Given /// \code /// template<typename X> /// class C : private X { /// using X::x; /// }; /// \endcode /// unresolvedUsingValueDecl() /// matches \code using X::x \endcode const internal::VariadicDynCastAllOfMatcher< Decl, UnresolvedUsingValueDecl> unresolvedUsingValueDecl; /// \brief Matches constructor call expressions (including implicit ones). /// /// Example matches string(ptr, n) and ptr within arguments of f /// (matcher = constructExpr()) /// \code /// void f(const string &a, const string &b); /// char *ptr; /// int n; /// f(string(ptr, n), ptr); /// \endcode const internal::VariadicDynCastAllOfMatcher< Stmt, CXXConstructExpr> constructExpr; /// \brief Matches unresolved constructor call expressions. /// /// Example matches T(t) in return statement of f /// (matcher = unresolvedConstructExpr()) /// \code /// template <typename T> /// void f(const T& t) { return T(t); } /// \endcode const internal::VariadicDynCastAllOfMatcher< Stmt, CXXUnresolvedConstructExpr> unresolvedConstructExpr; /// \brief Matches implicit and explicit this expressions. /// /// Example matches the implicit this expression in "return i". /// (matcher = thisExpr()) /// \code /// struct foo { /// int i; /// int f() { return i; } /// }; /// \endcode const internal::VariadicDynCastAllOfMatcher<Stmt, CXXThisExpr> thisExpr; /// \brief Matches nodes where temporaries are created. /// /// Example matches FunctionTakesString(GetStringByValue()) /// (matcher = bindTemporaryExpr()) /// \code /// FunctionTakesString(GetStringByValue()); /// FunctionTakesStringByPointer(GetStringPointer()); /// \endcode const internal::VariadicDynCastAllOfMatcher< Stmt, CXXBindTemporaryExpr> bindTemporaryExpr; /// \brief Matches nodes where temporaries are materialized. /// /// Example: Given /// \code /// struct T {void func()}; /// T f(); /// void g(T); /// \endcode /// materializeTemporaryExpr() matches 'f()' in these statements /// \code /// T u(f()); /// g(f()); /// \endcode /// but does not match /// \code /// f(); /// f().func(); /// \endcode const internal::VariadicDynCastAllOfMatcher< Stmt, MaterializeTemporaryExpr> materializeTemporaryExpr; /// \brief Matches new expressions. /// /// Given /// \code /// new X; /// \endcode /// newExpr() /// matches 'new X'. const internal::VariadicDynCastAllOfMatcher<Stmt, CXXNewExpr> newExpr; /// \brief Matches delete expressions. /// /// Given /// \code /// delete X; /// \endcode /// deleteExpr() /// matches 'delete X'. const internal::VariadicDynCastAllOfMatcher<Stmt, CXXDeleteExpr> deleteExpr; /// \brief Matches array subscript expressions. /// /// Given /// \code /// int i = a[1]; /// \endcode /// arraySubscriptExpr() /// matches "a[1]" const internal::VariadicDynCastAllOfMatcher< Stmt, ArraySubscriptExpr> arraySubscriptExpr; /// \brief Matches the value of a default argument at the call site. /// /// Example matches the CXXDefaultArgExpr placeholder inserted for the /// default value of the second parameter in the call expression f(42) /// (matcher = defaultArgExpr()) /// \code /// void f(int x, int y = 0); /// f(42); /// \endcode const internal::VariadicDynCastAllOfMatcher< Stmt, CXXDefaultArgExpr> defaultArgExpr; /// \brief Matches overloaded operator calls. /// /// Note that if an operator isn't overloaded, it won't match. Instead, use /// binaryOperator matcher. /// Currently it does not match operators such as new delete. /// FIXME: figure out why these do not match? /// /// Example matches both operator<<((o << b), c) and operator<<(o, b) /// (matcher = operatorCallExpr()) /// \code /// ostream &operator<< (ostream &out, int i) { }; /// ostream &o; int b = 1, c = 1; /// o << b << c; /// \endcode const internal::VariadicDynCastAllOfMatcher< Stmt, CXXOperatorCallExpr> operatorCallExpr; /// \brief Matches expressions. /// /// Example matches x() /// \code /// void f() { x(); } /// \endcode const internal::VariadicDynCastAllOfMatcher<Stmt, Expr> expr; /// \brief Matches expressions that refer to declarations. /// /// Example matches x in if (x) /// \code /// bool x; /// if (x) {} /// \endcode const internal::VariadicDynCastAllOfMatcher<Stmt, DeclRefExpr> declRefExpr; /// \brief Matches if statements. /// /// Example matches 'if (x) {}' /// \code /// if (x) {} /// \endcode const internal::VariadicDynCastAllOfMatcher<Stmt, IfStmt> ifStmt; /// \brief Matches for statements. /// /// Example matches 'for (;;) {}' /// \code /// for (;;) {} /// int i[] = {1, 2, 3}; for (auto a : i); /// \endcode const internal::VariadicDynCastAllOfMatcher<Stmt, ForStmt> forStmt; /// \brief Matches the increment statement of a for loop. /// /// Example: /// forStmt(hasIncrement(unaryOperator(hasOperatorName("++")))) /// matches '++x' in /// \code /// for (x; x < N; ++x) { } /// \endcode AST_MATCHER_P(ForStmt, hasIncrement, internal::Matcher<Stmt>, InnerMatcher) { const Stmt *const Increment = Node.getInc(); return (Increment != nullptr && InnerMatcher.matches(*Increment, Finder, Builder)); } /// \brief Matches the initialization statement of a for loop. /// /// Example: /// forStmt(hasLoopInit(declStmt())) /// matches 'int x = 0' in /// \code /// for (int x = 0; x < N; ++x) { } /// \endcode AST_MATCHER_P(ForStmt, hasLoopInit, internal::Matcher<Stmt>, InnerMatcher) { const Stmt *const Init = Node.getInit(); return (Init != nullptr && InnerMatcher.matches(*Init, Finder, Builder)); } /// \brief Matches range-based for statements. /// /// forRangeStmt() matches 'for (auto a : i)' /// \code /// int i[] = {1, 2, 3}; for (auto a : i); /// for(int j = 0; j < 5; ++j); /// \endcode const internal::VariadicDynCastAllOfMatcher<Stmt, CXXForRangeStmt> forRangeStmt; /// \brief Matches the initialization statement of a for loop. /// /// Example: /// forStmt(hasLoopVariable(anything())) /// matches 'int x' in /// \code /// for (int x : a) { } /// \endcode AST_MATCHER_P(CXXForRangeStmt, hasLoopVariable, internal::Matcher<VarDecl>, InnerMatcher) { const VarDecl *const Var = Node.getLoopVariable(); return (Var != nullptr && InnerMatcher.matches(*Var, Finder, Builder)); } /// \brief Matches the range initialization statement of a for loop. /// /// Example: /// forStmt(hasRangeInit(anything())) /// matches 'a' in /// \code /// for (int x : a) { } /// \endcode AST_MATCHER_P(CXXForRangeStmt, hasRangeInit, internal::Matcher<Expr>, InnerMatcher) { const Expr *const Init = Node.getRangeInit(); return (Init != nullptr && InnerMatcher.matches(*Init, Finder, Builder)); } /// \brief Matches while statements. /// /// Given /// \code /// while (true) {} /// \endcode /// whileStmt() /// matches 'while (true) {}'. const internal::VariadicDynCastAllOfMatcher<Stmt, WhileStmt> whileStmt; /// \brief Matches do statements. /// /// Given /// \code /// do {} while (true); /// \endcode /// doStmt() /// matches 'do {} while(true)' const internal::VariadicDynCastAllOfMatcher<Stmt, DoStmt> doStmt; /// \brief Matches break statements. /// /// Given /// \code /// while (true) { break; } /// \endcode /// breakStmt() /// matches 'break' const internal::VariadicDynCastAllOfMatcher<Stmt, BreakStmt> breakStmt; /// \brief Matches continue statements. /// /// Given /// \code /// while (true) { continue; } /// \endcode /// continueStmt() /// matches 'continue' const internal::VariadicDynCastAllOfMatcher<Stmt, ContinueStmt> continueStmt; /// \brief Matches return statements. /// /// Given /// \code /// return 1; /// \endcode /// returnStmt() /// matches 'return 1' const internal::VariadicDynCastAllOfMatcher<Stmt, ReturnStmt> returnStmt; /// \brief Matches goto statements. /// /// Given /// \code /// goto FOO; /// FOO: bar(); /// \endcode /// gotoStmt() /// matches 'goto FOO' const internal::VariadicDynCastAllOfMatcher<Stmt, GotoStmt> gotoStmt; /// \brief Matches label statements. /// /// Given /// \code /// goto FOO; /// FOO: bar(); /// \endcode /// labelStmt() /// matches 'FOO:' const internal::VariadicDynCastAllOfMatcher<Stmt, LabelStmt> labelStmt; /// \brief Matches switch statements. /// /// Given /// \code /// switch(a) { case 42: break; default: break; } /// \endcode /// switchStmt() /// matches 'switch(a)'. const internal::VariadicDynCastAllOfMatcher<Stmt, SwitchStmt> switchStmt; /// \brief Matches case and default statements inside switch statements. /// /// Given /// \code /// switch(a) { case 42: break; default: break; } /// \endcode /// switchCase() /// matches 'case 42: break;' and 'default: break;'. const internal::VariadicDynCastAllOfMatcher<Stmt, SwitchCase> switchCase; /// \brief Matches case statements inside switch statements. /// /// Given /// \code /// switch(a) { case 42: break; default: break; } /// \endcode /// caseStmt() /// matches 'case 42: break;'. const internal::VariadicDynCastAllOfMatcher<Stmt, CaseStmt> caseStmt; /// \brief Matches default statements inside switch statements. /// /// Given /// \code /// switch(a) { case 42: break; default: break; } /// \endcode /// defaultStmt() /// matches 'default: break;'. const internal::VariadicDynCastAllOfMatcher<Stmt, DefaultStmt> defaultStmt; /// \brief Matches compound statements. /// /// Example matches '{}' and '{{}}'in 'for (;;) {{}}' /// \code /// for (;;) {{}} /// \endcode const internal::VariadicDynCastAllOfMatcher<Stmt, CompoundStmt> compoundStmt; /// \brief Matches catch statements. /// /// \code /// try {} catch(int i) {} /// \endcode /// catchStmt() /// matches 'catch(int i)' const internal::VariadicDynCastAllOfMatcher<Stmt, CXXCatchStmt> catchStmt; /// \brief Matches try statements. /// /// \code /// try {} catch(int i) {} /// \endcode /// tryStmt() /// matches 'try {}' const internal::VariadicDynCastAllOfMatcher<Stmt, CXXTryStmt> tryStmt; /// \brief Matches throw expressions. /// /// \code /// try { throw 5; } catch(int i) {} /// \endcode /// throwExpr() /// matches 'throw 5' const internal::VariadicDynCastAllOfMatcher<Stmt, CXXThrowExpr> throwExpr; /// \brief Matches null statements. /// /// \code /// foo();; /// \endcode /// nullStmt() /// matches the second ';' const internal::VariadicDynCastAllOfMatcher<Stmt, NullStmt> nullStmt; /// \brief Matches asm statements. /// /// \code /// int i = 100; /// __asm("mov al, 2"); /// \endcode /// asmStmt() /// matches '__asm("mov al, 2")' const internal::VariadicDynCastAllOfMatcher<Stmt, AsmStmt> asmStmt; /// \brief Matches bool literals. /// /// Example matches true /// \code /// true /// \endcode const internal::VariadicDynCastAllOfMatcher< Stmt, CXXBoolLiteralExpr> boolLiteral; /// \brief Matches string literals (also matches wide string literals). /// /// Example matches "abcd", L"abcd" /// \code /// char *s = "abcd"; wchar_t *ws = L"abcd" /// \endcode const internal::VariadicDynCastAllOfMatcher< Stmt, StringLiteral> stringLiteral; /// \brief Matches character literals (also matches wchar_t). /// /// Not matching Hex-encoded chars (e.g. 0x1234, which is a IntegerLiteral), /// though. /// /// Example matches 'a', L'a' /// \code /// char ch = 'a'; wchar_t chw = L'a'; /// \endcode const internal::VariadicDynCastAllOfMatcher< Stmt, CharacterLiteral> characterLiteral; /// \brief Matches integer literals of all sizes / encodings, e.g. /// 1, 1L, 0x1 and 1U. /// /// Does not match character-encoded integers such as L'a'. const internal::VariadicDynCastAllOfMatcher< Stmt, IntegerLiteral> integerLiteral; /// \brief Matches float literals of all sizes / encodings, e.g. /// 1.0, 1.0f, 1.0L and 1e10. /// /// Does not match implicit conversions such as /// \code /// float a = 10; /// \endcode const internal::VariadicDynCastAllOfMatcher< Stmt, FloatingLiteral> floatLiteral; /// \brief Matches user defined literal operator call. /// /// Example match: "foo"_suffix const internal::VariadicDynCastAllOfMatcher< Stmt, UserDefinedLiteral> userDefinedLiteral; /// \brief Matches compound (i.e. non-scalar) literals /// /// Example match: {1}, (1, 2) /// \code /// int array[4] = {1}; vector int myvec = (vector int)(1, 2); /// \endcode const internal::VariadicDynCastAllOfMatcher< Stmt, CompoundLiteralExpr> compoundLiteralExpr; /// \brief Matches nullptr literal. const internal::VariadicDynCastAllOfMatcher< Stmt, CXXNullPtrLiteralExpr> nullPtrLiteralExpr; /// \brief Matches GNU __null expression. const internal::VariadicDynCastAllOfMatcher< Stmt, GNUNullExpr> gnuNullExpr; /// \brief Matches binary operator expressions. /// /// Example matches a || b /// \code /// !(a || b) /// \endcode const internal::VariadicDynCastAllOfMatcher< Stmt, BinaryOperator> binaryOperator; /// \brief Matches unary operator expressions. /// /// Example matches !a /// \code /// !a || b /// \endcode const internal::VariadicDynCastAllOfMatcher< Stmt, UnaryOperator> unaryOperator; /// \brief Matches conditional operator expressions. /// /// Example matches a ? b : c /// \code /// (a ? b : c) + 42 /// \endcode const internal::VariadicDynCastAllOfMatcher< Stmt, ConditionalOperator> conditionalOperator; /// \brief Matches a C++ static_assert declaration. /// /// Example: /// staticAssertExpr() /// matches /// static_assert(sizeof(S) == sizeof(int)) /// in /// \code /// struct S { /// int x; /// }; /// static_assert(sizeof(S) == sizeof(int)); /// \endcode const internal::VariadicDynCastAllOfMatcher< Decl, StaticAssertDecl> staticAssertDecl; /// \brief Matches a reinterpret_cast expression. /// /// Either the source expression or the destination type can be matched /// using has(), but hasDestinationType() is more specific and can be /// more readable. /// /// Example matches reinterpret_cast<char*>(&p) in /// \code /// void* p = reinterpret_cast<char*>(&p); /// \endcode const internal::VariadicDynCastAllOfMatcher< Stmt, CXXReinterpretCastExpr> reinterpretCastExpr; /// \brief Matches a C++ static_cast expression. /// /// \see hasDestinationType /// \see reinterpretCast /// /// Example: /// staticCastExpr() /// matches /// static_cast<long>(8) /// in /// \code /// long eight(static_cast<long>(8)); /// \endcode const internal::VariadicDynCastAllOfMatcher< Stmt, CXXStaticCastExpr> staticCastExpr; /// \brief Matches a dynamic_cast expression. /// /// Example: /// dynamicCastExpr() /// matches /// dynamic_cast<D*>(&b); /// in /// \code /// struct B { virtual ~B() {} }; struct D : B {}; /// B b; /// D* p = dynamic_cast<D*>(&b); /// \endcode const internal::VariadicDynCastAllOfMatcher< Stmt, CXXDynamicCastExpr> dynamicCastExpr; /// \brief Matches a const_cast expression. /// /// Example: Matches const_cast<int*>(&r) in /// \code /// int n = 42; /// const int &r(n); /// int* p = const_cast<int*>(&r); /// \endcode const internal::VariadicDynCastAllOfMatcher< Stmt, CXXConstCastExpr> constCastExpr; /// \brief Matches a C-style cast expression. /// /// Example: Matches (int*) 2.2f in /// \code /// int i = (int) 2.2f; /// \endcode const internal::VariadicDynCastAllOfMatcher< Stmt, CStyleCastExpr> cStyleCastExpr; /// \brief Matches explicit cast expressions. /// /// Matches any cast expression written in user code, whether it be a /// C-style cast, a functional-style cast, or a keyword cast. /// /// Does not match implicit conversions. /// /// Note: the name "explicitCast" is chosen to match Clang's terminology, as /// Clang uses the term "cast" to apply to implicit conversions as well as to /// actual cast expressions. /// /// \see hasDestinationType. /// /// Example: matches all five of the casts in /// \code /// int((int)(reinterpret_cast<int>(static_cast<int>(const_cast<int>(42))))) /// \endcode /// but does not match the implicit conversion in /// \code /// long ell = 42; /// \endcode const internal::VariadicDynCastAllOfMatcher< Stmt, ExplicitCastExpr> explicitCastExpr; /// \brief Matches the implicit cast nodes of Clang's AST. /// /// This matches many different places, including function call return value /// eliding, as well as any type conversions. const internal::VariadicDynCastAllOfMatcher< Stmt, ImplicitCastExpr> implicitCastExpr; /// \brief Matches any cast nodes of Clang's AST. /// /// Example: castExpr() matches each of the following: /// \code /// (int) 3; /// const_cast<Expr *>(SubExpr); /// char c = 0; /// \endcode /// but does not match /// \code /// int i = (0); /// int k = 0; /// \endcode const internal::VariadicDynCastAllOfMatcher<Stmt, CastExpr> castExpr; /// \brief Matches functional cast expressions /// /// Example: Matches Foo(bar); /// \code /// Foo f = bar; /// Foo g = (Foo) bar; /// Foo h = Foo(bar); /// \endcode const internal::VariadicDynCastAllOfMatcher< Stmt, CXXFunctionalCastExpr> functionalCastExpr; /// \brief Matches functional cast expressions having N != 1 arguments /// /// Example: Matches Foo(bar, bar) /// \code /// Foo h = Foo(bar, bar); /// \endcode const internal::VariadicDynCastAllOfMatcher< Stmt, CXXTemporaryObjectExpr> temporaryObjectExpr; /// \brief Matches \c QualTypes in the clang AST. const internal::VariadicAllOfMatcher<QualType> qualType; /// \brief Matches \c Types in the clang AST. const internal::VariadicAllOfMatcher<Type> type; /// \brief Matches \c TypeLocs in the clang AST. const internal::VariadicAllOfMatcher<TypeLoc> typeLoc; /// \brief Matches if any of the given matchers matches. /// /// Unlike \c anyOf, \c eachOf will generate a match result for each /// matching submatcher. /// /// For example, in: /// \code /// class A { int a; int b; }; /// \endcode /// The matcher: /// \code /// recordDecl(eachOf(has(fieldDecl(hasName("a")).bind("v")), /// has(fieldDecl(hasName("b")).bind("v")))) /// \endcode /// will generate two results binding "v", the first of which binds /// the field declaration of \c a, the second the field declaration of /// \c b. /// /// Usable as: Any Matcher const internal::VariadicOperatorMatcherFunc<2, UINT_MAX> eachOf = { internal::DynTypedMatcher::VO_EachOf }; /// \brief Matches if any of the given matchers matches. /// /// Usable as: Any Matcher const internal::VariadicOperatorMatcherFunc<2, UINT_MAX> anyOf = { internal::DynTypedMatcher::VO_AnyOf }; /// \brief Matches if all given matchers match. /// /// Usable as: Any Matcher const internal::VariadicOperatorMatcherFunc<2, UINT_MAX> allOf = { internal::DynTypedMatcher::VO_AllOf }; /// \brief Matches sizeof (C99), alignof (C++11) and vec_step (OpenCL) /// /// Given /// \code /// Foo x = bar; /// int y = sizeof(x) + alignof(x); /// \endcode /// unaryExprOrTypeTraitExpr() /// matches \c sizeof(x) and \c alignof(x) const internal::VariadicDynCastAllOfMatcher< Stmt, UnaryExprOrTypeTraitExpr> unaryExprOrTypeTraitExpr; /// \brief Matches unary expressions that have a specific type of argument. /// /// Given /// \code /// int a, c; float b; int s = sizeof(a) + sizeof(b) + alignof(c); /// \endcode /// unaryExprOrTypeTraitExpr(hasArgumentOfType(asString("int")) /// matches \c sizeof(a) and \c alignof(c) AST_MATCHER_P(UnaryExprOrTypeTraitExpr, hasArgumentOfType, internal::Matcher<QualType>, InnerMatcher) { const QualType ArgumentType = Node.getTypeOfArgument(); return InnerMatcher.matches(ArgumentType, Finder, Builder); } /// \brief Matches unary expressions of a certain kind. /// /// Given /// \code /// int x; /// int s = sizeof(x) + alignof(x) /// \endcode /// unaryExprOrTypeTraitExpr(ofKind(UETT_SizeOf)) /// matches \c sizeof(x) AST_MATCHER_P(UnaryExprOrTypeTraitExpr, ofKind, UnaryExprOrTypeTrait, Kind) { return Node.getKind() == Kind; } /// \brief Same as unaryExprOrTypeTraitExpr, but only matching /// alignof. inline internal::Matcher<Stmt> alignOfExpr( const internal::Matcher<UnaryExprOrTypeTraitExpr> &InnerMatcher) { return stmt(unaryExprOrTypeTraitExpr(allOf( ofKind(UETT_AlignOf), InnerMatcher))); } /// \brief Same as unaryExprOrTypeTraitExpr, but only matching /// sizeof. inline internal::Matcher<Stmt> sizeOfExpr( const internal::Matcher<UnaryExprOrTypeTraitExpr> &InnerMatcher) { return stmt(unaryExprOrTypeTraitExpr( allOf(ofKind(UETT_SizeOf), InnerMatcher))); } /// \brief Matches NamedDecl nodes that have the specified name. /// /// Supports specifying enclosing namespaces or classes by prefixing the name /// with '<enclosing>::'. /// Does not match typedefs of an underlying type with the given name. /// /// Example matches X (Name == "X") /// \code /// class X; /// \endcode /// /// Example matches X (Name is one of "::a::b::X", "a::b::X", "b::X", "X") /// \code /// namespace a { namespace b { class X; } } /// \endcode inline internal::Matcher<NamedDecl> hasName(const std::string &Name) { return internal::Matcher<NamedDecl>(new internal::HasNameMatcher(Name)); } /// \brief Matches NamedDecl nodes whose fully qualified names contain /// a substring matched by the given RegExp. /// /// Supports specifying enclosing namespaces or classes by /// prefixing the name with '<enclosing>::'. Does not match typedefs /// of an underlying type with the given name. /// /// Example matches X (regexp == "::X") /// \code /// class X; /// \endcode /// /// Example matches X (regexp is one of "::X", "^foo::.*X", among others) /// \code /// namespace foo { namespace bar { class X; } } /// \endcode AST_MATCHER_P(NamedDecl, matchesName, std::string, RegExp) { assert(!RegExp.empty()); std::string FullNameString = "::" + Node.getQualifiedNameAsString(); llvm::Regex RE(RegExp); return RE.match(FullNameString); } /// \brief Matches overloaded operator names. /// /// Matches overloaded operator names specified in strings without the /// "operator" prefix: e.g. "<<". /// /// Given: /// \code /// class A { int operator*(); }; /// const A &operator<<(const A &a, const A &b); /// A a; /// a << a; // <-- This matches /// \endcode /// /// \c operatorCallExpr(hasOverloadedOperatorName("<<"))) matches the specified /// line and \c recordDecl(hasMethod(hasOverloadedOperatorName("*"))) matches /// the declaration of \c A. /// /// Usable as: Matcher<CXXOperatorCallExpr>, Matcher<FunctionDecl> inline internal::PolymorphicMatcherWithParam1< internal::HasOverloadedOperatorNameMatcher, StringRef, AST_POLYMORPHIC_SUPPORTED_TYPES(CXXOperatorCallExpr, FunctionDecl)> hasOverloadedOperatorName(StringRef Name) { return internal::PolymorphicMatcherWithParam1< internal::HasOverloadedOperatorNameMatcher, StringRef, AST_POLYMORPHIC_SUPPORTED_TYPES(CXXOperatorCallExpr, FunctionDecl)>(Name); } /// \brief Matches C++ classes that are directly or indirectly derived from /// a class matching \c Base. /// /// Note that a class is not considered to be derived from itself. /// /// Example matches Y, Z, C (Base == hasName("X")) /// \code /// class X; /// class Y : public X {}; // directly derived /// class Z : public Y {}; // indirectly derived /// typedef X A; /// typedef A B; /// class C : public B {}; // derived from a typedef of X /// \endcode /// /// In the following example, Bar matches isDerivedFrom(hasName("X")): /// \code /// class Foo; /// typedef Foo X; /// class Bar : public Foo {}; // derived from a type that X is a typedef of /// \endcode AST_MATCHER_P(CXXRecordDecl, isDerivedFrom, internal::Matcher<NamedDecl>, Base) { return Finder->classIsDerivedFrom(&Node, Base, Builder); } /// \brief Overloaded method as shortcut for \c isDerivedFrom(hasName(...)). AST_MATCHER_P_OVERLOAD(CXXRecordDecl, isDerivedFrom, std::string, BaseName, 1) { assert(!BaseName.empty()); return isDerivedFrom(hasName(BaseName)).matches(Node, Finder, Builder); } /// \brief Similar to \c isDerivedFrom(), but also matches classes that directly /// match \c Base. AST_MATCHER_P_OVERLOAD(CXXRecordDecl, isSameOrDerivedFrom, internal::Matcher<NamedDecl>, Base, 0) { return Matcher<CXXRecordDecl>(anyOf(Base, isDerivedFrom(Base))) .matches(Node, Finder, Builder); } /// \brief Overloaded method as shortcut for /// \c isSameOrDerivedFrom(hasName(...)). AST_MATCHER_P_OVERLOAD(CXXRecordDecl, isSameOrDerivedFrom, std::string, BaseName, 1) { assert(!BaseName.empty()); return isSameOrDerivedFrom(hasName(BaseName)).matches(Node, Finder, Builder); } /// \brief Matches the first method of a class or struct that satisfies \c /// InnerMatcher. /// /// Given: /// \code /// class A { void func(); }; /// class B { void member(); }; /// \code /// /// \c recordDecl(hasMethod(hasName("func"))) matches the declaration of \c A /// but not \c B. AST_MATCHER_P(CXXRecordDecl, hasMethod, internal::Matcher<CXXMethodDecl>, InnerMatcher) { return matchesFirstInPointerRange(InnerMatcher, Node.method_begin(), Node.method_end(), Finder, Builder); } /// \brief Matches AST nodes that have child AST nodes that match the /// provided matcher. /// /// Example matches X, Y (matcher = recordDecl(has(recordDecl(hasName("X"))) /// \code /// class X {}; // Matches X, because X::X is a class of name X inside X. /// class Y { class X {}; }; /// class Z { class Y { class X {}; }; }; // Does not match Z. /// \endcode /// /// ChildT must be an AST base type. /// /// Usable as: Any Matcher const internal::ArgumentAdaptingMatcherFunc<internal::HasMatcher> LLVM_ATTRIBUTE_UNUSED has = {}; /// \brief Matches AST nodes that have descendant AST nodes that match the /// provided matcher. /// /// Example matches X, Y, Z /// (matcher = recordDecl(hasDescendant(recordDecl(hasName("X"))))) /// \code /// class X {}; // Matches X, because X::X is a class of name X inside X. /// class Y { class X {}; }; /// class Z { class Y { class X {}; }; }; /// \endcode /// /// DescendantT must be an AST base type. /// /// Usable as: Any Matcher const internal::ArgumentAdaptingMatcherFunc<internal::HasDescendantMatcher> LLVM_ATTRIBUTE_UNUSED hasDescendant = {}; /// \brief Matches AST nodes that have child AST nodes that match the /// provided matcher. /// /// Example matches X, Y (matcher = recordDecl(forEach(recordDecl(hasName("X"))) /// \code /// class X {}; // Matches X, because X::X is a class of name X inside X. /// class Y { class X {}; }; /// class Z { class Y { class X {}; }; }; // Does not match Z. /// \endcode /// /// ChildT must be an AST base type. /// /// As opposed to 'has', 'forEach' will cause a match for each result that /// matches instead of only on the first one. /// /// Usable as: Any Matcher const internal::ArgumentAdaptingMatcherFunc<internal::ForEachMatcher> LLVM_ATTRIBUTE_UNUSED forEach = {}; /// \brief Matches AST nodes that have descendant AST nodes that match the /// provided matcher. /// /// Example matches X, A, B, C /// (matcher = recordDecl(forEachDescendant(recordDecl(hasName("X"))))) /// \code /// class X {}; // Matches X, because X::X is a class of name X inside X. /// class A { class X {}; }; /// class B { class C { class X {}; }; }; /// \endcode /// /// DescendantT must be an AST base type. /// /// As opposed to 'hasDescendant', 'forEachDescendant' will cause a match for /// each result that matches instead of only on the first one. /// /// Note: Recursively combined ForEachDescendant can cause many matches: /// recordDecl(forEachDescendant(recordDecl(forEachDescendant(recordDecl())))) /// will match 10 times (plus injected class name matches) on: /// \code /// class A { class B { class C { class D { class E {}; }; }; }; }; /// \endcode /// /// Usable as: Any Matcher const internal::ArgumentAdaptingMatcherFunc<internal::ForEachDescendantMatcher> LLVM_ATTRIBUTE_UNUSED forEachDescendant = {}; /// \brief Matches if the node or any descendant matches. /// /// Generates results for each match. /// /// For example, in: /// \code /// class A { class B {}; class C {}; }; /// \endcode /// The matcher: /// \code /// recordDecl(hasName("::A"), findAll(recordDecl(isDefinition()).bind("m"))) /// \endcode /// will generate results for \c A, \c B and \c C. /// /// Usable as: Any Matcher template <typename T> internal::Matcher<T> findAll(const internal::Matcher<T> &Matcher) { return eachOf(Matcher, forEachDescendant(Matcher)); } /// \brief Matches AST nodes that have a parent that matches the provided /// matcher. /// /// Given /// \code /// void f() { for (;;) { int x = 42; if (true) { int x = 43; } } } /// \endcode /// \c compoundStmt(hasParent(ifStmt())) matches "{ int x = 43; }". /// /// Usable as: Any Matcher const internal::ArgumentAdaptingMatcherFunc< internal::HasParentMatcher, internal::TypeList<Decl, Stmt>, internal::TypeList<Decl, Stmt> > LLVM_ATTRIBUTE_UNUSED hasParent = {}; /// \brief Matches AST nodes that have an ancestor that matches the provided /// matcher. /// /// Given /// \code /// void f() { if (true) { int x = 42; } } /// void g() { for (;;) { int x = 43; } } /// \endcode /// \c expr(integerLiteral(hasAncestor(ifStmt()))) matches \c 42, but not 43. /// /// Usable as: Any Matcher const internal::ArgumentAdaptingMatcherFunc< internal::HasAncestorMatcher, internal::TypeList<Decl, Stmt>, internal::TypeList<Decl, Stmt> > LLVM_ATTRIBUTE_UNUSED hasAncestor = {}; /// \brief Matches if the provided matcher does not match. /// /// Example matches Y (matcher = recordDecl(unless(hasName("X")))) /// \code /// class X {}; /// class Y {}; /// \endcode /// /// Usable as: Any Matcher const internal::VariadicOperatorMatcherFunc<1, 1> unless = { internal::DynTypedMatcher::VO_UnaryNot }; /// \brief Matches a node if the declaration associated with that node /// matches the given matcher. /// /// The associated declaration is: /// - for type nodes, the declaration of the underlying type /// - for CallExpr, the declaration of the callee /// - for MemberExpr, the declaration of the referenced member /// - for CXXConstructExpr, the declaration of the constructor /// /// Also usable as Matcher<T> for any T supporting the getDecl() member /// function. e.g. various subtypes of clang::Type and various expressions. /// /// Usable as: Matcher<CallExpr>, Matcher<CXXConstructExpr>, /// Matcher<DeclRefExpr>, Matcher<EnumType>, Matcher<InjectedClassNameType>, /// Matcher<LabelStmt>, Matcher<MemberExpr>, Matcher<QualType>, /// Matcher<RecordType>, Matcher<TagType>, /// Matcher<TemplateSpecializationType>, Matcher<TemplateTypeParmType>, /// Matcher<TypedefType>, Matcher<UnresolvedUsingType> inline internal::PolymorphicMatcherWithParam1< internal::HasDeclarationMatcher, internal::Matcher<Decl>, void(internal::HasDeclarationSupportedTypes)> hasDeclaration(const internal::Matcher<Decl> &InnerMatcher) { return internal::PolymorphicMatcherWithParam1< internal::HasDeclarationMatcher, internal::Matcher<Decl>, void(internal::HasDeclarationSupportedTypes)>(InnerMatcher); } /// \brief Matches on the implicit object argument of a member call expression. /// /// Example matches y.x() (matcher = callExpr(on(hasType(recordDecl(hasName("Y")))))) /// \code /// class Y { public: void x(); }; /// void z() { Y y; y.x(); }", /// \endcode /// /// FIXME: Overload to allow directly matching types? AST_MATCHER_P(CXXMemberCallExpr, on, internal::Matcher<Expr>, InnerMatcher) { const Expr *ExprNode = Node.getImplicitObjectArgument() ->IgnoreParenImpCasts(); return (ExprNode != nullptr && InnerMatcher.matches(*ExprNode, Finder, Builder)); } /// \brief Matches on the receiver of an ObjectiveC Message expression. /// /// Example /// matcher = objCMessageExpr(hasRecieverType(asString("UIWebView *"))); /// matches the [webView ...] message invocation. /// \code /// NSString *webViewJavaScript = ... /// UIWebView *webView = ... /// [webView stringByEvaluatingJavaScriptFromString:webViewJavascript]; /// \endcode AST_MATCHER_P(ObjCMessageExpr, hasReceiverType, internal::Matcher<QualType>, InnerMatcher) { const QualType TypeDecl = Node.getReceiverType(); return InnerMatcher.matches(TypeDecl, Finder, Builder); } /// \brief Matches when BaseName == Selector.getAsString() /// /// matcher = objCMessageExpr(hasSelector("loadHTMLString:baseURL:")); /// matches the outer message expr in the code below, but NOT the message /// invocation for self.bodyView. /// \code /// [self.bodyView loadHTMLString:html baseURL:NULL]; /// \endcode AST_MATCHER_P(ObjCMessageExpr, hasSelector, std::string, BaseName) { Selector Sel = Node.getSelector(); return BaseName.compare(Sel.getAsString()) == 0; } /// \brief Matches ObjC selectors whose name contains /// a substring matched by the given RegExp. /// matcher = objCMessageExpr(matchesSelector("loadHTMLString\:baseURL?")); /// matches the outer message expr in the code below, but NOT the message /// invocation for self.bodyView. /// \code /// [self.bodyView loadHTMLString:html baseURL:NULL]; /// \endcode AST_MATCHER_P(ObjCMessageExpr, matchesSelector, std::string, RegExp) { assert(!RegExp.empty()); std::string SelectorString = Node.getSelector().getAsString(); llvm::Regex RE(RegExp); return RE.match(SelectorString); } /// \brief Matches when the selector is the empty selector /// /// Matches only when the selector of the objCMessageExpr is NULL. This may /// represent an error condition in the tree! AST_MATCHER(ObjCMessageExpr, hasNullSelector) { return Node.getSelector().isNull(); } /// \brief Matches when the selector is a Unary Selector /// /// matcher = objCMessageExpr(matchesSelector(hasUnarySelector()); /// matches self.bodyView in the code below, but NOT the outer message /// invocation of "loadHTMLString:baseURL:". /// \code /// [self.bodyView loadHTMLString:html baseURL:NULL]; /// \endcode AST_MATCHER(ObjCMessageExpr, hasUnarySelector) { return Node.getSelector().isUnarySelector(); } /// \brief Matches when the selector is a keyword selector /// /// objCMessageExpr(hasKeywordSelector()) matches the generated setFrame /// message expression in /// /// \code /// UIWebView *webView = ...; /// CGRect bodyFrame = webView.frame; /// bodyFrame.size.height = self.bodyContentHeight; /// webView.frame = bodyFrame; /// // ^---- matches here /// \endcode AST_MATCHER(ObjCMessageExpr, hasKeywordSelector) { return Node.getSelector().isKeywordSelector(); } /// \brief Matches when the selector has the specified number of arguments /// /// matcher = objCMessageExpr(numSelectorArgs(1)); /// matches self.bodyView in the code below /// /// matcher = objCMessageExpr(numSelectorArgs(2)); /// matches the invocation of "loadHTMLString:baseURL:" but not that /// of self.bodyView /// \code /// [self.bodyView loadHTMLString:html baseURL:NULL]; /// \endcode AST_MATCHER_P(ObjCMessageExpr, numSelectorArgs, unsigned, N) { return Node.getSelector().getNumArgs() == N; } /// \brief Matches if the call expression's callee expression matches. /// /// Given /// \code /// class Y { void x() { this->x(); x(); Y y; y.x(); } }; /// void f() { f(); } /// \endcode /// callExpr(callee(expr())) /// matches this->x(), x(), y.x(), f() /// with callee(...) /// matching this->x, x, y.x, f respectively /// /// Note: Callee cannot take the more general internal::Matcher<Expr> /// because this introduces ambiguous overloads with calls to Callee taking a /// internal::Matcher<Decl>, as the matcher hierarchy is purely /// implemented in terms of implicit casts. AST_MATCHER_P(CallExpr, callee, internal::Matcher<Stmt>, InnerMatcher) { const Expr *ExprNode = Node.getCallee(); return (ExprNode != nullptr && InnerMatcher.matches(*ExprNode, Finder, Builder)); } /// \brief Matches if the call expression's callee's declaration matches the /// given matcher. /// /// Example matches y.x() (matcher = callExpr(callee(methodDecl(hasName("x"))))) /// \code /// class Y { public: void x(); }; /// void z() { Y y; y.x(); } /// \endcode AST_MATCHER_P_OVERLOAD(CallExpr, callee, internal::Matcher<Decl>, InnerMatcher, 1) { return callExpr(hasDeclaration(InnerMatcher)).matches(Node, Finder, Builder); } /// \brief Matches if the expression's or declaration's type matches a type /// matcher. /// /// Example matches x (matcher = expr(hasType(recordDecl(hasName("X"))))) /// and z (matcher = varDecl(hasType(recordDecl(hasName("X"))))) /// \code /// class X {}; /// void y(X &x) { x; X z; } /// \endcode AST_POLYMORPHIC_MATCHER_P_OVERLOAD( hasType, AST_POLYMORPHIC_SUPPORTED_TYPES(Expr, ValueDecl), internal::Matcher<QualType>, InnerMatcher, 0) { return InnerMatcher.matches(Node.getType(), Finder, Builder); } /// \brief Overloaded to match the declaration of the expression's or value /// declaration's type. /// /// In case of a value declaration (for example a variable declaration), /// this resolves one layer of indirection. For example, in the value /// declaration "X x;", recordDecl(hasName("X")) matches the declaration of X, /// while varDecl(hasType(recordDecl(hasName("X")))) matches the declaration /// of x." /// /// Example matches x (matcher = expr(hasType(recordDecl(hasName("X"))))) /// and z (matcher = varDecl(hasType(recordDecl(hasName("X"))))) /// \code /// class X {}; /// void y(X &x) { x; X z; } /// \endcode /// /// Usable as: Matcher<Expr>, Matcher<ValueDecl> AST_POLYMORPHIC_MATCHER_P_OVERLOAD(hasType, AST_POLYMORPHIC_SUPPORTED_TYPES(Expr, ValueDecl), internal::Matcher<Decl>, InnerMatcher, 1) { return qualType(hasDeclaration(InnerMatcher)) .matches(Node.getType(), Finder, Builder); } /// \brief Matches if the type location of the declarator decl's type matches /// the inner matcher. /// /// Given /// \code /// int x; /// \endcode /// declaratorDecl(hasTypeLoc(loc(asString("int")))) /// matches int x AST_MATCHER_P(DeclaratorDecl, hasTypeLoc, internal::Matcher<TypeLoc>, Inner) { if (!Node.getTypeSourceInfo()) // This happens for example for implicit destructors. return false; return Inner.matches(Node.getTypeSourceInfo()->getTypeLoc(), Finder, Builder); } /// \brief Matches if the matched type is represented by the given string. /// /// Given /// \code /// class Y { public: void x(); }; /// void z() { Y* y; y->x(); } /// \endcode /// callExpr(on(hasType(asString("class Y *")))) /// matches y->x() AST_MATCHER_P(QualType, asString, std::string, Name) { return Name == Node.getAsString(); } /// \brief Matches if the matched type is a pointer type and the pointee type /// matches the specified matcher. /// /// Example matches y->x() /// (matcher = callExpr(on(hasType(pointsTo(recordDecl(hasName("Y"))))))) /// \code /// class Y { public: void x(); }; /// void z() { Y *y; y->x(); } /// \endcode AST_MATCHER_P( QualType, pointsTo, internal::Matcher<QualType>, InnerMatcher) { return (!Node.isNull() && Node->isPointerType() && InnerMatcher.matches(Node->getPointeeType(), Finder, Builder)); } /// \brief Overloaded to match the pointee type's declaration. AST_MATCHER_P_OVERLOAD(QualType, pointsTo, internal::Matcher<Decl>, InnerMatcher, 1) { return pointsTo(qualType(hasDeclaration(InnerMatcher))) .matches(Node, Finder, Builder); } /// \brief Matches if the matched type is a reference type and the referenced /// type matches the specified matcher. /// /// Example matches X &x and const X &y /// (matcher = varDecl(hasType(references(recordDecl(hasName("X")))))) /// \code /// class X { /// void a(X b) { /// X &x = b; /// const X &y = b; /// } /// }; /// \endcode AST_MATCHER_P(QualType, references, internal::Matcher<QualType>, InnerMatcher) { return (!Node.isNull() && Node->isReferenceType() && InnerMatcher.matches(Node->getPointeeType(), Finder, Builder)); } /// \brief Matches QualTypes whose canonical type matches InnerMatcher. /// /// Given: /// \code /// typedef int &int_ref; /// int a; /// int_ref b = a; /// \code /// /// \c varDecl(hasType(qualType(referenceType()))))) will not match the /// declaration of b but \c /// varDecl(hasType(qualType(hasCanonicalType(referenceType())))))) does. AST_MATCHER_P(QualType, hasCanonicalType, internal::Matcher<QualType>, InnerMatcher) { if (Node.isNull()) return false; return InnerMatcher.matches(Node.getCanonicalType(), Finder, Builder); } /// \brief Overloaded to match the referenced type's declaration. AST_MATCHER_P_OVERLOAD(QualType, references, internal::Matcher<Decl>, InnerMatcher, 1) { return references(qualType(hasDeclaration(InnerMatcher))) .matches(Node, Finder, Builder); } AST_MATCHER_P(CXXMemberCallExpr, onImplicitObjectArgument, internal::Matcher<Expr>, InnerMatcher) { const Expr *ExprNode = Node.getImplicitObjectArgument(); return (ExprNode != nullptr && InnerMatcher.matches(*ExprNode, Finder, Builder)); } /// \brief Matches if the expression's type either matches the specified /// matcher, or is a pointer to a type that matches the InnerMatcher. AST_MATCHER_P_OVERLOAD(CXXMemberCallExpr, thisPointerType, internal::Matcher<QualType>, InnerMatcher, 0) { return onImplicitObjectArgument( anyOf(hasType(InnerMatcher), hasType(pointsTo(InnerMatcher)))) .matches(Node, Finder, Builder); } /// \brief Overloaded to match the type's declaration. AST_MATCHER_P_OVERLOAD(CXXMemberCallExpr, thisPointerType, internal::Matcher<Decl>, InnerMatcher, 1) { return onImplicitObjectArgument( anyOf(hasType(InnerMatcher), hasType(pointsTo(InnerMatcher)))) .matches(Node, Finder, Builder); } /// \brief Matches a DeclRefExpr that refers to a declaration that matches the /// specified matcher. /// /// Example matches x in if(x) /// (matcher = declRefExpr(to(varDecl(hasName("x"))))) /// \code /// bool x; /// if (x) {} /// \endcode AST_MATCHER_P(DeclRefExpr, to, internal::Matcher<Decl>, InnerMatcher) { const Decl *DeclNode = Node.getDecl(); return (DeclNode != nullptr && InnerMatcher.matches(*DeclNode, Finder, Builder)); } /// \brief Matches a \c DeclRefExpr that refers to a declaration through a /// specific using shadow declaration. /// /// FIXME: This currently only works for functions. Fix. /// /// Given /// \code /// namespace a { void f() {} } /// using a::f; /// void g() { /// f(); // Matches this .. /// a::f(); // .. but not this. /// } /// \endcode /// declRefExpr(throughUsingDeclaration(anything())) /// matches \c f() AST_MATCHER_P(DeclRefExpr, throughUsingDecl, internal::Matcher<UsingShadowDecl>, InnerMatcher) { const NamedDecl *FoundDecl = Node.getFoundDecl(); if (const UsingShadowDecl *UsingDecl = dyn_cast<UsingShadowDecl>(FoundDecl)) return InnerMatcher.matches(*UsingDecl, Finder, Builder); return false; } /// \brief Matches the Decl of a DeclStmt which has a single declaration. /// /// Given /// \code /// int a, b; /// int c; /// \endcode /// declStmt(hasSingleDecl(anything())) /// matches 'int c;' but not 'int a, b;'. AST_MATCHER_P(DeclStmt, hasSingleDecl, internal::Matcher<Decl>, InnerMatcher) { if (Node.isSingleDecl()) { const Decl *FoundDecl = Node.getSingleDecl(); return InnerMatcher.matches(*FoundDecl, Finder, Builder); } return false; } /// \brief Matches a variable declaration that has an initializer expression /// that matches the given matcher. /// /// Example matches x (matcher = varDecl(hasInitializer(callExpr()))) /// \code /// bool y() { return true; } /// bool x = y(); /// \endcode AST_MATCHER_P( VarDecl, hasInitializer, internal::Matcher<Expr>, InnerMatcher) { const Expr *Initializer = Node.getAnyInitializer(); return (Initializer != nullptr && InnerMatcher.matches(*Initializer, Finder, Builder)); } /// \brief Matches a variable declaration that has function scope and is a /// non-static local variable. /// /// Example matches x (matcher = varDecl(hasLocalStorage()) /// \code /// void f() { /// int x; /// static int y; /// } /// int z; /// \endcode AST_MATCHER(VarDecl, hasLocalStorage) { return Node.hasLocalStorage(); } /// \brief Matches a variable declaration that does not have local storage. /// /// Example matches y and z (matcher = varDecl(hasGlobalStorage()) /// \code /// void f() { /// int x; /// static int y; /// } /// int z; /// \endcode AST_MATCHER(VarDecl, hasGlobalStorage) { return Node.hasGlobalStorage(); } /// \brief Checks that a call expression or a constructor call expression has /// a specific number of arguments (including absent default arguments). /// /// Example matches f(0, 0) (matcher = callExpr(argumentCountIs(2))) /// \code /// void f(int x, int y); /// f(0, 0); /// \endcode AST_POLYMORPHIC_MATCHER_P(argumentCountIs, AST_POLYMORPHIC_SUPPORTED_TYPES(CallExpr, CXXConstructExpr, ObjCMessageExpr), unsigned, N) { return Node.getNumArgs() == N; } /// \brief Matches the n'th argument of a call expression or a constructor /// call expression. /// /// Example matches y in x(y) /// (matcher = callExpr(hasArgument(0, declRefExpr()))) /// \code /// void x(int) { int y; x(y); } /// \endcode AST_POLYMORPHIC_MATCHER_P2(hasArgument, AST_POLYMORPHIC_SUPPORTED_TYPES(CallExpr, CXXConstructExpr, ObjCMessageExpr), unsigned, N, internal::Matcher<Expr>, InnerMatcher) { return (N < Node.getNumArgs() && InnerMatcher.matches( *Node.getArg(N)->IgnoreParenImpCasts(), Finder, Builder)); } /// \brief Matches declaration statements that contain a specific number of /// declarations. /// /// Example: Given /// \code /// int a, b; /// int c; /// int d = 2, e; /// \endcode /// declCountIs(2) /// matches 'int a, b;' and 'int d = 2, e;', but not 'int c;'. AST_MATCHER_P(DeclStmt, declCountIs, unsigned, N) { return std::distance(Node.decl_begin(), Node.decl_end()) == (ptrdiff_t)N; } /// \brief Matches the n'th declaration of a declaration statement. /// /// Note that this does not work for global declarations because the AST /// breaks up multiple-declaration DeclStmt's into multiple single-declaration /// DeclStmt's. /// Example: Given non-global declarations /// \code /// int a, b = 0; /// int c; /// int d = 2, e; /// \endcode /// declStmt(containsDeclaration( /// 0, varDecl(hasInitializer(anything())))) /// matches only 'int d = 2, e;', and /// declStmt(containsDeclaration(1, varDecl())) /// \code /// matches 'int a, b = 0' as well as 'int d = 2, e;' /// but 'int c;' is not matched. /// \endcode AST_MATCHER_P2(DeclStmt, containsDeclaration, unsigned, N, internal::Matcher<Decl>, InnerMatcher) { const unsigned NumDecls = std::distance(Node.decl_begin(), Node.decl_end()); if (N >= NumDecls) return false; DeclStmt::const_decl_iterator Iterator = Node.decl_begin(); std::advance(Iterator, N); return InnerMatcher.matches(**Iterator, Finder, Builder); } /// \brief Matches a C++ catch statement that has a catch-all handler. /// /// Given /// \code /// try { /// // ... /// } catch (int) { /// // ... /// } catch (...) { /// // ... /// } /// /endcode /// catchStmt(isCatchAll()) matches catch(...) but not catch(int). AST_MATCHER(CXXCatchStmt, isCatchAll) { return Node.getExceptionDecl() == nullptr; } /// \brief Matches a constructor initializer. /// /// Given /// \code /// struct Foo { /// Foo() : foo_(1) { } /// int foo_; /// }; /// \endcode /// recordDecl(has(constructorDecl(hasAnyConstructorInitializer(anything())))) /// record matches Foo, hasAnyConstructorInitializer matches foo_(1) AST_MATCHER_P(CXXConstructorDecl, hasAnyConstructorInitializer, internal::Matcher<CXXCtorInitializer>, InnerMatcher) { return matchesFirstInPointerRange(InnerMatcher, Node.init_begin(), Node.init_end(), Finder, Builder); } /// \brief Matches the field declaration of a constructor initializer. /// /// Given /// \code /// struct Foo { /// Foo() : foo_(1) { } /// int foo_; /// }; /// \endcode /// recordDecl(has(constructorDecl(hasAnyConstructorInitializer( /// forField(hasName("foo_")))))) /// matches Foo /// with forField matching foo_ AST_MATCHER_P(CXXCtorInitializer, forField, internal::Matcher<FieldDecl>, InnerMatcher) { const FieldDecl *NodeAsDecl = Node.getMember(); return (NodeAsDecl != nullptr && InnerMatcher.matches(*NodeAsDecl, Finder, Builder)); } /// \brief Matches the initializer expression of a constructor initializer. /// /// Given /// \code /// struct Foo { /// Foo() : foo_(1) { } /// int foo_; /// }; /// \endcode /// recordDecl(has(constructorDecl(hasAnyConstructorInitializer( /// withInitializer(integerLiteral(equals(1))))))) /// matches Foo /// with withInitializer matching (1) AST_MATCHER_P(CXXCtorInitializer, withInitializer, internal::Matcher<Expr>, InnerMatcher) { const Expr* NodeAsExpr = Node.getInit(); return (NodeAsExpr != nullptr && InnerMatcher.matches(*NodeAsExpr, Finder, Builder)); } /// \brief Matches a constructor initializer if it is explicitly written in /// code (as opposed to implicitly added by the compiler). /// /// Given /// \code /// struct Foo { /// Foo() { } /// Foo(int) : foo_("A") { } /// string foo_; /// }; /// \endcode /// constructorDecl(hasAnyConstructorInitializer(isWritten())) /// will match Foo(int), but not Foo() AST_MATCHER(CXXCtorInitializer, isWritten) { return Node.isWritten(); } /// \brief Matches any argument of a call expression or a constructor call /// expression. /// /// Given /// \code /// void x(int, int, int) { int y; x(1, y, 42); } /// \endcode /// callExpr(hasAnyArgument(declRefExpr())) /// matches x(1, y, 42) /// with hasAnyArgument(...) /// matching y /// /// FIXME: Currently this will ignore parentheses and implicit casts on /// the argument before applying the inner matcher. We'll want to remove /// this to allow for greater control by the user once \c ignoreImplicit() /// has been implemented. AST_POLYMORPHIC_MATCHER_P(hasAnyArgument, AST_POLYMORPHIC_SUPPORTED_TYPES(CallExpr, CXXConstructExpr), internal::Matcher<Expr>, InnerMatcher) { for (const Expr *Arg : Node.arguments()) { BoundNodesTreeBuilder Result(*Builder); if (InnerMatcher.matches(*Arg->IgnoreParenImpCasts(), Finder, &Result)) { *Builder = std::move(Result); return true; } } return false; } /// \brief Matches a constructor call expression which uses list initialization. AST_MATCHER(CXXConstructExpr, isListInitialization) { return Node.isListInitialization(); } /// \brief Matches the n'th parameter of a function declaration. /// /// Given /// \code /// class X { void f(int x) {} }; /// \endcode /// methodDecl(hasParameter(0, hasType(varDecl()))) /// matches f(int x) {} /// with hasParameter(...) /// matching int x AST_MATCHER_P2(FunctionDecl, hasParameter, unsigned, N, internal::Matcher<ParmVarDecl>, InnerMatcher) { return (N < Node.getNumParams() && InnerMatcher.matches( *Node.getParamDecl(N), Finder, Builder)); } /// \brief Matches any parameter of a function declaration. /// /// Does not match the 'this' parameter of a method. /// /// Given /// \code /// class X { void f(int x, int y, int z) {} }; /// \endcode /// methodDecl(hasAnyParameter(hasName("y"))) /// matches f(int x, int y, int z) {} /// with hasAnyParameter(...) /// matching int y AST_MATCHER_P(FunctionDecl, hasAnyParameter, internal::Matcher<ParmVarDecl>, InnerMatcher) { return matchesFirstInPointerRange(InnerMatcher, Node.param_begin(), Node.param_end(), Finder, Builder); } /// \brief Matches \c FunctionDecls that have a specific parameter count. /// /// Given /// \code /// void f(int i) {} /// void g(int i, int j) {} /// \endcode /// functionDecl(parameterCountIs(2)) /// matches g(int i, int j) {} AST_MATCHER_P(FunctionDecl, parameterCountIs, unsigned, N) { return Node.getNumParams() == N; } /// \brief Matches the return type of a function declaration. /// /// Given: /// \code /// class X { int f() { return 1; } }; /// \endcode /// methodDecl(returns(asString("int"))) /// matches int f() { return 1; } AST_MATCHER_P(FunctionDecl, returns, internal::Matcher<QualType>, InnerMatcher) { return InnerMatcher.matches(Node.getReturnType(), Finder, Builder); } /// \brief Matches extern "C" function declarations. /// /// Given: /// \code /// extern "C" void f() {} /// extern "C" { void g() {} } /// void h() {} /// \endcode /// functionDecl(isExternC()) /// matches the declaration of f and g, but not the declaration h AST_MATCHER(FunctionDecl, isExternC) { return Node.isExternC(); } /// \brief Matches deleted function declarations. /// /// Given: /// \code /// void Func(); /// void DeletedFunc() = delete; /// \endcode /// functionDecl(isDeleted()) /// matches the declaration of DeletedFunc, but not Func. AST_MATCHER(FunctionDecl, isDeleted) { return Node.isDeleted(); } /// \brief Matches constexpr variable and function declarations. /// /// Given: /// \code /// constexpr int foo = 42; /// constexpr int bar(); /// \endcode /// varDecl(isConstexpr()) /// matches the declaration of foo. /// functionDecl(isConstexpr()) /// matches the declaration of bar. AST_POLYMORPHIC_MATCHER(isConstexpr, AST_POLYMORPHIC_SUPPORTED_TYPES(VarDecl, FunctionDecl)) { return Node.isConstexpr(); } /// \brief Matches the condition expression of an if statement, for loop, /// or conditional operator. /// /// Example matches true (matcher = hasCondition(boolLiteral(equals(true)))) /// \code /// if (true) {} /// \endcode AST_POLYMORPHIC_MATCHER_P(hasCondition, AST_POLYMORPHIC_SUPPORTED_TYPES(IfStmt, ForStmt, WhileStmt, DoStmt, ConditionalOperator), internal::Matcher<Expr>, InnerMatcher) { const Expr *const Condition = Node.getCond(); return (Condition != nullptr && InnerMatcher.matches(*Condition, Finder, Builder)); } /// \brief Matches the then-statement of an if statement. /// /// Examples matches the if statement /// (matcher = ifStmt(hasThen(boolLiteral(equals(true))))) /// \code /// if (false) true; else false; /// \endcode AST_MATCHER_P(IfStmt, hasThen, internal::Matcher<Stmt>, InnerMatcher) { const Stmt *const Then = Node.getThen(); return (Then != nullptr && InnerMatcher.matches(*Then, Finder, Builder)); } /// \brief Matches the else-statement of an if statement. /// /// Examples matches the if statement /// (matcher = ifStmt(hasElse(boolLiteral(equals(true))))) /// \code /// if (false) false; else true; /// \endcode AST_MATCHER_P(IfStmt, hasElse, internal::Matcher<Stmt>, InnerMatcher) { const Stmt *const Else = Node.getElse(); return (Else != nullptr && InnerMatcher.matches(*Else, Finder, Builder)); } /// \brief Matches if a node equals a previously bound node. /// /// Matches a node if it equals the node previously bound to \p ID. /// /// Given /// \code /// class X { int a; int b; }; /// \endcode /// recordDecl( /// has(fieldDecl(hasName("a"), hasType(type().bind("t")))), /// has(fieldDecl(hasName("b"), hasType(type(equalsBoundNode("t")))))) /// matches the class \c X, as \c a and \c b have the same type. /// /// Note that when multiple matches are involved via \c forEach* matchers, /// \c equalsBoundNodes acts as a filter. /// For example: /// compoundStmt( /// forEachDescendant(varDecl().bind("d")), /// forEachDescendant(declRefExpr(to(decl(equalsBoundNode("d")))))) /// will trigger a match for each combination of variable declaration /// and reference to that variable declaration within a compound statement. AST_POLYMORPHIC_MATCHER_P(equalsBoundNode, AST_POLYMORPHIC_SUPPORTED_TYPES(Stmt, Decl, Type, QualType), std::string, ID) { // FIXME: Figure out whether it makes sense to allow this // on any other node types. // For *Loc it probably does not make sense, as those seem // unique. For NestedNameSepcifier it might make sense, as // those also have pointer identity, but I'm not sure whether // they're ever reused. internal::NotEqualsBoundNodePredicate Predicate; Predicate.ID = ID; Predicate.Node = ast_type_traits::DynTypedNode::create(Node); return Builder->removeBindings(Predicate); } /// \brief Matches the condition variable statement in an if statement. /// /// Given /// \code /// if (A* a = GetAPointer()) {} /// \endcode /// hasConditionVariableStatement(...) /// matches 'A* a = GetAPointer()'. AST_MATCHER_P(IfStmt, hasConditionVariableStatement, internal::Matcher<DeclStmt>, InnerMatcher) { const DeclStmt* const DeclarationStatement = Node.getConditionVariableDeclStmt(); return DeclarationStatement != nullptr && InnerMatcher.matches(*DeclarationStatement, Finder, Builder); } /// \brief Matches the index expression of an array subscript expression. /// /// Given /// \code /// int i[5]; /// void f() { i[1] = 42; } /// \endcode /// arraySubscriptExpression(hasIndex(integerLiteral())) /// matches \c i[1] with the \c integerLiteral() matching \c 1 AST_MATCHER_P(ArraySubscriptExpr, hasIndex, internal::Matcher<Expr>, InnerMatcher) { if (const Expr* Expression = Node.getIdx()) return InnerMatcher.matches(*Expression, Finder, Builder); return false; } /// \brief Matches the base expression of an array subscript expression. /// /// Given /// \code /// int i[5]; /// void f() { i[1] = 42; } /// \endcode /// arraySubscriptExpression(hasBase(implicitCastExpr( /// hasSourceExpression(declRefExpr())))) /// matches \c i[1] with the \c declRefExpr() matching \c i AST_MATCHER_P(ArraySubscriptExpr, hasBase, internal::Matcher<Expr>, InnerMatcher) { if (const Expr* Expression = Node.getBase()) return InnerMatcher.matches(*Expression, Finder, Builder); return false; } /// \brief Matches a 'for', 'while', or 'do while' statement that has /// a given body. /// /// Given /// \code /// for (;;) {} /// \endcode /// hasBody(compoundStmt()) /// matches 'for (;;) {}' /// with compoundStmt() /// matching '{}' AST_POLYMORPHIC_MATCHER_P(hasBody, AST_POLYMORPHIC_SUPPORTED_TYPES(DoStmt, ForStmt, WhileStmt, CXXForRangeStmt), internal::Matcher<Stmt>, InnerMatcher) { const Stmt *const Statement = Node.getBody(); return (Statement != nullptr && InnerMatcher.matches(*Statement, Finder, Builder)); } /// \brief Matches compound statements where at least one substatement matches /// a given matcher. /// /// Given /// \code /// { {}; 1+2; } /// \endcode /// hasAnySubstatement(compoundStmt()) /// matches '{ {}; 1+2; }' /// with compoundStmt() /// matching '{}' AST_MATCHER_P(CompoundStmt, hasAnySubstatement, internal::Matcher<Stmt>, InnerMatcher) { return matchesFirstInPointerRange(InnerMatcher, Node.body_begin(), Node.body_end(), Finder, Builder); } /// \brief Checks that a compound statement contains a specific number of /// child statements. /// /// Example: Given /// \code /// { for (;;) {} } /// \endcode /// compoundStmt(statementCountIs(0))) /// matches '{}' /// but does not match the outer compound statement. AST_MATCHER_P(CompoundStmt, statementCountIs, unsigned, N) { return Node.size() == N; } /// \brief Matches literals that are equal to the given value. /// /// Example matches true (matcher = boolLiteral(equals(true))) /// \code /// true /// \endcode /// /// Usable as: Matcher<CharacterLiteral>, Matcher<CXXBoolLiteral>, /// Matcher<FloatingLiteral>, Matcher<IntegerLiteral> template <typename ValueT> internal::PolymorphicMatcherWithParam1<internal::ValueEqualsMatcher, ValueT> equals(const ValueT &Value) { return internal::PolymorphicMatcherWithParam1< internal::ValueEqualsMatcher, ValueT>(Value); } /// \brief Matches the operator Name of operator expressions (binary or /// unary). /// /// Example matches a || b (matcher = binaryOperator(hasOperatorName("||"))) /// \code /// !(a || b) /// \endcode AST_POLYMORPHIC_MATCHER_P(hasOperatorName, AST_POLYMORPHIC_SUPPORTED_TYPES(BinaryOperator, UnaryOperator), std::string, Name) { return Name == Node.getOpcodeStr(Node.getOpcode()); } /// \brief Matches the left hand side of binary operator expressions. /// /// Example matches a (matcher = binaryOperator(hasLHS())) /// \code /// a || b /// \endcode AST_MATCHER_P(BinaryOperator, hasLHS, internal::Matcher<Expr>, InnerMatcher) { Expr *LeftHandSide = Node.getLHS(); return (LeftHandSide != nullptr && InnerMatcher.matches(*LeftHandSide, Finder, Builder)); } /// \brief Matches the right hand side of binary operator expressions. /// /// Example matches b (matcher = binaryOperator(hasRHS())) /// \code /// a || b /// \endcode AST_MATCHER_P(BinaryOperator, hasRHS, internal::Matcher<Expr>, InnerMatcher) { Expr *RightHandSide = Node.getRHS(); return (RightHandSide != nullptr && InnerMatcher.matches(*RightHandSide, Finder, Builder)); } /// \brief Matches if either the left hand side or the right hand side of a /// binary operator matches. inline internal::Matcher<BinaryOperator> hasEitherOperand( const internal::Matcher<Expr> &InnerMatcher) { return anyOf(hasLHS(InnerMatcher), hasRHS(InnerMatcher)); } /// \brief Matches if the operand of a unary operator matches. /// /// Example matches true (matcher = hasUnaryOperand(boolLiteral(equals(true)))) /// \code /// !true /// \endcode AST_MATCHER_P(UnaryOperator, hasUnaryOperand, internal::Matcher<Expr>, InnerMatcher) { const Expr * const Operand = Node.getSubExpr(); return (Operand != nullptr && InnerMatcher.matches(*Operand, Finder, Builder)); } /// \brief Matches if the cast's source expression matches the given matcher. /// /// Example: matches "a string" (matcher = /// hasSourceExpression(constructExpr())) /// \code /// class URL { URL(string); }; /// URL url = "a string"; AST_MATCHER_P(CastExpr, hasSourceExpression, internal::Matcher<Expr>, InnerMatcher) { const Expr* const SubExpression = Node.getSubExpr(); return (SubExpression != nullptr && InnerMatcher.matches(*SubExpression, Finder, Builder)); } /// \brief Matches casts whose destination type matches a given matcher. /// /// (Note: Clang's AST refers to other conversions as "casts" too, and calls /// actual casts "explicit" casts.) AST_MATCHER_P(ExplicitCastExpr, hasDestinationType, internal::Matcher<QualType>, InnerMatcher) { const QualType NodeType = Node.getTypeAsWritten(); return InnerMatcher.matches(NodeType, Finder, Builder); } /// \brief Matches implicit casts whose destination type matches a given /// matcher. /// /// FIXME: Unit test this matcher AST_MATCHER_P(ImplicitCastExpr, hasImplicitDestinationType, internal::Matcher<QualType>, InnerMatcher) { return InnerMatcher.matches(Node.getType(), Finder, Builder); } /// \brief Matches the true branch expression of a conditional operator. /// /// Example matches a /// \code /// condition ? a : b /// \endcode AST_MATCHER_P(ConditionalOperator, hasTrueExpression, internal::Matcher<Expr>, InnerMatcher) { Expr *Expression = Node.getTrueExpr(); return (Expression != nullptr && InnerMatcher.matches(*Expression, Finder, Builder)); } /// \brief Matches the false branch expression of a conditional operator. /// /// Example matches b /// \code /// condition ? a : b /// \endcode AST_MATCHER_P(ConditionalOperator, hasFalseExpression, internal::Matcher<Expr>, InnerMatcher) { Expr *Expression = Node.getFalseExpr(); return (Expression != nullptr && InnerMatcher.matches(*Expression, Finder, Builder)); } /// \brief Matches if a declaration has a body attached. /// /// Example matches A, va, fa /// \code /// class A {}; /// class B; // Doesn't match, as it has no body. /// int va; /// extern int vb; // Doesn't match, as it doesn't define the variable. /// void fa() {} /// void fb(); // Doesn't match, as it has no body. /// \endcode /// /// Usable as: Matcher<TagDecl>, Matcher<VarDecl>, Matcher<FunctionDecl> AST_POLYMORPHIC_MATCHER(isDefinition, AST_POLYMORPHIC_SUPPORTED_TYPES(TagDecl, VarDecl, FunctionDecl)) { return Node.isThisDeclarationADefinition(); } /// \brief Matches the class declaration that the given method declaration /// belongs to. /// /// FIXME: Generalize this for other kinds of declarations. /// FIXME: What other kind of declarations would we need to generalize /// this to? /// /// Example matches A() in the last line /// (matcher = constructExpr(hasDeclaration(methodDecl( /// ofClass(hasName("A")))))) /// \code /// class A { /// public: /// A(); /// }; /// A a = A(); /// \endcode AST_MATCHER_P(CXXMethodDecl, ofClass, internal::Matcher<CXXRecordDecl>, InnerMatcher) { const CXXRecordDecl *Parent = Node.getParent(); return (Parent != nullptr && InnerMatcher.matches(*Parent, Finder, Builder)); } /// \brief Matches if the given method declaration is virtual. /// /// Given /// \code /// class A { /// public: /// virtual void x(); /// }; /// \endcode /// matches A::x AST_MATCHER(CXXMethodDecl, isVirtual) { return Node.isVirtual(); } /// \brief Matches if the given method declaration is pure. /// /// Given /// \code /// class A { /// public: /// virtual void x() = 0; /// }; /// \endcode /// matches A::x AST_MATCHER(CXXMethodDecl, isPure) { return Node.isPure(); } /// \brief Matches if the given method declaration is const. /// /// Given /// \code /// struct A { /// void foo() const; /// void bar(); /// }; /// \endcode /// /// methodDecl(isConst()) matches A::foo() but not A::bar() AST_MATCHER(CXXMethodDecl, isConst) { return Node.isConst(); } /// \brief Matches if the given method declaration overrides another method. /// /// Given /// \code /// class A { /// public: /// virtual void x(); /// }; /// class B : public A { /// public: /// virtual void x(); /// }; /// \endcode /// matches B::x AST_MATCHER(CXXMethodDecl, isOverride) { return Node.size_overridden_methods() > 0 || Node.hasAttr<OverrideAttr>(); } /// \brief Matches member expressions that are called with '->' as opposed /// to '.'. /// /// Member calls on the implicit this pointer match as called with '->'. /// /// Given /// \code /// class Y { /// void x() { this->x(); x(); Y y; y.x(); a; this->b; Y::b; } /// int a; /// static int b; /// }; /// \endcode /// memberExpr(isArrow()) /// matches this->x, x, y.x, a, this->b AST_MATCHER(MemberExpr, isArrow) { return Node.isArrow(); } /// \brief Matches QualType nodes that are of integer type. /// /// Given /// \code /// void a(int); /// void b(long); /// void c(double); /// \endcode /// functionDecl(hasAnyParameter(hasType(isInteger()))) /// matches "a(int)", "b(long)", but not "c(double)". AST_MATCHER(QualType, isInteger) { return Node->isIntegerType(); } /// \brief Matches QualType nodes that are const-qualified, i.e., that /// include "top-level" const. /// /// Given /// \code /// void a(int); /// void b(int const); /// void c(const int); /// void d(const int*); /// void e(int const) {}; /// \endcode /// functionDecl(hasAnyParameter(hasType(isConstQualified()))) /// matches "void b(int const)", "void c(const int)" and /// "void e(int const) {}". It does not match d as there /// is no top-level const on the parameter type "const int *". AST_MATCHER(QualType, isConstQualified) { return Node.isConstQualified(); } /// \brief Matches QualType nodes that have local CV-qualifiers attached to /// the node, not hidden within a typedef. /// /// Given /// \code /// typedef const int const_int; /// const_int i; /// int *const j; /// int *volatile k; /// int m; /// \endcode /// \c varDecl(hasType(hasLocalQualifiers())) matches only \c j and \c k. /// \c i is const-qualified but the qualifier is not local. AST_MATCHER(QualType, hasLocalQualifiers) { return Node.hasLocalQualifiers(); } /// \brief Matches a member expression where the member is matched by a /// given matcher. /// /// Given /// \code /// struct { int first, second; } first, second; /// int i(second.first); /// int j(first.second); /// \endcode /// memberExpr(member(hasName("first"))) /// matches second.first /// but not first.second (because the member name there is "second"). AST_MATCHER_P(MemberExpr, member, internal::Matcher<ValueDecl>, InnerMatcher) { return InnerMatcher.matches(*Node.getMemberDecl(), Finder, Builder); } /// \brief Matches a member expression where the object expression is /// matched by a given matcher. /// /// Given /// \code /// struct X { int m; }; /// void f(X x) { x.m; m; } /// \endcode /// memberExpr(hasObjectExpression(hasType(recordDecl(hasName("X"))))))) /// matches "x.m" and "m" /// with hasObjectExpression(...) /// matching "x" and the implicit object expression of "m" which has type X*. AST_MATCHER_P(MemberExpr, hasObjectExpression, internal::Matcher<Expr>, InnerMatcher) { return InnerMatcher.matches(*Node.getBase(), Finder, Builder); } /// \brief Matches any using shadow declaration. /// /// Given /// \code /// namespace X { void b(); } /// using X::b; /// \endcode /// usingDecl(hasAnyUsingShadowDecl(hasName("b")))) /// matches \code using X::b \endcode AST_MATCHER_P(UsingDecl, hasAnyUsingShadowDecl, internal::Matcher<UsingShadowDecl>, InnerMatcher) { return matchesFirstInPointerRange(InnerMatcher, Node.shadow_begin(), Node.shadow_end(), Finder, Builder); } /// \brief Matches a using shadow declaration where the target declaration is /// matched by the given matcher. /// /// Given /// \code /// namespace X { int a; void b(); } /// using X::a; /// using X::b; /// \endcode /// usingDecl(hasAnyUsingShadowDecl(hasTargetDecl(functionDecl()))) /// matches \code using X::b \endcode /// but not \code using X::a \endcode AST_MATCHER_P(UsingShadowDecl, hasTargetDecl, internal::Matcher<NamedDecl>, InnerMatcher) { return InnerMatcher.matches(*Node.getTargetDecl(), Finder, Builder); } /// \brief Matches template instantiations of function, class, or static /// member variable template instantiations. /// /// Given /// \code /// template <typename T> class X {}; class A {}; X<A> x; /// \endcode /// or /// \code /// template <typename T> class X {}; class A {}; template class X<A>; /// \endcode /// recordDecl(hasName("::X"), isTemplateInstantiation()) /// matches the template instantiation of X<A>. /// /// But given /// \code /// template <typename T> class X {}; class A {}; /// template <> class X<A> {}; X<A> x; /// \endcode /// recordDecl(hasName("::X"), isTemplateInstantiation()) /// does not match, as X<A> is an explicit template specialization. /// /// Usable as: Matcher<FunctionDecl>, Matcher<VarDecl>, Matcher<CXXRecordDecl> AST_POLYMORPHIC_MATCHER(isTemplateInstantiation, AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl, VarDecl, CXXRecordDecl)) { return (Node.getTemplateSpecializationKind() == TSK_ImplicitInstantiation || Node.getTemplateSpecializationKind() == TSK_ExplicitInstantiationDefinition); } /// \brief Matches declarations that are template instantiations or are inside /// template instantiations. /// /// Given /// \code /// template<typename T> void A(T t) { T i; } /// A(0); /// A(0U); /// \endcode /// functionDecl(isInstantiated()) /// matches 'A(int) {...};' and 'A(unsigned) {...}'. AST_MATCHER_FUNCTION(internal::Matcher<Decl>, isInstantiated) { auto IsInstantiation = decl(anyOf(recordDecl(isTemplateInstantiation()), functionDecl(isTemplateInstantiation()))); return decl(anyOf(IsInstantiation, hasAncestor(IsInstantiation))); } /// \brief Matches statements inside of a template instantiation. /// /// Given /// \code /// int j; /// template<typename T> void A(T t) { T i; j += 42;} /// A(0); /// A(0U); /// \endcode /// declStmt(isInTemplateInstantiation()) /// matches 'int i;' and 'unsigned i'. /// unless(stmt(isInTemplateInstantiation())) /// will NOT match j += 42; as it's shared between the template definition and /// instantiation. AST_MATCHER_FUNCTION(internal::Matcher<Stmt>, isInTemplateInstantiation) { return stmt( hasAncestor(decl(anyOf(recordDecl(isTemplateInstantiation()), functionDecl(isTemplateInstantiation()))))); } /// \brief Matches explicit template specializations of function, class, or /// static member variable template instantiations. /// /// Given /// \code /// template<typename T> void A(T t) { } /// template<> void A(int N) { } /// \endcode /// functionDecl(isExplicitTemplateSpecialization()) /// matches the specialization A<int>(). /// /// Usable as: Matcher<FunctionDecl>, Matcher<VarDecl>, Matcher<CXXRecordDecl> AST_POLYMORPHIC_MATCHER(isExplicitTemplateSpecialization, AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl, VarDecl, CXXRecordDecl)) { return (Node.getTemplateSpecializationKind() == TSK_ExplicitSpecialization); } /// \brief Matches \c TypeLocs for which the given inner /// QualType-matcher matches. AST_MATCHER_FUNCTION_P_OVERLOAD(internal::BindableMatcher<TypeLoc>, loc, internal::Matcher<QualType>, InnerMatcher, 0) { return internal::BindableMatcher<TypeLoc>( new internal::TypeLocTypeMatcher(InnerMatcher)); } /// \brief Matches type \c void. /// /// Given /// \code /// struct S { void func(); }; /// \endcode /// functionDecl(returns(voidType())) /// matches "void func();" AST_MATCHER(Type, voidType) { return Node.isVoidType(); } /// \brief Matches builtin Types. /// /// Given /// \code /// struct A {}; /// A a; /// int b; /// float c; /// bool d; /// \endcode /// builtinType() /// matches "int b", "float c" and "bool d" AST_TYPE_MATCHER(BuiltinType, builtinType); /// \brief Matches all kinds of arrays. /// /// Given /// \code /// int a[] = { 2, 3 }; /// int b[4]; /// void f() { int c[a[0]]; } /// \endcode /// arrayType() /// matches "int a[]", "int b[4]" and "int c[a[0]]"; AST_TYPE_MATCHER(ArrayType, arrayType); /// \brief Matches C99 complex types. /// /// Given /// \code /// _Complex float f; /// \endcode /// complexType() /// matches "_Complex float f" AST_TYPE_MATCHER(ComplexType, complexType); /// \brief Matches arrays and C99 complex types that have a specific element /// type. /// /// Given /// \code /// struct A {}; /// A a[7]; /// int b[7]; /// \endcode /// arrayType(hasElementType(builtinType())) /// matches "int b[7]" /// /// Usable as: Matcher<ArrayType>, Matcher<ComplexType> AST_TYPELOC_TRAVERSE_MATCHER(hasElementType, getElement, AST_POLYMORPHIC_SUPPORTED_TYPES(ArrayType, ComplexType)); /// \brief Matches C arrays with a specified constant size. /// /// Given /// \code /// void() { /// int a[2]; /// int b[] = { 2, 3 }; /// int c[b[0]]; /// } /// \endcode /// constantArrayType() /// matches "int a[2]" AST_TYPE_MATCHER(ConstantArrayType, constantArrayType); /// \brief Matches \c ConstantArrayType nodes that have the specified size. /// /// Given /// \code /// int a[42]; /// int b[2 * 21]; /// int c[41], d[43]; /// \endcode /// constantArrayType(hasSize(42)) /// matches "int a[42]" and "int b[2 * 21]" AST_MATCHER_P(ConstantArrayType, hasSize, unsigned, N) { return Node.getSize() == N; } /// \brief Matches C++ arrays whose size is a value-dependent expression. /// /// Given /// \code /// template<typename T, int Size> /// class array { /// T data[Size]; /// }; /// \endcode /// dependentSizedArrayType /// matches "T data[Size]" AST_TYPE_MATCHER(DependentSizedArrayType, dependentSizedArrayType); /// \brief Matches C arrays with unspecified size. /// /// Given /// \code /// int a[] = { 2, 3 }; /// int b[42]; /// void f(int c[]) { int d[a[0]]; }; /// \endcode /// incompleteArrayType() /// matches "int a[]" and "int c[]" AST_TYPE_MATCHER(IncompleteArrayType, incompleteArrayType); /// \brief Matches C arrays with a specified size that is not an /// integer-constant-expression. /// /// Given /// \code /// void f() { /// int a[] = { 2, 3 } /// int b[42]; /// int c[a[0]]; /// } /// \endcode /// variableArrayType() /// matches "int c[a[0]]" AST_TYPE_MATCHER(VariableArrayType, variableArrayType); /// \brief Matches \c VariableArrayType nodes that have a specific size /// expression. /// /// Given /// \code /// void f(int b) { /// int a[b]; /// } /// \endcode /// variableArrayType(hasSizeExpr(ignoringImpCasts(declRefExpr(to( /// varDecl(hasName("b"))))))) /// matches "int a[b]" AST_MATCHER_P(VariableArrayType, hasSizeExpr, internal::Matcher<Expr>, InnerMatcher) { return InnerMatcher.matches(*Node.getSizeExpr(), Finder, Builder); } /// \brief Matches atomic types. /// /// Given /// \code /// _Atomic(int) i; /// \endcode /// atomicType() /// matches "_Atomic(int) i" AST_TYPE_MATCHER(AtomicType, atomicType); /// \brief Matches atomic types with a specific value type. /// /// Given /// \code /// _Atomic(int) i; /// _Atomic(float) f; /// \endcode /// atomicType(hasValueType(isInteger())) /// matches "_Atomic(int) i" /// /// Usable as: Matcher<AtomicType> AST_TYPELOC_TRAVERSE_MATCHER(hasValueType, getValue, AST_POLYMORPHIC_SUPPORTED_TYPES(AtomicType)); /// \brief Matches types nodes representing C++11 auto types. /// /// Given: /// \code /// auto n = 4; /// int v[] = { 2, 3 } /// for (auto i : v) { } /// \endcode /// autoType() /// matches "auto n" and "auto i" AST_TYPE_MATCHER(AutoType, autoType); /// \brief Matches \c AutoType nodes where the deduced type is a specific type. /// /// Note: There is no \c TypeLoc for the deduced type and thus no /// \c getDeducedLoc() matcher. /// /// Given /// \code /// auto a = 1; /// auto b = 2.0; /// \endcode /// autoType(hasDeducedType(isInteger())) /// matches "auto a" /// /// Usable as: Matcher<AutoType> AST_TYPE_TRAVERSE_MATCHER(hasDeducedType, getDeducedType, AST_POLYMORPHIC_SUPPORTED_TYPES(AutoType)); /// \brief Matches \c FunctionType nodes. /// /// Given /// \code /// int (*f)(int); /// void g(); /// \endcode /// functionType() /// matches "int (*f)(int)" and the type of "g". AST_TYPE_MATCHER(FunctionType, functionType); /// \brief Matches \c ParenType nodes. /// /// Given /// \code /// int (*ptr_to_array)[4]; /// int *array_of_ptrs[4]; /// \endcode /// /// \c varDecl(hasType(pointsTo(parenType()))) matches \c ptr_to_array but not /// \c array_of_ptrs. AST_TYPE_MATCHER(ParenType, parenType); /// \brief Matches \c ParenType nodes where the inner type is a specific type. /// /// Given /// \code /// int (*ptr_to_array)[4]; /// int (*ptr_to_func)(int); /// \endcode /// /// \c varDecl(hasType(pointsTo(parenType(innerType(functionType()))))) matches /// \c ptr_to_func but not \c ptr_to_array. /// /// Usable as: Matcher<ParenType> AST_TYPE_TRAVERSE_MATCHER(innerType, getInnerType, AST_POLYMORPHIC_SUPPORTED_TYPES(ParenType)); /// \brief Matches block pointer types, i.e. types syntactically represented as /// "void (^)(int)". /// /// The \c pointee is always required to be a \c FunctionType. AST_TYPE_MATCHER(BlockPointerType, blockPointerType); /// \brief Matches member pointer types. /// Given /// \code /// struct A { int i; } /// A::* ptr = A::i; /// \endcode /// memberPointerType() /// matches "A::* ptr" AST_TYPE_MATCHER(MemberPointerType, memberPointerType); /// \brief Matches pointer types. /// /// Given /// \code /// int *a; /// int &b = *a; /// int c = 5; /// \endcode /// pointerType() /// matches "int *a" AST_TYPE_MATCHER(PointerType, pointerType); /// \brief Matches both lvalue and rvalue reference types. /// /// Given /// \code /// int *a; /// int &b = *a; /// int &&c = 1; /// auto &d = b; /// auto &&e = c; /// auto &&f = 2; /// int g = 5; /// \endcode /// /// \c referenceType() matches the types of \c b, \c c, \c d, \c e, and \c f. AST_TYPE_MATCHER(ReferenceType, referenceType); /// \brief Matches lvalue reference types. /// /// Given: /// \code /// int *a; /// int &b = *a; /// int &&c = 1; /// auto &d = b; /// auto &&e = c; /// auto &&f = 2; /// int g = 5; /// \endcode /// /// \c lValueReferenceType() matches the types of \c b, \c d, and \c e. \c e is /// matched since the type is deduced as int& by reference collapsing rules. AST_TYPE_MATCHER(LValueReferenceType, lValueReferenceType); /// \brief Matches rvalue reference types. /// /// Given: /// \code /// int *a; /// int &b = *a; /// int &&c = 1; /// auto &d = b; /// auto &&e = c; /// auto &&f = 2; /// int g = 5; /// \endcode /// /// \c rValueReferenceType() matches the types of \c c and \c f. \c e is not /// matched as it is deduced to int& by reference collapsing rules. AST_TYPE_MATCHER(RValueReferenceType, rValueReferenceType); /// \brief Narrows PointerType (and similar) matchers to those where the /// \c pointee matches a given matcher. /// /// Given /// \code /// int *a; /// int const *b; /// float const *f; /// \endcode /// pointerType(pointee(isConstQualified(), isInteger())) /// matches "int const *b" /// /// Usable as: Matcher<BlockPointerType>, Matcher<MemberPointerType>, /// Matcher<PointerType>, Matcher<ReferenceType> AST_TYPELOC_TRAVERSE_MATCHER(pointee, getPointee, AST_POLYMORPHIC_SUPPORTED_TYPES(BlockPointerType, MemberPointerType, PointerType, ReferenceType)); /// \brief Matches typedef types. /// /// Given /// \code /// typedef int X; /// \endcode /// typedefType() /// matches "typedef int X" AST_TYPE_MATCHER(TypedefType, typedefType); /// \brief Matches template specialization types. /// /// Given /// \code /// template <typename T> /// class C { }; /// /// template class C<int>; // A /// C<char> var; // B /// \code /// /// \c templateSpecializationType() matches the type of the explicit /// instantiation in \c A and the type of the variable declaration in \c B. AST_TYPE_MATCHER(TemplateSpecializationType, templateSpecializationType); /// \brief Matches types nodes representing unary type transformations. /// /// Given: /// \code /// typedef __underlying_type(T) type; /// \endcode /// unaryTransformType() /// matches "__underlying_type(T)" AST_TYPE_MATCHER(UnaryTransformType, unaryTransformType); /// \brief Matches record types (e.g. structs, classes). /// /// Given /// \code /// class C {}; /// struct S {}; /// /// C c; /// S s; /// \code /// /// \c recordType() matches the type of the variable declarations of both \c c /// and \c s. AST_TYPE_MATCHER(RecordType, recordType); /// \brief Matches types specified with an elaborated type keyword or with a /// qualified name. /// /// Given /// \code /// namespace N { /// namespace M { /// class D {}; /// } /// } /// class C {}; /// /// class C c; /// N::M::D d; /// \code /// /// \c elaboratedType() matches the type of the variable declarations of both /// \c c and \c d. AST_TYPE_MATCHER(ElaboratedType, elaboratedType); /// \brief Matches ElaboratedTypes whose qualifier, a NestedNameSpecifier, /// matches \c InnerMatcher if the qualifier exists. /// /// Given /// \code /// namespace N { /// namespace M { /// class D {}; /// } /// } /// N::M::D d; /// \code /// /// \c elaboratedType(hasQualifier(hasPrefix(specifiesNamespace(hasName("N")))) /// matches the type of the variable declaration of \c d. AST_MATCHER_P(ElaboratedType, hasQualifier, internal::Matcher<NestedNameSpecifier>, InnerMatcher) { if (const NestedNameSpecifier *Qualifier = Node.getQualifier()) return InnerMatcher.matches(*Qualifier, Finder, Builder); return false; } /// \brief Matches ElaboratedTypes whose named type matches \c InnerMatcher. /// /// Given /// \code /// namespace N { /// namespace M { /// class D {}; /// } /// } /// N::M::D d; /// \code /// /// \c elaboratedType(namesType(recordType( /// hasDeclaration(namedDecl(hasName("D")))))) matches the type of the variable /// declaration of \c d. AST_MATCHER_P(ElaboratedType, namesType, internal::Matcher<QualType>, InnerMatcher) { return InnerMatcher.matches(Node.getNamedType(), Finder, Builder); } /// \brief Matches declarations whose declaration context, interpreted as a /// Decl, matches \c InnerMatcher. /// /// Given /// \code /// namespace N { /// namespace M { /// class D {}; /// } /// } /// \code /// /// \c recordDecl(hasDeclContext(namedDecl(hasName("M")))) matches the /// declaration of \c class \c D. AST_MATCHER_P(Decl, hasDeclContext, internal::Matcher<Decl>, InnerMatcher) { const DeclContext *DC = Node.getDeclContext(); if (!DC) return false; return InnerMatcher.matches(*Decl::castFromDeclContext(DC), Finder, Builder); } /// \brief Matches nested name specifiers. /// /// Given /// \code /// namespace ns { /// struct A { static void f(); }; /// void A::f() {} /// void g() { A::f(); } /// } /// ns::A a; /// \endcode /// nestedNameSpecifier() /// matches "ns::" and both "A::" const internal::VariadicAllOfMatcher<NestedNameSpecifier> nestedNameSpecifier; /// \brief Same as \c nestedNameSpecifier but matches \c NestedNameSpecifierLoc. const internal::VariadicAllOfMatcher< NestedNameSpecifierLoc> nestedNameSpecifierLoc; /// \brief Matches \c NestedNameSpecifierLocs for which the given inner /// NestedNameSpecifier-matcher matches. AST_MATCHER_FUNCTION_P_OVERLOAD( internal::BindableMatcher<NestedNameSpecifierLoc>, loc, internal::Matcher<NestedNameSpecifier>, InnerMatcher, 1) { return internal::BindableMatcher<NestedNameSpecifierLoc>( new internal::LocMatcher<NestedNameSpecifierLoc, NestedNameSpecifier>( InnerMatcher)); } /// \brief Matches nested name specifiers that specify a type matching the /// given \c QualType matcher without qualifiers. /// /// Given /// \code /// struct A { struct B { struct C {}; }; }; /// A::B::C c; /// \endcode /// nestedNameSpecifier(specifiesType(hasDeclaration(recordDecl(hasName("A"))))) /// matches "A::" AST_MATCHER_P(NestedNameSpecifier, specifiesType, internal::Matcher<QualType>, InnerMatcher) { if (!Node.getAsType()) return false; return InnerMatcher.matches(QualType(Node.getAsType(), 0), Finder, Builder); } /// \brief Matches nested name specifier locs that specify a type matching the /// given \c TypeLoc. /// /// Given /// \code /// struct A { struct B { struct C {}; }; }; /// A::B::C c; /// \endcode /// nestedNameSpecifierLoc(specifiesTypeLoc(loc(type( /// hasDeclaration(recordDecl(hasName("A"))))))) /// matches "A::" AST_MATCHER_P(NestedNameSpecifierLoc, specifiesTypeLoc, internal::Matcher<TypeLoc>, InnerMatcher) { return Node && InnerMatcher.matches(Node.getTypeLoc(), Finder, Builder); } /// \brief Matches on the prefix of a \c NestedNameSpecifier. /// /// Given /// \code /// struct A { struct B { struct C {}; }; }; /// A::B::C c; /// \endcode /// nestedNameSpecifier(hasPrefix(specifiesType(asString("struct A")))) and /// matches "A::" AST_MATCHER_P_OVERLOAD(NestedNameSpecifier, hasPrefix, internal::Matcher<NestedNameSpecifier>, InnerMatcher, 0) { NestedNameSpecifier *NextNode = Node.getPrefix(); if (!NextNode) return false; return InnerMatcher.matches(*NextNode, Finder, Builder); } /// \brief Matches on the prefix of a \c NestedNameSpecifierLoc. /// /// Given /// \code /// struct A { struct B { struct C {}; }; }; /// A::B::C c; /// \endcode /// nestedNameSpecifierLoc(hasPrefix(loc(specifiesType(asString("struct A"))))) /// matches "A::" AST_MATCHER_P_OVERLOAD(NestedNameSpecifierLoc, hasPrefix, internal::Matcher<NestedNameSpecifierLoc>, InnerMatcher, 1) { NestedNameSpecifierLoc NextNode = Node.getPrefix(); if (!NextNode) return false; return InnerMatcher.matches(NextNode, Finder, Builder); } /// \brief Matches nested name specifiers that specify a namespace matching the /// given namespace matcher. /// /// Given /// \code /// namespace ns { struct A {}; } /// ns::A a; /// \endcode /// nestedNameSpecifier(specifiesNamespace(hasName("ns"))) /// matches "ns::" AST_MATCHER_P(NestedNameSpecifier, specifiesNamespace, internal::Matcher<NamespaceDecl>, InnerMatcher) { if (!Node.getAsNamespace()) return false; return InnerMatcher.matches(*Node.getAsNamespace(), Finder, Builder); } /// \brief Overloads for the \c equalsNode matcher. /// FIXME: Implement for other node types. /// @{ /// \brief Matches if a node equals another node. /// /// \c Decl has pointer identity in the AST. AST_MATCHER_P_OVERLOAD(Decl, equalsNode, const Decl*, Other, 0) { return &Node == Other; } /// \brief Matches if a node equals another node. /// /// \c Stmt has pointer identity in the AST. /// AST_MATCHER_P_OVERLOAD(Stmt, equalsNode, const Stmt*, Other, 1) { return &Node == Other; } /// @} /// \brief Matches each case or default statement belonging to the given switch /// statement. This matcher may produce multiple matches. /// /// Given /// \code /// switch (1) { case 1: case 2: default: switch (2) { case 3: case 4: ; } } /// \endcode /// switchStmt(forEachSwitchCase(caseStmt().bind("c"))).bind("s") /// matches four times, with "c" binding each of "case 1:", "case 2:", /// "case 3:" and "case 4:", and "s" respectively binding "switch (1)", /// "switch (1)", "switch (2)" and "switch (2)". AST_MATCHER_P(SwitchStmt, forEachSwitchCase, internal::Matcher<SwitchCase>, InnerMatcher) { BoundNodesTreeBuilder Result; // FIXME: getSwitchCaseList() does not necessarily guarantee a stable // iteration order. We should use the more general iterating matchers once // they are capable of expressing this matcher (for example, it should ignore // case statements belonging to nested switch statements). bool Matched = false; for (const SwitchCase *SC = Node.getSwitchCaseList(); SC; SC = SC->getNextSwitchCase()) { BoundNodesTreeBuilder CaseBuilder(*Builder); bool CaseMatched = InnerMatcher.matches(*SC, Finder, &CaseBuilder); if (CaseMatched) { Matched = true; Result.addMatch(CaseBuilder); } } *Builder = std::move(Result); return Matched; } /// \brief Matches each constructor initializer in a constructor definition. /// /// Given /// \code /// class A { A() : i(42), j(42) {} int i; int j; }; /// \endcode /// constructorDecl(forEachConstructorInitializer(forField(decl().bind("x")))) /// will trigger two matches, binding for 'i' and 'j' respectively. AST_MATCHER_P(CXXConstructorDecl, forEachConstructorInitializer, internal::Matcher<CXXCtorInitializer>, InnerMatcher) { BoundNodesTreeBuilder Result; bool Matched = false; for (const auto *I : Node.inits()) { BoundNodesTreeBuilder InitBuilder(*Builder); if (InnerMatcher.matches(*I, Finder, &InitBuilder)) { Matched = true; Result.addMatch(InitBuilder); } } *Builder = std::move(Result); return Matched; } /// \brief If the given case statement does not use the GNU case range /// extension, matches the constant given in the statement. /// /// Given /// \code /// switch (1) { case 1: case 1+1: case 3 ... 4: ; } /// \endcode /// caseStmt(hasCaseConstant(integerLiteral())) /// matches "case 1:" AST_MATCHER_P(CaseStmt, hasCaseConstant, internal::Matcher<Expr>, InnerMatcher) { if (Node.getRHS()) return false; return InnerMatcher.matches(*Node.getLHS(), Finder, Builder); } /// \brief Matches declaration that has a given attribute. /// /// Given /// \code /// __attribute__((device)) void f() { ... } /// \endcode /// decl(hasAttr(clang::attr::CUDADevice)) matches the function declaration of /// f. AST_MATCHER_P(Decl, hasAttr, attr::Kind, AttrKind) { for (const auto *Attr : Node.attrs()) { if (Attr->getKind() == AttrKind) return true; } return false; } /// \brief Matches CUDA kernel call expression. /// /// Example matches, /// \code /// kernel<<<i,j>>>(); /// \endcode const internal::VariadicDynCastAllOfMatcher<Stmt, CUDAKernelCallExpr> CUDAKernelCallExpr; } // end namespace ast_matchers } // end namespace clang #endif
0
repos/DirectXShaderCompiler/tools/clang/include/clang/ASTMatchers
repos/DirectXShaderCompiler/tools/clang/include/clang/ASTMatchers/Dynamic/Registry.h
//===--- Registry.h - Matcher registry -----*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// /// /// \file /// \brief Registry of all known matchers. /// /// The registry provides a generic interface to construct any matcher by name. /// //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_ASTMATCHERS_DYNAMIC_REGISTRY_H #define LLVM_CLANG_ASTMATCHERS_DYNAMIC_REGISTRY_H #include "clang/ASTMatchers/Dynamic/Diagnostics.h" #include "clang/ASTMatchers/Dynamic/VariantValue.h" #include "clang/Basic/LLVM.h" #include "llvm/ADT/ArrayRef.h" #include "llvm/ADT/Optional.h" #include "llvm/ADT/StringRef.h" namespace clang { namespace ast_matchers { namespace dynamic { namespace internal { class MatcherDescriptor; } typedef const internal::MatcherDescriptor *MatcherCtor; struct MatcherCompletion { MatcherCompletion() {} MatcherCompletion(StringRef TypedText, StringRef MatcherDecl, unsigned Specificity) : TypedText(TypedText), MatcherDecl(MatcherDecl), Specificity(Specificity) {} /// \brief The text to type to select this matcher. std::string TypedText; /// \brief The "declaration" of the matcher, with type information. std::string MatcherDecl; /// \brief Value corresponding to the "specificity" of the converted matcher. /// /// Zero specificity indicates that this conversion would produce a trivial /// matcher that will either always or never match. /// Such matchers are excluded from code completion results. unsigned Specificity; bool operator==(const MatcherCompletion &Other) const { return TypedText == Other.TypedText && MatcherDecl == Other.MatcherDecl; } }; class Registry { public: /// \brief Look up a matcher in the registry by name, /// /// \return An opaque value which may be used to refer to the matcher /// constructor, or Optional<MatcherCtor>() if not found. static llvm::Optional<MatcherCtor> lookupMatcherCtor(StringRef MatcherName); /// \brief Compute the list of completion types for \p Context. /// /// Each element of \p Context represents a matcher invocation, going from /// outermost to innermost. Elements are pairs consisting of a reference to /// the matcher constructor and the index of the next element in the /// argument list of that matcher (or for the last element, the index of /// the completion point in the argument list). An empty list requests /// completion for the root matcher. static std::vector<ArgKind> getAcceptedCompletionTypes( llvm::ArrayRef<std::pair<MatcherCtor, unsigned>> Context); /// \brief Compute the list of completions that match any of /// \p AcceptedTypes. /// /// \param AcceptedTypes All types accepted for this completion. /// /// \return All completions for the specified types. /// Completions should be valid when used in \c lookupMatcherCtor(). /// The matcher constructed from the return of \c lookupMatcherCtor() /// should be convertible to some type in \p AcceptedTypes. static std::vector<MatcherCompletion> getMatcherCompletions(ArrayRef<ArgKind> AcceptedTypes); /// \brief Construct a matcher from the registry. /// /// \param Ctor The matcher constructor to instantiate. /// /// \param NameRange The location of the name in the matcher source. /// Useful for error reporting. /// /// \param Args The argument list for the matcher. The number and types of the /// values must be valid for the matcher requested. Otherwise, the function /// will return an error. /// /// \return The matcher object constructed if no error was found. /// A null matcher if the number of arguments or argument types do not match /// the signature. In that case \c Error will contain the description of /// the error. static VariantMatcher constructMatcher(MatcherCtor Ctor, const SourceRange &NameRange, ArrayRef<ParserValue> Args, Diagnostics *Error); /// \brief Construct a matcher from the registry and bind it. /// /// Similar the \c constructMatcher() above, but it then tries to bind the /// matcher to the specified \c BindID. /// If the matcher is not bindable, it sets an error in \c Error and returns /// a null matcher. static VariantMatcher constructBoundMatcher(MatcherCtor Ctor, const SourceRange &NameRange, StringRef BindID, ArrayRef<ParserValue> Args, Diagnostics *Error); private: Registry() = delete; }; } // namespace dynamic } // namespace ast_matchers } // namespace clang #endif // LLVM_CLANG_AST_MATCHERS_DYNAMIC_REGISTRY_H
0
repos/DirectXShaderCompiler/tools/clang/include/clang/ASTMatchers
repos/DirectXShaderCompiler/tools/clang/include/clang/ASTMatchers/Dynamic/Parser.h
//===--- Parser.h - Matcher expression parser -----*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// /// /// \file /// \brief Simple matcher expression parser. /// /// The parser understands matcher expressions of the form: /// MatcherName(Arg0, Arg1, ..., ArgN) /// as well as simple types like strings. /// The parser does not know how to process the matchers. It delegates this task /// to a Sema object received as an argument. /// /// \code /// Grammar for the expressions supported: /// <Expression> := <Literal> | <NamedValue> | <MatcherExpression> /// <Literal> := <StringLiteral> | <Unsigned> /// <StringLiteral> := "quoted string" /// <Unsigned> := [0-9]+ /// <NamedValue> := <Identifier> /// <MatcherExpression> := <Identifier>(<ArgumentList>) | /// <Identifier>(<ArgumentList>).bind(<StringLiteral>) /// <Identifier> := [a-zA-Z]+ /// <ArgumentList> := <Expression> | <Expression>,<ArgumentList> /// \endcode /// //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_ASTMATCHERS_DYNAMIC_PARSER_H #define LLVM_CLANG_ASTMATCHERS_DYNAMIC_PARSER_H #include "clang/ASTMatchers/Dynamic/Diagnostics.h" #include "clang/ASTMatchers/Dynamic/Registry.h" #include "clang/ASTMatchers/Dynamic/VariantValue.h" #include "clang/Basic/LLVM.h" #include "llvm/ADT/ArrayRef.h" #include "llvm/ADT/Optional.h" #include "llvm/ADT/StringRef.h" namespace clang { namespace ast_matchers { namespace dynamic { /// \brief Matcher expression parser. class Parser { public: /// \brief Interface to connect the parser with the registry and more. /// /// The parser uses the Sema instance passed into /// parseMatcherExpression() to handle all matcher tokens. The simplest /// processor implementation would simply call into the registry to create /// the matchers. /// However, a more complex processor might decide to intercept the matcher /// creation and do some extra work. For example, it could apply some /// transformation to the matcher by adding some id() nodes, or could detect /// specific matcher nodes for more efficient lookup. class Sema { public: virtual ~Sema(); /// \brief Process a matcher expression. /// /// All the arguments passed here have already been processed. /// /// \param Ctor A matcher constructor looked up by lookupMatcherCtor. /// /// \param NameRange The location of the name in the matcher source. /// Useful for error reporting. /// /// \param BindID The ID to use to bind the matcher, or a null \c StringRef /// if no ID is specified. /// /// \param Args The argument list for the matcher. /// /// \return The matcher objects constructed by the processor, or a null /// matcher if an error occurred. In that case, \c Error will contain a /// description of the error. virtual VariantMatcher actOnMatcherExpression(MatcherCtor Ctor, const SourceRange &NameRange, StringRef BindID, ArrayRef<ParserValue> Args, Diagnostics *Error) = 0; /// \brief Look up a matcher by name. /// /// \param MatcherName The matcher name found by the parser. /// /// \return The matcher constructor, or Optional<MatcherCtor>() if not /// found. virtual llvm::Optional<MatcherCtor> lookupMatcherCtor(StringRef MatcherName) = 0; /// \brief Compute the list of completion types for \p Context. /// /// Each element of \p Context represents a matcher invocation, going from /// outermost to innermost. Elements are pairs consisting of a reference to /// the matcher constructor and the index of the next element in the /// argument list of that matcher (or for the last element, the index of /// the completion point in the argument list). An empty list requests /// completion for the root matcher. virtual std::vector<ArgKind> getAcceptedCompletionTypes( llvm::ArrayRef<std::pair<MatcherCtor, unsigned>> Context); /// \brief Compute the list of completions that match any of /// \p AcceptedTypes. /// /// \param AcceptedTypes All types accepted for this completion. /// /// \return All completions for the specified types. /// Completions should be valid when used in \c lookupMatcherCtor(). /// The matcher constructed from the return of \c lookupMatcherCtor() /// should be convertible to some type in \p AcceptedTypes. virtual std::vector<MatcherCompletion> getMatcherCompletions(llvm::ArrayRef<ArgKind> AcceptedTypes); }; /// \brief Sema implementation that uses the matcher registry to process the /// tokens. class RegistrySema : public Parser::Sema { public: ~RegistrySema() override; llvm::Optional<MatcherCtor> lookupMatcherCtor(StringRef MatcherName) override; VariantMatcher actOnMatcherExpression(MatcherCtor Ctor, const SourceRange &NameRange, StringRef BindID, ArrayRef<ParserValue> Args, Diagnostics *Error) override; std::vector<ArgKind> getAcceptedCompletionTypes( llvm::ArrayRef<std::pair<MatcherCtor, unsigned>> Context) override; std::vector<MatcherCompletion> getMatcherCompletions(llvm::ArrayRef<ArgKind> AcceptedTypes) override; }; typedef llvm::StringMap<VariantValue> NamedValueMap; /// \brief Parse a matcher expression. /// /// \param MatcherCode The matcher expression to parse. /// /// \param S The Sema instance that will help the parser /// construct the matchers. If null, it uses the default registry. /// /// \param NamedValues A map of precomputed named values. This provides /// the dictionary for the <NamedValue> rule of the grammar. /// If null, it is ignored. /// /// \return The matcher object constructed by the processor, or an empty /// Optional if an error occurred. In that case, \c Error will contain a /// description of the error. /// The caller takes ownership of the DynTypedMatcher object returned. static llvm::Optional<DynTypedMatcher> parseMatcherExpression(StringRef MatcherCode, Sema *S, const NamedValueMap *NamedValues, Diagnostics *Error); static llvm::Optional<DynTypedMatcher> parseMatcherExpression(StringRef MatcherCode, Sema *S, Diagnostics *Error) { return parseMatcherExpression(MatcherCode, S, nullptr, Error); } static llvm::Optional<DynTypedMatcher> parseMatcherExpression(StringRef MatcherCode, Diagnostics *Error) { return parseMatcherExpression(MatcherCode, nullptr, Error); } /// \brief Parse an expression. /// /// Parses any expression supported by this parser. In general, the /// \c parseMatcherExpression function is a better approach to get a matcher /// object. /// /// \param S The Sema instance that will help the parser /// construct the matchers. If null, it uses the default registry. /// /// \param NamedValues A map of precomputed named values. This provides /// the dictionary for the <NamedValue> rule of the grammar. /// If null, it is ignored. static bool parseExpression(StringRef Code, Sema *S, const NamedValueMap *NamedValues, VariantValue *Value, Diagnostics *Error); static bool parseExpression(StringRef Code, Sema *S, VariantValue *Value, Diagnostics *Error) { return parseExpression(Code, S, nullptr, Value, Error); } static bool parseExpression(StringRef Code, VariantValue *Value, Diagnostics *Error) { return parseExpression(Code, nullptr, Value, Error); } /// \brief Complete an expression at the given offset. /// /// \param S The Sema instance that will help the parser /// construct the matchers. If null, it uses the default registry. /// /// \param NamedValues A map of precomputed named values. This provides /// the dictionary for the <NamedValue> rule of the grammar. /// If null, it is ignored. /// /// \return The list of completions, which may be empty if there are no /// available completions or if an error occurred. static std::vector<MatcherCompletion> completeExpression(StringRef Code, unsigned CompletionOffset, Sema *S, const NamedValueMap *NamedValues); static std::vector<MatcherCompletion> completeExpression(StringRef Code, unsigned CompletionOffset, Sema *S) { return completeExpression(Code, CompletionOffset, S, nullptr); } static std::vector<MatcherCompletion> completeExpression(StringRef Code, unsigned CompletionOffset) { return completeExpression(Code, CompletionOffset, nullptr); } private: class CodeTokenizer; struct ScopedContextEntry; struct TokenInfo; Parser(CodeTokenizer *Tokenizer, Sema *S, const NamedValueMap *NamedValues, Diagnostics *Error); bool parseExpressionImpl(VariantValue *Value); bool parseMatcherExpressionImpl(const TokenInfo &NameToken, VariantValue *Value); bool parseIdentifierPrefixImpl(VariantValue *Value); void addCompletion(const TokenInfo &CompToken, const MatcherCompletion &Completion); void addExpressionCompletions(); std::vector<MatcherCompletion> getNamedValueCompletions(ArrayRef<ArgKind> AcceptedTypes); CodeTokenizer *const Tokenizer; Sema *const S; const NamedValueMap *const NamedValues; Diagnostics *const Error; typedef std::vector<std::pair<MatcherCtor, unsigned> > ContextStackTy; ContextStackTy ContextStack; std::vector<MatcherCompletion> Completions; }; } // namespace dynamic } // namespace ast_matchers } // namespace clang #endif // LLVM_CLANG_AST_MATCHERS_DYNAMIC_PARSER_H
0
repos/DirectXShaderCompiler/tools/clang/include/clang/ASTMatchers
repos/DirectXShaderCompiler/tools/clang/include/clang/ASTMatchers/Dynamic/VariantValue.h
//===--- VariantValue.h - Polymorphic value type -*- C++ -*-===/ // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// /// /// \file /// \brief Polymorphic value type. /// /// Supports all the types required for dynamic Matcher construction. /// Used by the registry to construct matchers in a generic way. /// //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_ASTMATCHERS_DYNAMIC_VARIANTVALUE_H #define LLVM_CLANG_ASTMATCHERS_DYNAMIC_VARIANTVALUE_H #include "clang/ASTMatchers/ASTMatchers.h" #include "clang/ASTMatchers/ASTMatchersInternal.h" #include "llvm/ADT/IntrusiveRefCntPtr.h" #include "llvm/ADT/Optional.h" #include "llvm/ADT/Twine.h" #include <memory> #include <vector> namespace clang { namespace ast_matchers { namespace dynamic { /// \brief Kind identifier. /// /// It supports all types that VariantValue can contain. class ArgKind { public: enum Kind { AK_Matcher, AK_Unsigned, AK_String }; /// \brief Constructor for non-matcher types. ArgKind(Kind K) : K(K) { assert(K != AK_Matcher); } /// \brief Constructor for matcher types. ArgKind(ast_type_traits::ASTNodeKind MatcherKind) : K(AK_Matcher), MatcherKind(MatcherKind) {} Kind getArgKind() const { return K; } ast_type_traits::ASTNodeKind getMatcherKind() const { assert(K == AK_Matcher); return MatcherKind; } /// \brief Determines if this type can be converted to \p To. /// /// \param To the requested destination type. /// /// \param Specificity value corresponding to the "specificity" of the /// convertion. bool isConvertibleTo(ArgKind To, unsigned *Specificity) const; bool operator<(const ArgKind &Other) const { if (K == AK_Matcher && Other.K == AK_Matcher) return MatcherKind < Other.MatcherKind; return K < Other.K; } /// \brief String representation of the type. std::string asString() const; private: Kind K; ast_type_traits::ASTNodeKind MatcherKind; }; using ast_matchers::internal::DynTypedMatcher; /// \brief A variant matcher object. /// /// The purpose of this object is to abstract simple and polymorphic matchers /// into a single object type. /// Polymorphic matchers might be implemented as a list of all the possible /// overloads of the matcher. \c VariantMatcher knows how to select the /// appropriate overload when needed. /// To get a real matcher object out of a \c VariantMatcher you can do: /// - getSingleMatcher() which returns a matcher, only if it is not ambiguous /// to decide which matcher to return. Eg. it contains only a single /// matcher, or a polymorphic one with only one overload. /// - hasTypedMatcher<T>()/getTypedMatcher<T>(): These calls will determine if /// the underlying matcher(s) can unambiguously return a Matcher<T>. class VariantMatcher { /// \brief Methods that depend on T from hasTypedMatcher/getTypedMatcher. class MatcherOps { public: MatcherOps(ast_type_traits::ASTNodeKind NodeKind) : NodeKind(NodeKind) {} bool canConstructFrom(const DynTypedMatcher &Matcher, bool &IsExactMatch) const; /// \brief Convert \p Matcher the destination type and return it as a new /// DynTypedMatcher. virtual DynTypedMatcher convertMatcher(const DynTypedMatcher &Matcher) const = 0; /// \brief Constructs a variadic typed matcher from \p InnerMatchers. /// Will try to convert each inner matcher to the destination type and /// return llvm::None if it fails to do so. llvm::Optional<DynTypedMatcher> constructVariadicOperator(DynTypedMatcher::VariadicOperator Op, ArrayRef<VariantMatcher> InnerMatchers) const; protected: ~MatcherOps() = default; private: ast_type_traits::ASTNodeKind NodeKind; }; /// \brief Payload interface to be specialized by each matcher type. /// /// It follows a similar interface as VariantMatcher itself. class Payload : public RefCountedBaseVPTR { public: ~Payload() override; virtual llvm::Optional<DynTypedMatcher> getSingleMatcher() const = 0; virtual std::string getTypeAsString() const = 0; virtual llvm::Optional<DynTypedMatcher> getTypedMatcher(const MatcherOps &Ops) const = 0; virtual bool isConvertibleTo(ast_type_traits::ASTNodeKind Kind, unsigned *Specificity) const = 0; }; public: /// \brief A null matcher. VariantMatcher(); /// \brief Clones the provided matcher. static VariantMatcher SingleMatcher(const DynTypedMatcher &Matcher); /// \brief Clones the provided matchers. /// /// They should be the result of a polymorphic matcher. static VariantMatcher PolymorphicMatcher(std::vector<DynTypedMatcher> Matchers); /// \brief Creates a 'variadic' operator matcher. /// /// It will bind to the appropriate type on getTypedMatcher<T>(). static VariantMatcher VariadicOperatorMatcher(DynTypedMatcher::VariadicOperator Op, std::vector<VariantMatcher> Args); /// \brief Makes the matcher the "null" matcher. void reset(); /// \brief Whether the matcher is null. bool isNull() const { return !Value; } /// \brief Return a single matcher, if there is no ambiguity. /// /// \returns the matcher, if there is only one matcher. An empty Optional, if /// the underlying matcher is a polymorphic matcher with more than one /// representation. llvm::Optional<DynTypedMatcher> getSingleMatcher() const; /// \brief Determines if the contained matcher can be converted to /// \c Matcher<T>. /// /// For the Single case, it returns true if it can be converted to /// \c Matcher<T>. /// For the Polymorphic case, it returns true if one, and only one, of the /// overloads can be converted to \c Matcher<T>. If there are more than one /// that can, the result would be ambiguous and false is returned. template <class T> bool hasTypedMatcher() const { if (!Value) return false; return Value->getTypedMatcher(TypedMatcherOps<T>()).hasValue(); } /// \brief Determines if the contained matcher can be converted to \p Kind. /// /// \param Kind the requested destination type. /// /// \param Specificity value corresponding to the "specificity" of the /// convertion. bool isConvertibleTo(ast_type_traits::ASTNodeKind Kind, unsigned *Specificity) const { if (Value) return Value->isConvertibleTo(Kind, Specificity); return false; } /// \brief Return this matcher as a \c Matcher<T>. /// /// Handles the different types (Single, Polymorphic) accordingly. /// Asserts that \c hasTypedMatcher<T>() is true. template <class T> ast_matchers::internal::Matcher<T> getTypedMatcher() const { assert(hasTypedMatcher<T>() && "hasTypedMatcher<T>() == false"); return Value->getTypedMatcher(TypedMatcherOps<T>()) ->template convertTo<T>(); } /// \brief String representation of the type of the value. /// /// If the underlying matcher is a polymorphic one, the string will show all /// the types. std::string getTypeAsString() const; private: explicit VariantMatcher(Payload *Value) : Value(Value) {} template <typename T> struct TypedMatcherOps; class SinglePayload; class PolymorphicPayload; class VariadicOpPayload; IntrusiveRefCntPtr<const Payload> Value; }; template <typename T> struct VariantMatcher::TypedMatcherOps final : VariantMatcher::MatcherOps { TypedMatcherOps() : MatcherOps(ast_type_traits::ASTNodeKind::getFromNodeKind<T>()) {} typedef ast_matchers::internal::Matcher<T> MatcherT; DynTypedMatcher convertMatcher(const DynTypedMatcher &Matcher) const override { return DynTypedMatcher(Matcher.convertTo<T>()); } }; /// \brief Variant value class. /// /// Basically, a tagged union with value type semantics. /// It is used by the registry as the return value and argument type for the /// matcher factory methods. /// It can be constructed from any of the supported types. It supports /// copy/assignment. /// /// Supported types: /// - \c unsigned /// - \c llvm::StringRef /// - \c VariantMatcher (\c DynTypedMatcher / \c Matcher<T>) class VariantValue { public: VariantValue() : Type(VT_Nothing) {} VariantValue(const VariantValue &Other); ~VariantValue(); VariantValue &operator=(const VariantValue &Other); /// \brief Specific constructors for each supported type. VariantValue(unsigned Unsigned); VariantValue(StringRef String); VariantValue(const VariantMatcher &Matchers); /// \brief Returns true iff this is not an empty value. explicit operator bool() const { return hasValue(); } bool hasValue() const { return Type != VT_Nothing; } /// \brief Unsigned value functions. bool isUnsigned() const; unsigned getUnsigned() const; void setUnsigned(unsigned Unsigned); /// \brief String value functions. bool isString() const; const std::string &getString() const; void setString(StringRef String); /// \brief Matcher value functions. bool isMatcher() const; const VariantMatcher &getMatcher() const; void setMatcher(const VariantMatcher &Matcher); /// \brief Determines if the contained value can be converted to \p Kind. /// /// \param Kind the requested destination type. /// /// \param Specificity value corresponding to the "specificity" of the /// convertion. bool isConvertibleTo(ArgKind Kind, unsigned* Specificity) const; /// \brief Determines if the contained value can be converted to any kind /// in \p Kinds. /// /// \param Kinds the requested destination types. /// /// \param Specificity value corresponding to the "specificity" of the /// convertion. It is the maximum specificity of all the possible /// conversions. bool isConvertibleTo(ArrayRef<ArgKind> Kinds, unsigned *Specificity) const; /// \brief String representation of the type of the value. std::string getTypeAsString() const; private: void reset(); /// \brief All supported value types. enum ValueType { VT_Nothing, VT_Unsigned, VT_String, VT_Matcher }; /// \brief All supported value types. union AllValues { unsigned Unsigned; std::string *String; VariantMatcher *Matcher; }; ValueType Type; AllValues Value; }; } // end namespace dynamic } // end namespace ast_matchers } // end namespace clang #endif // LLVM_CLANG_AST_MATCHERS_DYNAMIC_VARIANT_VALUE_H
0
repos/DirectXShaderCompiler/tools/clang/include/clang/ASTMatchers
repos/DirectXShaderCompiler/tools/clang/include/clang/ASTMatchers/Dynamic/Diagnostics.h
//===--- Diagnostics.h - Helper class for error diagnostics -----*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// /// /// \file /// \brief Diagnostics class to manage error messages. /// //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_ASTMATCHERS_DYNAMIC_DIAGNOSTICS_H #define LLVM_CLANG_ASTMATCHERS_DYNAMIC_DIAGNOSTICS_H #include "clang/ASTMatchers/Dynamic/VariantValue.h" #include "clang/Basic/LLVM.h" #include "llvm/ADT/ArrayRef.h" #include "llvm/ADT/StringRef.h" #include "llvm/ADT/Twine.h" #include "llvm/Support/raw_ostream.h" #include <string> #include <vector> namespace clang { namespace ast_matchers { namespace dynamic { struct SourceLocation { SourceLocation() : Line(), Column() {} unsigned Line; unsigned Column; }; struct SourceRange { SourceLocation Start; SourceLocation End; }; /// \brief A VariantValue instance annotated with its parser context. struct ParserValue { ParserValue() : Text(), Range(), Value() {} StringRef Text; SourceRange Range; VariantValue Value; }; /// \brief Helper class to manage error messages. class Diagnostics { public: /// \brief Parser context types. enum ContextType { CT_MatcherArg = 0, CT_MatcherConstruct = 1 }; /// \brief All errors from the system. enum ErrorType { ET_None = 0, ET_RegistryMatcherNotFound = 1, ET_RegistryWrongArgCount = 2, ET_RegistryWrongArgType = 3, ET_RegistryNotBindable = 4, ET_RegistryAmbiguousOverload = 5, ET_RegistryValueNotFound = 6, ET_ParserStringError = 100, ET_ParserNoOpenParen = 101, ET_ParserNoCloseParen = 102, ET_ParserNoComma = 103, ET_ParserNoCode = 104, ET_ParserNotAMatcher = 105, ET_ParserInvalidToken = 106, ET_ParserMalformedBindExpr = 107, ET_ParserTrailingCode = 108, ET_ParserUnsignedError = 109, ET_ParserOverloadedType = 110 }; /// \brief Helper stream class. class ArgStream { public: ArgStream(std::vector<std::string> *Out) : Out(Out) {} template <class T> ArgStream &operator<<(const T &Arg) { return operator<<(Twine(Arg)); } ArgStream &operator<<(const Twine &Arg); private: std::vector<std::string> *Out; }; /// \brief Class defining a parser context. /// /// Used by the parser to specify (possibly recursive) contexts where the /// parsing/construction can fail. Any error triggered within a context will /// keep information about the context chain. /// This class should be used as a RAII instance in the stack. struct Context { public: /// \brief About to call the constructor for a matcher. enum ConstructMatcherEnum { ConstructMatcher }; Context(ConstructMatcherEnum, Diagnostics *Error, StringRef MatcherName, const SourceRange &MatcherRange); /// \brief About to recurse into parsing one argument for a matcher. enum MatcherArgEnum { MatcherArg }; Context(MatcherArgEnum, Diagnostics *Error, StringRef MatcherName, const SourceRange &MatcherRange, unsigned ArgNumber); ~Context(); private: Diagnostics *const Error; }; /// \brief Context for overloaded matcher construction. /// /// This context will take care of merging all errors that happen within it /// as "candidate" overloads for the same matcher. struct OverloadContext { public: OverloadContext(Diagnostics* Error); ~OverloadContext(); /// \brief Revert all errors that happened within this context. void revertErrors(); private: Diagnostics *const Error; unsigned BeginIndex; }; /// \brief Add an error to the diagnostics. /// /// All the context information will be kept on the error message. /// \return a helper class to allow the caller to pass the arguments for the /// error message, using the << operator. ArgStream addError(const SourceRange &Range, ErrorType Error); /// \brief Information stored for one frame of the context. struct ContextFrame { ContextType Type; SourceRange Range; std::vector<std::string> Args; }; /// \brief Information stored for each error found. struct ErrorContent { std::vector<ContextFrame> ContextStack; struct Message { SourceRange Range; ErrorType Type; std::vector<std::string> Args; }; std::vector<Message> Messages; }; ArrayRef<ErrorContent> errors() const { return Errors; } /// \brief Returns a simple string representation of each error. /// /// Each error only shows the error message without any context. void printToStream(llvm::raw_ostream &OS) const; std::string toString() const; /// \brief Returns the full string representation of each error. /// /// Each error message contains the full context. void printToStreamFull(llvm::raw_ostream &OS) const; std::string toStringFull() const; private: /// \brief Helper function used by the constructors of ContextFrame. ArgStream pushContextFrame(ContextType Type, SourceRange Range); std::vector<ContextFrame> ContextStack; std::vector<ErrorContent> Errors; }; } // namespace dynamic } // namespace ast_matchers } // namespace clang #endif // LLVM_CLANG_AST_MATCHERS_DYNAMIC_DIAGNOSTICS_H
0
repos/DirectXShaderCompiler/tools/clang/include/clang
repos/DirectXShaderCompiler/tools/clang/include/clang/Serialization/ASTWriter.h
//===--- ASTWriter.h - AST File Writer --------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines the ASTWriter class, which writes an AST file // containing a serialized representation of a translation unit. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_SERIALIZATION_ASTWRITER_H #define LLVM_CLANG_SERIALIZATION_ASTWRITER_H #include "clang/AST/ASTMutationListener.h" #include "clang/AST/Decl.h" #include "clang/AST/DeclarationName.h" #include "clang/Frontend/PCHContainerOperations.h" #include "clang/AST/TemplateBase.h" #include "clang/Sema/SemaConsumer.h" #include "clang/Serialization/ASTBitCodes.h" #include "clang/Serialization/ASTDeserializationListener.h" #include "llvm/ADT/DenseMap.h" #include "llvm/ADT/DenseSet.h" #include "llvm/ADT/MapVector.h" #include "llvm/ADT/SetVector.h" #include "llvm/ADT/SmallPtrSet.h" #include "llvm/ADT/SmallVector.h" #include "llvm/Bitcode/BitstreamWriter.h" #include <map> #include <queue> #include <vector> namespace llvm { class APFloat; class APInt; class BitstreamWriter; } namespace clang { class ASTContext; class Attr; class NestedNameSpecifier; class CXXBaseSpecifier; class CXXCtorInitializer; class FileEntry; class FPOptions; class HeaderSearch; class HeaderSearchOptions; class IdentifierResolver; class MacroDefinitionRecord; class MacroDirective; class MacroInfo; class OpaqueValueExpr; class OpenCLOptions; class ASTReader; class Module; class PreprocessedEntity; class PreprocessingRecord; class Preprocessor; class RecordDecl; class Sema; class SourceManager; struct StoredDeclsList; class SwitchCase; class TargetInfo; class Token; class VersionTuple; class ASTUnresolvedSet; namespace SrcMgr { class SLocEntry; } /// \brief Writes an AST file containing the contents of a translation unit. /// /// The ASTWriter class produces a bitstream containing the serialized /// representation of a given abstract syntax tree and its supporting /// data structures. This bitstream can be de-serialized via an /// instance of the ASTReader class. class ASTWriter : public ASTDeserializationListener, public ASTMutationListener { public: typedef SmallVector<uint64_t, 64> RecordData; typedef SmallVectorImpl<uint64_t> RecordDataImpl; friend class ASTDeclWriter; friend class ASTStmtWriter; private: /// \brief Map that provides the ID numbers of each type within the /// output stream, plus those deserialized from a chained PCH. /// /// The ID numbers of types are consecutive (in order of discovery) /// and start at 1. 0 is reserved for NULL. When types are actually /// stored in the stream, the ID number is shifted by 2 bits to /// allow for the const/volatile qualifiers. /// /// Keys in the map never have const/volatile qualifiers. typedef llvm::DenseMap<QualType, serialization::TypeIdx, serialization::UnsafeQualTypeDenseMapInfo> TypeIdxMap; /// \brief The bitstream writer used to emit this precompiled header. llvm::BitstreamWriter &Stream; /// \brief The ASTContext we're writing. ASTContext *Context; /// \brief The preprocessor we're writing. Preprocessor *PP; /// \brief The reader of existing AST files, if we're chaining. ASTReader *Chain; /// \brief The module we're currently writing, if any. Module *WritingModule; /// \brief The base directory for any relative paths we emit. std::string BaseDirectory; /// \brief Indicates when the AST writing is actively performing /// serialization, rather than just queueing updates. bool WritingAST; /// \brief Indicates that we are done serializing the collection of decls /// and types to emit. bool DoneWritingDeclsAndTypes; /// \brief Indicates that the AST contained compiler errors. bool ASTHasCompilerErrors; /// \brief Mapping from input file entries to the index into the /// offset table where information about that input file is stored. llvm::DenseMap<const FileEntry *, uint32_t> InputFileIDs; /// \brief Stores a declaration or a type to be written to the AST file. class DeclOrType { public: DeclOrType(Decl *D) : Stored(D), IsType(false) { } DeclOrType(QualType T) : Stored(T.getAsOpaquePtr()), IsType(true) { } bool isType() const { return IsType; } bool isDecl() const { return !IsType; } QualType getType() const { assert(isType() && "Not a type!"); return QualType::getFromOpaquePtr(Stored); } Decl *getDecl() const { assert(isDecl() && "Not a decl!"); return static_cast<Decl *>(Stored); } private: void *Stored; bool IsType; }; /// \brief The declarations and types to emit. std::queue<DeclOrType> DeclTypesToEmit; /// \brief The first ID number we can use for our own declarations. serialization::DeclID FirstDeclID; /// \brief The decl ID that will be assigned to the next new decl. serialization::DeclID NextDeclID; /// \brief Map that provides the ID numbers of each declaration within /// the output stream, as well as those deserialized from a chained PCH. /// /// The ID numbers of declarations are consecutive (in order of /// discovery) and start at 2. 1 is reserved for the translation /// unit, while 0 is reserved for NULL. llvm::DenseMap<const Decl *, serialization::DeclID> DeclIDs; /// \brief Offset of each declaration in the bitstream, indexed by /// the declaration's ID. std::vector<serialization::DeclOffset> DeclOffsets; /// \brief Sorted (by file offset) vector of pairs of file offset/DeclID. typedef SmallVector<std::pair<unsigned, serialization::DeclID>, 64> LocDeclIDsTy; struct DeclIDInFileInfo { LocDeclIDsTy DeclIDs; /// \brief Set when the DeclIDs vectors from all files are joined, this /// indicates the index that this particular vector has in the global one. unsigned FirstDeclIndex; }; typedef llvm::DenseMap<FileID, DeclIDInFileInfo *> FileDeclIDsTy; /// \brief Map from file SLocEntries to info about the file-level declarations /// that it contains. FileDeclIDsTy FileDeclIDs; void associateDeclWithFile(const Decl *D, serialization::DeclID); /// \brief The first ID number we can use for our own types. serialization::TypeID FirstTypeID; /// \brief The type ID that will be assigned to the next new type. serialization::TypeID NextTypeID; /// \brief Map that provides the ID numbers of each type within the /// output stream, plus those deserialized from a chained PCH. /// /// The ID numbers of types are consecutive (in order of discovery) /// and start at 1. 0 is reserved for NULL. When types are actually /// stored in the stream, the ID number is shifted by 2 bits to /// allow for the const/volatile qualifiers. /// /// Keys in the map never have const/volatile qualifiers. TypeIdxMap TypeIdxs; /// \brief Offset of each type in the bitstream, indexed by /// the type's ID. std::vector<uint32_t> TypeOffsets; /// \brief The first ID number we can use for our own identifiers. serialization::IdentID FirstIdentID; /// \brief The identifier ID that will be assigned to the next new identifier. serialization::IdentID NextIdentID; /// \brief Map that provides the ID numbers of each identifier in /// the output stream. /// /// The ID numbers for identifiers are consecutive (in order of /// discovery), starting at 1. An ID of zero refers to a NULL /// IdentifierInfo. llvm::MapVector<const IdentifierInfo *, serialization::IdentID> IdentifierIDs; /// \brief The first ID number we can use for our own macros. serialization::MacroID FirstMacroID; /// \brief The identifier ID that will be assigned to the next new identifier. serialization::MacroID NextMacroID; /// \brief Map that provides the ID numbers of each macro. llvm::DenseMap<MacroInfo *, serialization::MacroID> MacroIDs; struct MacroInfoToEmitData { const IdentifierInfo *Name; MacroInfo *MI; serialization::MacroID ID; }; /// \brief The macro infos to emit. std::vector<MacroInfoToEmitData> MacroInfosToEmit; llvm::DenseMap<const IdentifierInfo *, uint64_t> IdentMacroDirectivesOffsetMap; /// @name FlushStmt Caches /// @{ /// \brief Set of parent Stmts for the currently serializing sub-stmt. llvm::DenseSet<Stmt *> ParentStmts; /// \brief Offsets of sub-stmts already serialized. The offset points /// just after the stmt record. llvm::DenseMap<Stmt *, uint64_t> SubStmtEntries; /// @} /// \brief Offsets of each of the identifier IDs into the identifier /// table. std::vector<uint32_t> IdentifierOffsets; /// \brief The first ID number we can use for our own submodules. serialization::SubmoduleID FirstSubmoduleID; /// \brief The submodule ID that will be assigned to the next new submodule. serialization::SubmoduleID NextSubmoduleID; /// \brief The first ID number we can use for our own selectors. serialization::SelectorID FirstSelectorID; /// \brief The selector ID that will be assigned to the next new selector. serialization::SelectorID NextSelectorID; /// \brief Map that provides the ID numbers of each Selector. llvm::MapVector<Selector, serialization::SelectorID> SelectorIDs; /// \brief Offset of each selector within the method pool/selector /// table, indexed by the Selector ID (-1). std::vector<uint32_t> SelectorOffsets; /// \brief Mapping from macro definitions (as they occur in the preprocessing /// record) to the macro IDs. llvm::DenseMap<const MacroDefinitionRecord *, serialization::PreprocessedEntityID> MacroDefinitions; /// \brief Cache of indices of anonymous declarations within their lexical /// contexts. llvm::DenseMap<const Decl *, unsigned> AnonymousDeclarationNumbers; /// An update to a Decl. class DeclUpdate { /// A DeclUpdateKind. unsigned Kind; union { const Decl *Dcl; void *Type; unsigned Loc; unsigned Val; Module *Mod; const Attr *Attribute; }; public: DeclUpdate(unsigned Kind) : Kind(Kind), Dcl(nullptr) {} DeclUpdate(unsigned Kind, const Decl *Dcl) : Kind(Kind), Dcl(Dcl) {} DeclUpdate(unsigned Kind, QualType Type) : Kind(Kind), Type(Type.getAsOpaquePtr()) {} DeclUpdate(unsigned Kind, SourceLocation Loc) : Kind(Kind), Loc(Loc.getRawEncoding()) {} DeclUpdate(unsigned Kind, unsigned Val) : Kind(Kind), Val(Val) {} DeclUpdate(unsigned Kind, Module *M) : Kind(Kind), Mod(M) {} DeclUpdate(unsigned Kind, const Attr *Attribute) : Kind(Kind), Attribute(Attribute) {} unsigned getKind() const { return Kind; } const Decl *getDecl() const { return Dcl; } QualType getType() const { return QualType::getFromOpaquePtr(Type); } SourceLocation getLoc() const { return SourceLocation::getFromRawEncoding(Loc); } unsigned getNumber() const { return Val; } Module *getModule() const { return Mod; } const Attr *getAttr() const { return Attribute; } }; typedef SmallVector<DeclUpdate, 1> UpdateRecord; typedef llvm::MapVector<const Decl *, UpdateRecord> DeclUpdateMap; /// \brief Mapping from declarations that came from a chained PCH to the /// record containing modifications to them. DeclUpdateMap DeclUpdates; typedef llvm::DenseMap<Decl *, Decl *> FirstLatestDeclMap; /// \brief Map of first declarations from a chained PCH that point to the /// most recent declarations in another PCH. FirstLatestDeclMap FirstLatestDecls; /// \brief Declarations encountered that might be external /// definitions. /// /// We keep track of external definitions and other 'interesting' declarations /// as we are emitting declarations to the AST file. The AST file contains a /// separate record for these declarations, which are provided to the AST /// consumer by the AST reader. This is behavior is required to properly cope with, /// e.g., tentative variable definitions that occur within /// headers. The declarations themselves are stored as declaration /// IDs, since they will be written out to an EAGERLY_DESERIALIZED_DECLS /// record. SmallVector<uint64_t, 16> EagerlyDeserializedDecls; /// \brief DeclContexts that have received extensions since their serialized /// form. /// /// For namespaces, when we're chaining and encountering a namespace, we check /// if its primary namespace comes from the chain. If it does, we add the /// primary to this set, so that we can write out lexical content updates for /// it. llvm::SmallSetVector<const DeclContext *, 16> UpdatedDeclContexts; /// \brief Keeps track of visible decls that were added in DeclContexts /// coming from another AST file. SmallVector<const Decl *, 16> UpdatingVisibleDecls; typedef llvm::SmallSetVector<const Decl *, 16> DeclsToRewriteTy; /// \brief Decls that will be replaced in the current dependent AST file. DeclsToRewriteTy DeclsToRewrite; /// \brief The set of Objective-C class that have categories we /// should serialize. llvm::SetVector<ObjCInterfaceDecl *> ObjCClassesWithCategories; struct ReplacedDeclInfo { serialization::DeclID ID; uint64_t Offset; unsigned Loc; ReplacedDeclInfo() : ID(0), Offset(0), Loc(0) {} ReplacedDeclInfo(serialization::DeclID ID, uint64_t Offset, SourceLocation Loc) : ID(ID), Offset(Offset), Loc(Loc.getRawEncoding()) {} }; /// \brief Decls that have been replaced in the current dependent AST file. /// /// When a decl changes fundamentally after being deserialized (this shouldn't /// happen, but the ObjC AST nodes are designed this way), it will be /// serialized again. In this case, it is registered here, so that the reader /// knows to read the updated version. SmallVector<ReplacedDeclInfo, 16> ReplacedDecls; /// \brief The set of declarations that may have redeclaration chains that /// need to be serialized. llvm::SmallVector<const Decl *, 16> Redeclarations; /// \brief Statements that we've encountered while serializing a /// declaration or type. SmallVector<Stmt *, 16> StmtsToEmit; /// \brief Statements collection to use for ASTWriter::AddStmt(). /// It will point to StmtsToEmit unless it is overriden. SmallVector<Stmt *, 16> *CollectedStmts; /// \brief Mapping from SwitchCase statements to IDs. llvm::DenseMap<SwitchCase *, unsigned> SwitchCaseIDs; /// \brief The number of statements written to the AST file. unsigned NumStatements; /// \brief The number of macros written to the AST file. unsigned NumMacros; /// \brief The number of lexical declcontexts written to the AST /// file. unsigned NumLexicalDeclContexts; /// \brief The number of visible declcontexts written to the AST /// file. unsigned NumVisibleDeclContexts; /// \brief The offset of each CXXBaseSpecifier set within the AST. SmallVector<uint32_t, 16> CXXBaseSpecifiersOffsets; /// \brief The first ID number we can use for our own base specifiers. serialization::CXXBaseSpecifiersID FirstCXXBaseSpecifiersID; /// \brief The base specifiers ID that will be assigned to the next new /// set of C++ base specifiers. serialization::CXXBaseSpecifiersID NextCXXBaseSpecifiersID; /// \brief A set of C++ base specifiers that is queued to be written into the /// AST file. struct QueuedCXXBaseSpecifiers { QueuedCXXBaseSpecifiers() : ID(), Bases(), BasesEnd() { } QueuedCXXBaseSpecifiers(serialization::CXXBaseSpecifiersID ID, CXXBaseSpecifier const *Bases, CXXBaseSpecifier const *BasesEnd) : ID(ID), Bases(Bases), BasesEnd(BasesEnd) { } serialization::CXXBaseSpecifiersID ID; CXXBaseSpecifier const * Bases; CXXBaseSpecifier const * BasesEnd; }; /// \brief Queue of C++ base specifiers to be written to the AST file, /// in the order they should be written. SmallVector<QueuedCXXBaseSpecifiers, 2> CXXBaseSpecifiersToWrite; /// \brief The offset of each CXXCtorInitializer list within the AST. SmallVector<uint32_t, 16> CXXCtorInitializersOffsets; /// \brief The first ID number we can use for our own ctor initializers. serialization::CXXCtorInitializersID FirstCXXCtorInitializersID; /// \brief The ctor initializers ID that will be assigned to the next new /// list of C++ ctor initializers. serialization::CXXCtorInitializersID NextCXXCtorInitializersID; /// \brief A set of C++ ctor initializers that is queued to be written /// into the AST file. struct QueuedCXXCtorInitializers { QueuedCXXCtorInitializers() : ID() {} QueuedCXXCtorInitializers(serialization::CXXCtorInitializersID ID, ArrayRef<CXXCtorInitializer*> Inits) : ID(ID), Inits(Inits) {} serialization::CXXCtorInitializersID ID; ArrayRef<CXXCtorInitializer*> Inits; }; /// \brief Queue of C++ ctor initializers to be written to the AST file, /// in the order they should be written. SmallVector<QueuedCXXCtorInitializers, 2> CXXCtorInitializersToWrite; /// \brief A mapping from each known submodule to its ID number, which will /// be a positive integer. llvm::DenseMap<Module *, unsigned> SubmoduleIDs; /// \brief Retrieve or create a submodule ID for this module. unsigned getSubmoduleID(Module *Mod); /// \brief Write the given subexpression to the bitstream. void WriteSubStmt(Stmt *S, llvm::DenseMap<Stmt *, uint64_t> &SubStmtEntries, llvm::DenseSet<Stmt *> &ParentStmts); void WriteBlockInfoBlock(); void WriteControlBlock(Preprocessor &PP, ASTContext &Context, StringRef isysroot, const std::string &OutputFile); void WriteInputFiles(SourceManager &SourceMgr, HeaderSearchOptions &HSOpts, bool Modules); void WriteSourceManagerBlock(SourceManager &SourceMgr, const Preprocessor &PP); void WritePreprocessor(const Preprocessor &PP, bool IsModule); void WriteHeaderSearch(const HeaderSearch &HS); void WritePreprocessorDetail(PreprocessingRecord &PPRec); void WriteSubmodules(Module *WritingModule); void WritePragmaDiagnosticMappings(const DiagnosticsEngine &Diag, bool isModule); void WriteCXXBaseSpecifiersOffsets(); void WriteCXXCtorInitializersOffsets(); unsigned TypeExtQualAbbrev; unsigned TypeFunctionProtoAbbrev; void WriteTypeAbbrevs(); void WriteType(QualType T); bool isLookupResultExternal(StoredDeclsList &Result, DeclContext *DC); bool isLookupResultEntirelyExternal(StoredDeclsList &Result, DeclContext *DC); uint32_t GenerateNameLookupTable(const DeclContext *DC, llvm::SmallVectorImpl<char> &LookupTable); uint64_t WriteDeclContextLexicalBlock(ASTContext &Context, DeclContext *DC); uint64_t WriteDeclContextVisibleBlock(ASTContext &Context, DeclContext *DC); void WriteTypeDeclOffsets(); void WriteFileDeclIDsMap(); void WriteComments(); void WriteSelectors(Sema &SemaRef); void WriteReferencedSelectorsPool(Sema &SemaRef); void WriteIdentifierTable(Preprocessor &PP, IdentifierResolver &IdResolver, bool IsModule); void WriteAttributes(ArrayRef<const Attr*> Attrs, RecordDataImpl &Record); void WriteDeclUpdatesBlocks(RecordDataImpl &OffsetsRecord); void WriteDeclReplacementsBlock(); void WriteDeclContextVisibleUpdate(const DeclContext *DC); void WriteFPPragmaOptions(const FPOptions &Opts); void WriteOpenCLExtensions(Sema &SemaRef); void WriteObjCCategories(); void WriteRedeclarations(); void WriteLateParsedTemplates(Sema &SemaRef); void WriteOptimizePragmaOptions(Sema &SemaRef); unsigned DeclParmVarAbbrev; unsigned DeclContextLexicalAbbrev; unsigned DeclContextVisibleLookupAbbrev; unsigned UpdateVisibleAbbrev; unsigned DeclRecordAbbrev; unsigned DeclTypedefAbbrev; unsigned DeclVarAbbrev; unsigned DeclFieldAbbrev; unsigned DeclEnumAbbrev; unsigned DeclObjCIvarAbbrev; unsigned DeclCXXMethodAbbrev; unsigned DeclRefExprAbbrev; unsigned CharacterLiteralAbbrev; unsigned IntegerLiteralAbbrev; unsigned ExprImplicitCastAbbrev; void WriteDeclAbbrevs(); void WriteDecl(ASTContext &Context, Decl *D); void AddFunctionDefinition(const FunctionDecl *FD, RecordData &Record); void WriteASTCore(Sema &SemaRef, StringRef isysroot, const std::string &OutputFile, Module *WritingModule); public: /// \brief Create a new precompiled header writer that outputs to /// the given bitstream. ASTWriter(llvm::BitstreamWriter &Stream); ~ASTWriter() override; const LangOptions &getLangOpts() const; /// \brief Write a precompiled header for the given semantic analysis. /// /// \param SemaRef a reference to the semantic analysis object that processed /// the AST to be written into the precompiled header. /// /// \param WritingModule The module that we are writing. If null, we are /// writing a precompiled header. /// /// \param isysroot if non-empty, write a relocatable file whose headers /// are relative to the given system root. If we're writing a module, its /// build directory will be used in preference to this if both are available. void WriteAST(Sema &SemaRef, const std::string &OutputFile, Module *WritingModule, StringRef isysroot, bool hasErrors = false); /// \brief Emit a token. void AddToken(const Token &Tok, RecordDataImpl &Record); /// \brief Emit a source location. void AddSourceLocation(SourceLocation Loc, RecordDataImpl &Record); /// \brief Emit a source range. void AddSourceRange(SourceRange Range, RecordDataImpl &Record); /// \brief Emit an integral value. void AddAPInt(const llvm::APInt &Value, RecordDataImpl &Record); /// \brief Emit a signed integral value. void AddAPSInt(const llvm::APSInt &Value, RecordDataImpl &Record); /// \brief Emit a floating-point value. void AddAPFloat(const llvm::APFloat &Value, RecordDataImpl &Record); /// \brief Emit a reference to an identifier. void AddIdentifierRef(const IdentifierInfo *II, RecordDataImpl &Record); /// \brief Emit a Selector (which is a smart pointer reference). void AddSelectorRef(Selector, RecordDataImpl &Record); /// \brief Emit a CXXTemporary. void AddCXXTemporary(const CXXTemporary *Temp, RecordDataImpl &Record); /// \brief Emit a set of C++ base specifiers to the record. void AddCXXBaseSpecifiersRef(CXXBaseSpecifier const *Bases, CXXBaseSpecifier const *BasesEnd, RecordDataImpl &Record); /// \brief Get the unique number used to refer to the given selector. serialization::SelectorID getSelectorRef(Selector Sel); /// \brief Get the unique number used to refer to the given identifier. serialization::IdentID getIdentifierRef(const IdentifierInfo *II); /// \brief Get the unique number used to refer to the given macro. serialization::MacroID getMacroRef(MacroInfo *MI, const IdentifierInfo *Name); /// \brief Determine the ID of an already-emitted macro. serialization::MacroID getMacroID(MacroInfo *MI); uint64_t getMacroDirectivesOffset(const IdentifierInfo *Name); /// \brief Emit a reference to a type. void AddTypeRef(QualType T, RecordDataImpl &Record); /// \brief Force a type to be emitted and get its ID. serialization::TypeID GetOrCreateTypeID(QualType T); /// \brief Determine the type ID of an already-emitted type. serialization::TypeID getTypeID(QualType T) const; /// \brief Emits a reference to a declarator info. void AddTypeSourceInfo(TypeSourceInfo *TInfo, RecordDataImpl &Record); /// \brief Emits a type with source-location information. void AddTypeLoc(TypeLoc TL, RecordDataImpl &Record); /// \brief Emits a template argument location info. void AddTemplateArgumentLocInfo(TemplateArgument::ArgKind Kind, const TemplateArgumentLocInfo &Arg, RecordDataImpl &Record); /// \brief Emits a template argument location. void AddTemplateArgumentLoc(const TemplateArgumentLoc &Arg, RecordDataImpl &Record); /// \brief Emits an AST template argument list info. void AddASTTemplateArgumentListInfo( const ASTTemplateArgumentListInfo *ASTTemplArgList, RecordDataImpl &Record); /// \brief Emit a reference to a declaration. void AddDeclRef(const Decl *D, RecordDataImpl &Record); /// \brief Force a declaration to be emitted and get its ID. serialization::DeclID GetDeclRef(const Decl *D); /// \brief Determine the declaration ID of an already-emitted /// declaration. serialization::DeclID getDeclID(const Decl *D); /// \brief Emit a declaration name. void AddDeclarationName(DeclarationName Name, RecordDataImpl &Record); void AddDeclarationNameLoc(const DeclarationNameLoc &DNLoc, DeclarationName Name, RecordDataImpl &Record); void AddDeclarationNameInfo(const DeclarationNameInfo &NameInfo, RecordDataImpl &Record); unsigned getAnonymousDeclarationNumber(const NamedDecl *D); void AddQualifierInfo(const QualifierInfo &Info, RecordDataImpl &Record); /// \brief Emit a nested name specifier. void AddNestedNameSpecifier(NestedNameSpecifier *NNS, RecordDataImpl &Record); /// \brief Emit a nested name specifier with source-location information. void AddNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS, RecordDataImpl &Record); /// \brief Emit a template name. void AddTemplateName(TemplateName Name, RecordDataImpl &Record); /// \brief Emit a template argument. void AddTemplateArgument(const TemplateArgument &Arg, RecordDataImpl &Record); /// \brief Emit a template parameter list. void AddTemplateParameterList(const TemplateParameterList *TemplateParams, RecordDataImpl &Record); /// \brief Emit a template argument list. void AddTemplateArgumentList(const TemplateArgumentList *TemplateArgs, RecordDataImpl &Record); /// \brief Emit a UnresolvedSet structure. void AddUnresolvedSet(const ASTUnresolvedSet &Set, RecordDataImpl &Record); /// \brief Emit a C++ base specifier. void AddCXXBaseSpecifier(const CXXBaseSpecifier &Base, RecordDataImpl &Record); /// \brief Emit the ID for a CXXCtorInitializer array and register the array /// for later serialization. void AddCXXCtorInitializersRef(ArrayRef<CXXCtorInitializer *> Inits, RecordDataImpl &Record); /// \brief Emit a CXXCtorInitializer array. void AddCXXCtorInitializers( const CXXCtorInitializer * const *CtorInitializers, unsigned NumCtorInitializers, RecordDataImpl &Record); void AddCXXDefinitionData(const CXXRecordDecl *D, RecordDataImpl &Record); /// \brief Add a string to the given record. void AddString(StringRef Str, RecordDataImpl &Record); /// \brief Convert a path from this build process into one that is appropriate /// for emission in the module file. bool PreparePathForOutput(SmallVectorImpl<char> &Path); /// \brief Add a path to the given record. void AddPath(StringRef Path, RecordDataImpl &Record); /// \brief Emit the current record with the given path as a blob. void EmitRecordWithPath(unsigned Abbrev, RecordDataImpl &Record, StringRef Path); /// \brief Add a version tuple to the given record void AddVersionTuple(const VersionTuple &Version, RecordDataImpl &Record); void RewriteDecl(const Decl *D) { DeclsToRewrite.insert(D); } bool isRewritten(const Decl *D) const { return DeclsToRewrite.count(D); } /// \brief Infer the submodule ID that contains an entity at the given /// source location. serialization::SubmoduleID inferSubmoduleIDFromLocation(SourceLocation Loc); /// \brief Retrieve a submodule ID for this module. /// Returns 0 If no ID has been associated with the module. unsigned getExistingSubmoduleID(Module *Mod) const; /// \brief Note that the identifier II occurs at the given offset /// within the identifier table. void SetIdentifierOffset(const IdentifierInfo *II, uint32_t Offset); /// \brief Note that the selector Sel occurs at the given offset /// within the method pool/selector table. void SetSelectorOffset(Selector Sel, uint32_t Offset); /// \brief Add the given statement or expression to the queue of /// statements to emit. /// /// This routine should be used when emitting types and declarations /// that have expressions as part of their formulation. Once the /// type or declaration has been written, call FlushStmts() to write /// the corresponding statements just after the type or /// declaration. void AddStmt(Stmt *S) { CollectedStmts->push_back(S); } /// \brief Flush all of the statements and expressions that have /// been added to the queue via AddStmt(). void FlushStmts(); /// \brief Flush all of the C++ base specifier sets that have been added /// via \c AddCXXBaseSpecifiersRef(). void FlushCXXBaseSpecifiers(); /// \brief Flush all of the C++ constructor initializer lists that have been /// added via \c AddCXXCtorInitializersRef(). void FlushCXXCtorInitializers(); /// \brief Flush all pending records that are tacked onto the end of /// decl and decl update records. void FlushPendingAfterDecl() { FlushStmts(); FlushCXXBaseSpecifiers(); FlushCXXCtorInitializers(); } /// \brief Record an ID for the given switch-case statement. unsigned RecordSwitchCaseID(SwitchCase *S); /// \brief Retrieve the ID for the given switch-case statement. unsigned getSwitchCaseID(SwitchCase *S); void ClearSwitchCaseIDs(); unsigned getTypeExtQualAbbrev() const { return TypeExtQualAbbrev; } unsigned getTypeFunctionProtoAbbrev() const { return TypeFunctionProtoAbbrev; } unsigned getDeclParmVarAbbrev() const { return DeclParmVarAbbrev; } unsigned getDeclRecordAbbrev() const { return DeclRecordAbbrev; } unsigned getDeclTypedefAbbrev() const { return DeclTypedefAbbrev; } unsigned getDeclVarAbbrev() const { return DeclVarAbbrev; } unsigned getDeclFieldAbbrev() const { return DeclFieldAbbrev; } unsigned getDeclEnumAbbrev() const { return DeclEnumAbbrev; } unsigned getDeclObjCIvarAbbrev() const { return DeclObjCIvarAbbrev; } unsigned getDeclCXXMethodAbbrev() const { return DeclCXXMethodAbbrev; } unsigned getDeclRefExprAbbrev() const { return DeclRefExprAbbrev; } unsigned getCharacterLiteralAbbrev() const { return CharacterLiteralAbbrev; } unsigned getIntegerLiteralAbbrev() const { return IntegerLiteralAbbrev; } unsigned getExprImplicitCastAbbrev() const { return ExprImplicitCastAbbrev; } bool hasChain() const { return Chain; } // ASTDeserializationListener implementation void ReaderInitialized(ASTReader *Reader) override; void IdentifierRead(serialization::IdentID ID, IdentifierInfo *II) override; void MacroRead(serialization::MacroID ID, MacroInfo *MI) override; void TypeRead(serialization::TypeIdx Idx, QualType T) override; void SelectorRead(serialization::SelectorID ID, Selector Sel) override; void MacroDefinitionRead(serialization::PreprocessedEntityID ID, MacroDefinitionRecord *MD) override; void ModuleRead(serialization::SubmoduleID ID, Module *Mod) override; // ASTMutationListener implementation. void CompletedTagDefinition(const TagDecl *D) override; void AddedVisibleDecl(const DeclContext *DC, const Decl *D) override; void AddedCXXImplicitMember(const CXXRecordDecl *RD, const Decl *D) override; void AddedCXXTemplateSpecialization(const ClassTemplateDecl *TD, const ClassTemplateSpecializationDecl *D) override; void AddedCXXTemplateSpecialization(const VarTemplateDecl *TD, const VarTemplateSpecializationDecl *D) override; void AddedCXXTemplateSpecialization(const FunctionTemplateDecl *TD, const FunctionDecl *D) override; void ResolvedExceptionSpec(const FunctionDecl *FD) override; void DeducedReturnType(const FunctionDecl *FD, QualType ReturnType) override; void ResolvedOperatorDelete(const CXXDestructorDecl *DD, const FunctionDecl *Delete) override; void CompletedImplicitDefinition(const FunctionDecl *D) override; void StaticDataMemberInstantiated(const VarDecl *D) override; void FunctionDefinitionInstantiated(const FunctionDecl *D) override; void AddedObjCCategoryToInterface(const ObjCCategoryDecl *CatD, const ObjCInterfaceDecl *IFD) override; void AddedObjCPropertyInClassExtension(const ObjCPropertyDecl *Prop, const ObjCPropertyDecl *OrigProp, const ObjCCategoryDecl *ClassExt) override; void DeclarationMarkedUsed(const Decl *D) override; void DeclarationMarkedOpenMPThreadPrivate(const Decl *D) override; void RedefinedHiddenDefinition(const NamedDecl *D, Module *M) override; void AddedAttributeToRecord(const Attr *Attr, const RecordDecl *Record) override; }; /// \brief AST and semantic-analysis consumer that generates a /// precompiled header from the parsed source code. class PCHGenerator : public SemaConsumer { const Preprocessor &PP; std::string OutputFile; clang::Module *Module; std::string isysroot; Sema *SemaPtr; std::shared_ptr<PCHBuffer> Buffer; llvm::BitstreamWriter Stream; ASTWriter Writer; bool AllowASTWithErrors; protected: ASTWriter &getWriter() { return Writer; } const ASTWriter &getWriter() const { return Writer; } SmallVectorImpl<char> &getPCH() const { return Buffer->Data; } public: PCHGenerator(const Preprocessor &PP, StringRef OutputFile, clang::Module *Module, StringRef isysroot, std::shared_ptr<PCHBuffer> Buffer, bool AllowASTWithErrors = false); ~PCHGenerator() override; void InitializeSema(Sema &S) override { SemaPtr = &S; } void HandleTranslationUnit(ASTContext &Ctx) override; ASTMutationListener *GetASTMutationListener() override; ASTDeserializationListener *GetASTDeserializationListener() override; bool hasEmittedPCH() const { return Buffer->IsComplete; } }; } // end namespace clang #endif
0
repos/DirectXShaderCompiler/tools/clang/include/clang
repos/DirectXShaderCompiler/tools/clang/include/clang/Serialization/GlobalModuleIndex.h
//===--- GlobalModuleIndex.h - Global Module Index --------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines the GlobalModuleIndex class, which manages a global index // containing all of the identifiers known to the various modules within a given // subdirectory of the module cache. It is used to improve the performance of // queries such as "do any modules know about this identifier?" // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_SERIALIZATION_GLOBALMODULEINDEX_H #define LLVM_CLANG_SERIALIZATION_GLOBALMODULEINDEX_H #include "llvm/ADT/DenseMap.h" #include "llvm/ADT/SmallPtrSet.h" #include "llvm/ADT/SmallVector.h" #include "llvm/ADT/StringMap.h" #include "llvm/ADT/StringRef.h" #include <memory> #include <utility> namespace llvm { class BitstreamCursor; class MemoryBuffer; } namespace clang { class DirectoryEntry; class FileEntry; class FileManager; class IdentifierIterator; class PCHContainerOperations; namespace serialization { class ModuleFile; } using llvm::SmallVector; using llvm::SmallVectorImpl; using llvm::StringRef; using serialization::ModuleFile; /// \brief A global index for a set of module files, providing information about /// the identifiers within those module files. /// /// The global index is an aid for name lookup into modules, offering a central /// place where one can look for identifiers determine which /// module files contain any information about that identifier. This /// allows the client to restrict the search to only those module files known /// to have a information about that identifier, improving performance. Moreover, /// the global module index may know about module files that have not been /// imported, and can be queried to determine which modules the current /// translation could or should load to fix a problem. class GlobalModuleIndex { /// \brief Buffer containing the index file, which is lazily accessed so long /// as the global module index is live. std::unique_ptr<llvm::MemoryBuffer> Buffer; /// \brief The hash table. /// /// This pointer actually points to a IdentifierIndexTable object, /// but that type is only accessible within the implementation of /// GlobalModuleIndex. void *IdentifierIndex; /// \brief Information about a given module file. struct ModuleInfo { ModuleInfo() : File(), Size(), ModTime() { } /// \brief The module file, once it has been resolved. ModuleFile *File; /// \brief The module file name. std::string FileName; /// \brief Size of the module file at the time the global index was built. off_t Size; /// \brief Modification time of the module file at the time the global /// index was built. time_t ModTime; /// \brief The module IDs on which this module directly depends. /// FIXME: We don't really need a vector here. llvm::SmallVector<unsigned, 4> Dependencies; }; /// \brief A mapping from module IDs to information about each module. /// /// This vector may have gaps, if module files have been removed or have /// been updated since the index was built. A gap is indicated by an empty /// file name. llvm::SmallVector<ModuleInfo, 16> Modules; /// \brief Lazily-populated mapping from module files to their /// corresponding index into the \c Modules vector. llvm::DenseMap<ModuleFile *, unsigned> ModulesByFile; /// \brief The set of modules that have not yet been resolved. /// /// The string is just the name of the module itself, which maps to the /// module ID. llvm::StringMap<unsigned> UnresolvedModules; /// \brief The number of identifier lookups we performed. unsigned NumIdentifierLookups; /// \brief The number of identifier lookup hits, where we recognize the /// identifier. unsigned NumIdentifierLookupHits; /// \brief Internal constructor. Use \c readIndex() to read an index. explicit GlobalModuleIndex(std::unique_ptr<llvm::MemoryBuffer> Buffer, llvm::BitstreamCursor Cursor); GlobalModuleIndex(const GlobalModuleIndex &) = delete; GlobalModuleIndex &operator=(const GlobalModuleIndex &) = delete; public: ~GlobalModuleIndex(); /// \brief An error code returned when trying to read an index. enum ErrorCode { /// \brief No error occurred. EC_None, /// \brief No index was found. EC_NotFound, /// \brief Some other process is currently building the index; it is not /// available yet. EC_Building, /// \brief There was an unspecified I/O error reading or writing the index. EC_IOError }; /// \brief Read a global index file for the given directory. /// /// \param Path The path to the specific module cache where the module files /// for the intended configuration reside. /// /// \returns A pair containing the global module index (if it exists) and /// the error code. static std::pair<GlobalModuleIndex *, ErrorCode> readIndex(StringRef Path); /// \brief Returns an iterator for identifiers stored in the index table. /// /// The caller accepts ownership of the returned object. IdentifierIterator *createIdentifierIterator() const; /// \brief Retrieve the set of modules that have up-to-date indexes. /// /// \param ModuleFiles Will be populated with the set of module files that /// have been indexed. void getKnownModules(SmallVectorImpl<ModuleFile *> &ModuleFiles); /// \brief Retrieve the set of module files on which the given module file /// directly depends. void getModuleDependencies(ModuleFile *File, SmallVectorImpl<ModuleFile *> &Dependencies); /// \brief A set of module files in which we found a result. typedef llvm::SmallPtrSet<ModuleFile *, 4> HitSet; /// \brief Look for all of the module files with information about the given /// identifier, e.g., a global function, variable, or type with that name. /// /// \param Name The identifier to look for. /// /// \param Hits Will be populated with the set of module files that have /// information about this name. /// /// \returns true if the identifier is known to the index, false otherwise. bool lookupIdentifier(StringRef Name, HitSet &Hits); /// \brief Note that the given module file has been loaded. /// /// \returns false if the global module index has information about this /// module file, and true otherwise. bool loadedModuleFile(ModuleFile *File); /// \brief Print statistics to standard error. void printStats(); /// \brief Print debugging view to standard error. void dump(); /// \brief Write a global index into the given /// /// \param FileMgr The file manager to use to load module files. /// \param PCHContainerOps - The PCHContainerOperations to use for loading and /// creating modules. /// \param Path The path to the directory containing module files, into /// which the global index will be written. static ErrorCode writeIndex(FileManager &FileMgr, const PCHContainerReader &PCHContainerRdr, StringRef Path); }; } #endif
0
repos/DirectXShaderCompiler/tools/clang/include/clang
repos/DirectXShaderCompiler/tools/clang/include/clang/Serialization/ASTBitCodes.h
//===- ASTBitCodes.h - Enum values for the PCH bitcode format ---*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This header defines Bitcode enum values for Clang serialized AST files. // // The enum values defined in this file should be considered permanent. If // new features are added, they should have values added at the end of the // respective lists. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_SERIALIZATION_ASTBITCODES_H #define LLVM_CLANG_SERIALIZATION_ASTBITCODES_H #include "clang/AST/Type.h" #include "llvm/ADT/DenseMap.h" #include "llvm/Bitcode/BitCodes.h" #include "llvm/Support/DataTypes.h" namespace clang { namespace serialization { /// \brief AST file major version number supported by this version of /// Clang. /// /// Whenever the AST file format changes in a way that makes it /// incompatible with previous versions (such that a reader /// designed for the previous version could not support reading /// the new version), this number should be increased. /// /// Version 4 of AST files also requires that the version control branch and /// revision match exactly, since there is no backward compatibility of /// AST files at this time. const unsigned VERSION_MAJOR = 6; /// \brief AST file minor version number supported by this version of /// Clang. /// /// Whenever the AST format changes in a way that is still /// compatible with previous versions (such that a reader designed /// for the previous version could still support reading the new /// version by ignoring new kinds of subblocks), this number /// should be increased. const unsigned VERSION_MINOR = 0; /// \brief An ID number that refers to an identifier in an AST file. /// /// The ID numbers of identifiers are consecutive (in order of discovery) /// and start at 1. 0 is reserved for NULL. typedef uint32_t IdentifierID; /// \brief An ID number that refers to a declaration in an AST file. /// /// The ID numbers of declarations are consecutive (in order of /// discovery), with values below NUM_PREDEF_DECL_IDS being reserved. /// At the start of a chain of precompiled headers, declaration ID 1 is /// used for the translation unit declaration. typedef uint32_t DeclID; /// \brief a Decl::Kind/DeclID pair. typedef std::pair<uint32_t, DeclID> KindDeclIDPair; // FIXME: Turn these into classes so we can have some type safety when // we go from local ID to global and vice-versa. typedef DeclID LocalDeclID; typedef DeclID GlobalDeclID; /// \brief An ID number that refers to a type in an AST file. /// /// The ID of a type is partitioned into two parts: the lower /// three bits are used to store the const/volatile/restrict /// qualifiers (as with QualType) and the upper bits provide a /// type index. The type index values are partitioned into two /// sets. The values below NUM_PREDEF_TYPE_IDs are predefined type /// IDs (based on the PREDEF_TYPE_*_ID constants), with 0 as a /// placeholder for "no type". Values from NUM_PREDEF_TYPE_IDs are /// other types that have serialized representations. typedef uint32_t TypeID; /// \brief A type index; the type ID with the qualifier bits removed. class TypeIdx { uint32_t Idx; public: TypeIdx() : Idx(0) { } explicit TypeIdx(uint32_t index) : Idx(index) { } uint32_t getIndex() const { return Idx; } TypeID asTypeID(unsigned FastQuals) const { if (Idx == uint32_t(-1)) return TypeID(-1); return (Idx << Qualifiers::FastWidth) | FastQuals; } static TypeIdx fromTypeID(TypeID ID) { if (ID == TypeID(-1)) return TypeIdx(-1); return TypeIdx(ID >> Qualifiers::FastWidth); } }; /// A structure for putting "fast"-unqualified QualTypes into a /// DenseMap. This uses the standard pointer hash function. struct UnsafeQualTypeDenseMapInfo { static inline bool isEqual(QualType A, QualType B) { return A == B; } static inline QualType getEmptyKey() { return QualType::getFromOpaquePtr((void*) 1); } static inline QualType getTombstoneKey() { return QualType::getFromOpaquePtr((void*) 2); } static inline unsigned getHashValue(QualType T) { assert(!T.getLocalFastQualifiers() && "hash invalid for types with fast quals"); uintptr_t v = reinterpret_cast<uintptr_t>(T.getAsOpaquePtr()); return (unsigned(v) >> 4) ^ (unsigned(v) >> 9); } }; /// \brief An ID number that refers to an identifier in an AST file. typedef uint32_t IdentID; /// \brief The number of predefined identifier IDs. const unsigned int NUM_PREDEF_IDENT_IDS = 1; /// \brief An ID number that refers to a macro in an AST file. typedef uint32_t MacroID; /// \brief A global ID number that refers to a macro in an AST file. typedef uint32_t GlobalMacroID; /// \brief A local to a module ID number that refers to a macro in an /// AST file. typedef uint32_t LocalMacroID; /// \brief The number of predefined macro IDs. const unsigned int NUM_PREDEF_MACRO_IDS = 1; /// \brief An ID number that refers to an ObjC selector in an AST file. typedef uint32_t SelectorID; /// \brief The number of predefined selector IDs. const unsigned int NUM_PREDEF_SELECTOR_IDS = 1; /// \brief An ID number that refers to a set of CXXBaseSpecifiers in an /// AST file. typedef uint32_t CXXBaseSpecifiersID; /// \brief An ID number that refers to a list of CXXCtorInitializers in an /// AST file. typedef uint32_t CXXCtorInitializersID; /// \brief An ID number that refers to an entity in the detailed /// preprocessing record. typedef uint32_t PreprocessedEntityID; /// \brief An ID number that refers to a submodule in a module file. typedef uint32_t SubmoduleID; /// \brief The number of predefined submodule IDs. const unsigned int NUM_PREDEF_SUBMODULE_IDS = 1; /// \brief Source range/offset of a preprocessed entity. struct PPEntityOffset { /// \brief Raw source location of beginning of range. unsigned Begin; /// \brief Raw source location of end of range. unsigned End; /// \brief Offset in the AST file. uint32_t BitOffset; PPEntityOffset(SourceRange R, uint32_t BitOffset) : Begin(R.getBegin().getRawEncoding()), End(R.getEnd().getRawEncoding()), BitOffset(BitOffset) { } }; /// \brief Source range/offset of a preprocessed entity. struct DeclOffset { /// \brief Raw source location. unsigned Loc; /// \brief Offset in the AST file. uint32_t BitOffset; DeclOffset() : Loc(0), BitOffset(0) { } DeclOffset(SourceLocation Loc, uint32_t BitOffset) : Loc(Loc.getRawEncoding()), BitOffset(BitOffset) { } void setLocation(SourceLocation L) { Loc = L.getRawEncoding(); } }; /// \brief The number of predefined preprocessed entity IDs. const unsigned int NUM_PREDEF_PP_ENTITY_IDS = 1; /// \brief Describes the various kinds of blocks that occur within /// an AST file. enum BlockIDs { /// \brief The AST block, which acts as a container around the /// full AST block. AST_BLOCK_ID = llvm::bitc::FIRST_APPLICATION_BLOCKID, /// \brief The block containing information about the source /// manager. SOURCE_MANAGER_BLOCK_ID, /// \brief The block containing information about the /// preprocessor. PREPROCESSOR_BLOCK_ID, /// \brief The block containing the definitions of all of the /// types and decls used within the AST file. DECLTYPES_BLOCK_ID, /// \brief The block containing the detailed preprocessing record. PREPROCESSOR_DETAIL_BLOCK_ID, /// \brief The block containing the submodule structure. SUBMODULE_BLOCK_ID, /// \brief The block containing comments. COMMENTS_BLOCK_ID, /// \brief The control block, which contains all of the /// information that needs to be validated prior to committing /// to loading the AST file. CONTROL_BLOCK_ID, /// \brief The block of input files, which were used as inputs /// to create this AST file. /// /// This block is part of the control block. INPUT_FILES_BLOCK_ID }; /// \brief Record types that occur within the control block. enum ControlRecordTypes { /// \brief AST file metadata, including the AST file version number /// and information about the compiler used to build this AST file. METADATA = 1, /// \brief Record code for the list of other AST files imported by /// this AST file. IMPORTS = 2, /// \brief Record code for the language options table. /// /// The record with this code contains the contents of the /// LangOptions structure. We serialize the entire contents of /// the structure, and let the reader decide which options are /// actually important to check. LANGUAGE_OPTIONS = 3, /// \brief Record code for the target options table. TARGET_OPTIONS = 4, /// \brief Record code for the original file that was used to /// generate the AST file, including both its file ID and its /// name. ORIGINAL_FILE = 5, /// \brief The directory that the PCH was originally created in. ORIGINAL_PCH_DIR = 6, /// \brief Record code for file ID of the file or buffer that was used to /// generate the AST file. ORIGINAL_FILE_ID = 7, /// \brief Offsets into the input-files block where input files /// reside. INPUT_FILE_OFFSETS = 8, /// \brief Record code for the diagnostic options table. DIAGNOSTIC_OPTIONS = 9, /// \brief Record code for the filesystem options table. FILE_SYSTEM_OPTIONS = 10, /// \brief Record code for the headers search options table. HEADER_SEARCH_OPTIONS = 11, /// \brief Record code for the preprocessor options table. PREPROCESSOR_OPTIONS = 12, /// \brief Record code for the module name. MODULE_NAME = 13, /// \brief Record code for the module map file that was used to build this /// AST file. MODULE_MAP_FILE = 14, /// \brief Record code for the signature that identifiers this AST file. SIGNATURE = 15, /// \brief Record code for the module build directory. MODULE_DIRECTORY = 16, /// \brief Record code for the list of other AST files made available by /// this AST file but not actually used by it. KNOWN_MODULE_FILES = 17, }; /// \brief Record types that occur within the input-files block /// inside the control block. enum InputFileRecordTypes { /// \brief An input file. INPUT_FILE = 1 }; /// \brief Record types that occur within the AST block itself. enum ASTRecordTypes { /// \brief Record code for the offsets of each type. /// /// The TYPE_OFFSET constant describes the record that occurs /// within the AST block. The record itself is an array of offsets that /// point into the declarations and types block (identified by /// DECLTYPES_BLOCK_ID). The index into the array is based on the ID /// of a type. For a given type ID @c T, the lower three bits of /// @c T are its qualifiers (const, volatile, restrict), as in /// the QualType class. The upper bits, after being shifted and /// subtracting NUM_PREDEF_TYPE_IDS, are used to index into the /// TYPE_OFFSET block to determine the offset of that type's /// corresponding record within the DECLTYPES_BLOCK_ID block. TYPE_OFFSET = 1, /// \brief Record code for the offsets of each decl. /// /// The DECL_OFFSET constant describes the record that occurs /// within the block identified by DECL_OFFSETS_BLOCK_ID within /// the AST block. The record itself is an array of offsets that /// point into the declarations and types block (identified by /// DECLTYPES_BLOCK_ID). The declaration ID is an index into this /// record, after subtracting one to account for the use of /// declaration ID 0 for a NULL declaration pointer. Index 0 is /// reserved for the translation unit declaration. DECL_OFFSET = 2, /// \brief Record code for the table of offsets of each /// identifier ID. /// /// The offset table contains offsets into the blob stored in /// the IDENTIFIER_TABLE record. Each offset points to the /// NULL-terminated string that corresponds to that identifier. IDENTIFIER_OFFSET = 3, /// \brief This is so that older clang versions, before the introduction /// of the control block, can read and reject the newer PCH format. /// *DON"T CHANGE THIS NUMBER*. METADATA_OLD_FORMAT = 4, /// \brief Record code for the identifier table. /// /// The identifier table is a simple blob that contains /// NULL-terminated strings for all of the identifiers /// referenced by the AST file. The IDENTIFIER_OFFSET table /// contains the mapping from identifier IDs to the characters /// in this blob. Note that the starting offsets of all of the /// identifiers are odd, so that, when the identifier offset /// table is loaded in, we can use the low bit to distinguish /// between offsets (for unresolved identifier IDs) and /// IdentifierInfo pointers (for already-resolved identifier /// IDs). IDENTIFIER_TABLE = 5, /// \brief Record code for the array of eagerly deserialized decls. /// /// The AST file contains a list of all of the declarations that should be /// eagerly deserialized present within the parsed headers, stored as an /// array of declaration IDs. These declarations will be /// reported to the AST consumer after the AST file has been /// read, since their presence can affect the semantics of the /// program (e.g., for code generation). EAGERLY_DESERIALIZED_DECLS = 6, /// \brief Record code for the set of non-builtin, special /// types. /// /// This record contains the type IDs for the various type nodes /// that are constructed during semantic analysis (e.g., /// __builtin_va_list). The SPECIAL_TYPE_* constants provide /// offsets into this record. SPECIAL_TYPES = 7, /// \brief Record code for the extra statistics we gather while /// generating an AST file. STATISTICS = 8, /// \brief Record code for the array of tentative definitions. TENTATIVE_DEFINITIONS = 9, // ID 10 used to be for a list of extern "C" declarations. /// \brief Record code for the table of offsets into the /// Objective-C method pool. SELECTOR_OFFSETS = 11, /// \brief Record code for the Objective-C method pool, METHOD_POOL = 12, /// \brief The value of the next __COUNTER__ to dispense. /// [PP_COUNTER_VALUE, Val] PP_COUNTER_VALUE = 13, /// \brief Record code for the table of offsets into the block /// of source-location information. SOURCE_LOCATION_OFFSETS = 14, /// \brief Record code for the set of source location entries /// that need to be preloaded by the AST reader. /// /// This set contains the source location entry for the /// predefines buffer and for any file entries that need to be /// preloaded. SOURCE_LOCATION_PRELOADS = 15, /// \brief Record code for the set of ext_vector type names. EXT_VECTOR_DECLS = 16, /// \brief Record code for the array of unused file scoped decls. UNUSED_FILESCOPED_DECLS = 17, /// \brief Record code for the table of offsets to entries in the /// preprocessing record. PPD_ENTITIES_OFFSETS = 18, /// \brief Record code for the array of VTable uses. VTABLE_USES = 19, // ID 20 used to be for a list of dynamic classes. /// \brief Record code for referenced selector pool. REFERENCED_SELECTOR_POOL = 21, /// \brief Record code for an update to the TU's lexically contained /// declarations. TU_UPDATE_LEXICAL = 22, /// \brief Record code for the array describing the locations (in the /// LOCAL_REDECLARATIONS record) of the redeclaration chains, indexed by /// the first known ID. LOCAL_REDECLARATIONS_MAP = 23, /// \brief Record code for declarations that Sema keeps references of. SEMA_DECL_REFS = 24, /// \brief Record code for weak undeclared identifiers. WEAK_UNDECLARED_IDENTIFIERS = 25, /// \brief Record code for pending implicit instantiations. PENDING_IMPLICIT_INSTANTIATIONS = 26, /// \brief Record code for a decl replacement block. /// /// If a declaration is modified after having been deserialized, and then /// written to a dependent AST file, its ID and offset must be added to /// the replacement block. DECL_REPLACEMENTS = 27, /// \brief Record code for an update to a decl context's lookup table. /// /// In practice, this should only be used for the TU and namespaces. UPDATE_VISIBLE = 28, /// \brief Record for offsets of DECL_UPDATES records for declarations /// that were modified after being deserialized and need updates. DECL_UPDATE_OFFSETS = 29, /// \brief Record of updates for a declaration that was modified after /// being deserialized. DECL_UPDATES = 30, /// \brief Record code for the table of offsets to CXXBaseSpecifier /// sets. CXX_BASE_SPECIFIER_OFFSETS = 31, /// \brief Record code for \#pragma diagnostic mappings. DIAG_PRAGMA_MAPPINGS = 32, /// \brief Record code for special CUDA declarations. CUDA_SPECIAL_DECL_REFS = 33, /// \brief Record code for header search information. HEADER_SEARCH_TABLE = 34, /// \brief Record code for floating point \#pragma options. FP_PRAGMA_OPTIONS = 35, /// \brief Record code for enabled OpenCL extensions. OPENCL_EXTENSIONS = 36, /// \brief The list of delegating constructor declarations. DELEGATING_CTORS = 37, /// \brief Record code for the set of known namespaces, which are used /// for typo correction. KNOWN_NAMESPACES = 38, /// \brief Record code for the remapping information used to relate /// loaded modules to the various offsets and IDs(e.g., source location /// offests, declaration and type IDs) that are used in that module to /// refer to other modules. MODULE_OFFSET_MAP = 39, /// \brief Record code for the source manager line table information, /// which stores information about \#line directives. SOURCE_MANAGER_LINE_TABLE = 40, /// \brief Record code for map of Objective-C class definition IDs to the /// ObjC categories in a module that are attached to that class. OBJC_CATEGORIES_MAP = 41, /// \brief Record code for a file sorted array of DeclIDs in a module. FILE_SORTED_DECLS = 42, /// \brief Record code for an array of all of the (sub)modules that were /// imported by the AST file. IMPORTED_MODULES = 43, // ID 40 used to be a table of merged canonical declarations. /// \brief Record code for the array of redeclaration chains. /// /// This array can only be interpreted properly using the local /// redeclarations map. LOCAL_REDECLARATIONS = 45, /// \brief Record code for the array of Objective-C categories (including /// extensions). /// /// This array can only be interpreted properly using the Objective-C /// categories map. OBJC_CATEGORIES = 46, /// \brief Record code for the table of offsets of each macro ID. /// /// The offset table contains offsets into the blob stored in /// the preprocessor block. Each offset points to the corresponding /// macro definition. MACRO_OFFSET = 47, // ID 48 used to be a table of macros. /// \brief Record code for undefined but used functions and variables that /// need a definition in this TU. UNDEFINED_BUT_USED = 49, /// \brief Record code for late parsed template functions. LATE_PARSED_TEMPLATE = 50, /// \brief Record code for \#pragma optimize options. OPTIMIZE_PRAGMA_OPTIONS = 51, /// \brief Record code for potentially unused local typedef names. UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES = 52, /// \brief Record code for the table of offsets to CXXCtorInitializers /// lists. CXX_CTOR_INITIALIZERS_OFFSETS = 53, /// \brief Delete expressions that will be analyzed later. DELETE_EXPRS_TO_ANALYZE = 54 }; /// \brief Record types used within a source manager block. enum SourceManagerRecordTypes { /// \brief Describes a source location entry (SLocEntry) for a /// file. SM_SLOC_FILE_ENTRY = 1, /// \brief Describes a source location entry (SLocEntry) for a /// buffer. SM_SLOC_BUFFER_ENTRY = 2, /// \brief Describes a blob that contains the data for a buffer /// entry. This kind of record always directly follows a /// SM_SLOC_BUFFER_ENTRY record or a SM_SLOC_FILE_ENTRY with an /// overridden buffer. SM_SLOC_BUFFER_BLOB = 3, /// \brief Describes a source location entry (SLocEntry) for a /// macro expansion. SM_SLOC_EXPANSION_ENTRY = 4 }; /// \brief Record types used within a preprocessor block. enum PreprocessorRecordTypes { // The macros in the PP section are a PP_MACRO_* instance followed by a // list of PP_TOKEN instances for each token in the definition. /// \brief An object-like macro definition. /// [PP_MACRO_OBJECT_LIKE, IdentInfoID, SLoc, IsUsed] PP_MACRO_OBJECT_LIKE = 1, /// \brief A function-like macro definition. /// [PP_MACRO_FUNCTION_LIKE, \<ObjectLikeStuff>, IsC99Varargs, /// IsGNUVarars, NumArgs, ArgIdentInfoID* ] PP_MACRO_FUNCTION_LIKE = 2, /// \brief Describes one token. /// [PP_TOKEN, SLoc, Length, IdentInfoID, Kind, Flags] PP_TOKEN = 3, /// \brief The macro directives history for a particular identifier. PP_MACRO_DIRECTIVE_HISTORY = 4, /// \brief A macro directive exported by a module. /// [PP_MODULE_MACRO, SubmoduleID, MacroID, (Overridden SubmoduleID)*] PP_MODULE_MACRO = 5, }; /// \brief Record types used within a preprocessor detail block. enum PreprocessorDetailRecordTypes { /// \brief Describes a macro expansion within the preprocessing record. PPD_MACRO_EXPANSION = 0, /// \brief Describes a macro definition within the preprocessing record. PPD_MACRO_DEFINITION = 1, /// \brief Describes an inclusion directive within the preprocessing /// record. PPD_INCLUSION_DIRECTIVE = 2 }; /// \brief Record types used within a submodule description block. enum SubmoduleRecordTypes { /// \brief Metadata for submodules as a whole. SUBMODULE_METADATA = 0, /// \brief Defines the major attributes of a submodule, including its /// name and parent. SUBMODULE_DEFINITION = 1, /// \brief Specifies the umbrella header used to create this module, /// if any. SUBMODULE_UMBRELLA_HEADER = 2, /// \brief Specifies a header that falls into this (sub)module. SUBMODULE_HEADER = 3, /// \brief Specifies a top-level header that falls into this (sub)module. SUBMODULE_TOPHEADER = 4, /// \brief Specifies an umbrella directory. SUBMODULE_UMBRELLA_DIR = 5, /// \brief Specifies the submodules that are imported by this /// submodule. SUBMODULE_IMPORTS = 6, /// \brief Specifies the submodules that are re-exported from this /// submodule. SUBMODULE_EXPORTS = 7, /// \brief Specifies a required feature. SUBMODULE_REQUIRES = 8, /// \brief Specifies a header that has been explicitly excluded /// from this submodule. SUBMODULE_EXCLUDED_HEADER = 9, /// \brief Specifies a library or framework to link against. SUBMODULE_LINK_LIBRARY = 10, /// \brief Specifies a configuration macro for this module. SUBMODULE_CONFIG_MACRO = 11, /// \brief Specifies a conflict with another module. SUBMODULE_CONFLICT = 12, /// \brief Specifies a header that is private to this submodule. SUBMODULE_PRIVATE_HEADER = 13, /// \brief Specifies a header that is part of the module but must be /// textually included. SUBMODULE_TEXTUAL_HEADER = 14, /// \brief Specifies a header that is private to this submodule but /// must be textually included. SUBMODULE_PRIVATE_TEXTUAL_HEADER = 15, }; /// \brief Record types used within a comments block. enum CommentRecordTypes { COMMENTS_RAW_COMMENT = 0 }; /// \defgroup ASTAST AST file AST constants /// /// The constants in this group describe various components of the /// abstract syntax tree within an AST file. /// /// @{ /// \brief Predefined type IDs. /// /// These type IDs correspond to predefined types in the AST /// context, such as built-in types (int) and special place-holder /// types (the \<overload> and \<dependent> type markers). Such /// types are never actually serialized, since they will be built /// by the AST context when it is created. enum PredefinedTypeIDs { /// \brief The NULL type. PREDEF_TYPE_NULL_ID = 0, /// \brief The void type. PREDEF_TYPE_VOID_ID = 1, /// \brief The 'bool' or '_Bool' type. PREDEF_TYPE_BOOL_ID = 2, /// \brief The 'char' type, when it is unsigned. PREDEF_TYPE_CHAR_U_ID = 3, /// \brief The 'unsigned char' type. PREDEF_TYPE_UCHAR_ID = 4, /// \brief The 'unsigned short' type. PREDEF_TYPE_USHORT_ID = 5, /// \brief The 'unsigned int' type. PREDEF_TYPE_UINT_ID = 6, /// \brief The 'unsigned long' type. PREDEF_TYPE_ULONG_ID = 7, /// \brief The 'unsigned long long' type. PREDEF_TYPE_ULONGLONG_ID = 8, /// \brief The 'char' type, when it is signed. PREDEF_TYPE_CHAR_S_ID = 9, /// \brief The 'signed char' type. PREDEF_TYPE_SCHAR_ID = 10, /// \brief The C++ 'wchar_t' type. PREDEF_TYPE_WCHAR_ID = 11, /// \brief The (signed) 'short' type. PREDEF_TYPE_SHORT_ID = 12, /// \brief The (signed) 'int' type. PREDEF_TYPE_INT_ID = 13, /// \brief The (signed) 'long' type. PREDEF_TYPE_LONG_ID = 14, /// \brief The (signed) 'long long' type. PREDEF_TYPE_LONGLONG_ID = 15, /// \brief The 'float' type. PREDEF_TYPE_FLOAT_ID = 16, /// \brief The 'double' type. PREDEF_TYPE_DOUBLE_ID = 17, /// \brief The 'long double' type. PREDEF_TYPE_LONGDOUBLE_ID = 18, /// \brief The placeholder type for overloaded function sets. PREDEF_TYPE_OVERLOAD_ID = 19, /// \brief The placeholder type for dependent types. PREDEF_TYPE_DEPENDENT_ID = 20, /// \brief The '__uint128_t' type. PREDEF_TYPE_UINT128_ID = 21, /// \brief The '__int128_t' type. PREDEF_TYPE_INT128_ID = 22, /// \brief The type of 'nullptr'. PREDEF_TYPE_NULLPTR_ID = 23, /// \brief The C++ 'char16_t' type. PREDEF_TYPE_CHAR16_ID = 24, /// \brief The C++ 'char32_t' type. PREDEF_TYPE_CHAR32_ID = 25, /// \brief The ObjC 'id' type. PREDEF_TYPE_OBJC_ID = 26, /// \brief The ObjC 'Class' type. PREDEF_TYPE_OBJC_CLASS = 27, /// \brief The ObjC 'SEL' type. PREDEF_TYPE_OBJC_SEL = 28, /// \brief The 'unknown any' placeholder type. PREDEF_TYPE_UNKNOWN_ANY = 29, /// \brief The placeholder type for bound member functions. PREDEF_TYPE_BOUND_MEMBER = 30, /// \brief The "auto" deduction type. PREDEF_TYPE_AUTO_DEDUCT = 31, /// \brief The "auto &&" deduction type. PREDEF_TYPE_AUTO_RREF_DEDUCT = 32, /// \brief The OpenCL 'half' / ARM NEON __fp16 type. PREDEF_TYPE_HALF_ID = 33, /// \brief ARC's unbridged-cast placeholder type. PREDEF_TYPE_ARC_UNBRIDGED_CAST = 34, /// \brief The pseudo-object placeholder type. PREDEF_TYPE_PSEUDO_OBJECT = 35, /// \brief The __va_list_tag placeholder type. PREDEF_TYPE_VA_LIST_TAG = 36, /// \brief The placeholder type for builtin functions. PREDEF_TYPE_BUILTIN_FN = 37, /// \brief OpenCL 1d image type. PREDEF_TYPE_IMAGE1D_ID = 38, /// \brief OpenCL 1d image array type. PREDEF_TYPE_IMAGE1D_ARR_ID = 39, /// \brief OpenCL 1d image buffer type. PREDEF_TYPE_IMAGE1D_BUFF_ID = 40, /// \brief OpenCL 2d image type. PREDEF_TYPE_IMAGE2D_ID = 41, /// \brief OpenCL 2d image array type. PREDEF_TYPE_IMAGE2D_ARR_ID = 42, /// \brief OpenCL 3d image type. PREDEF_TYPE_IMAGE3D_ID = 43, /// \brief OpenCL event type. PREDEF_TYPE_EVENT_ID = 44, /// \brief OpenCL sampler type. PREDEF_TYPE_SAMPLER_ID = 45 }; /// \brief The number of predefined type IDs that are reserved for /// the PREDEF_TYPE_* constants. /// /// Type IDs for non-predefined types will start at /// NUM_PREDEF_TYPE_IDs. const unsigned NUM_PREDEF_TYPE_IDS = 100; /// \brief Record codes for each kind of type. /// /// These constants describe the type records that can occur within a /// block identified by DECLTYPES_BLOCK_ID in the AST file. Each /// constant describes a record for a specific type class in the /// AST. enum TypeCode { /// \brief An ExtQualType record. TYPE_EXT_QUAL = 1, /// \brief A ComplexType record. TYPE_COMPLEX = 3, /// \brief A PointerType record. TYPE_POINTER = 4, /// \brief A BlockPointerType record. TYPE_BLOCK_POINTER = 5, /// \brief An LValueReferenceType record. TYPE_LVALUE_REFERENCE = 6, /// \brief An RValueReferenceType record. TYPE_RVALUE_REFERENCE = 7, /// \brief A MemberPointerType record. TYPE_MEMBER_POINTER = 8, /// \brief A ConstantArrayType record. TYPE_CONSTANT_ARRAY = 9, /// \brief An IncompleteArrayType record. TYPE_INCOMPLETE_ARRAY = 10, /// \brief A VariableArrayType record. TYPE_VARIABLE_ARRAY = 11, /// \brief A VectorType record. TYPE_VECTOR = 12, /// \brief An ExtVectorType record. TYPE_EXT_VECTOR = 13, /// \brief A FunctionNoProtoType record. TYPE_FUNCTION_NO_PROTO = 14, /// \brief A FunctionProtoType record. TYPE_FUNCTION_PROTO = 15, /// \brief A TypedefType record. TYPE_TYPEDEF = 16, /// \brief A TypeOfExprType record. TYPE_TYPEOF_EXPR = 17, /// \brief A TypeOfType record. TYPE_TYPEOF = 18, /// \brief A RecordType record. TYPE_RECORD = 19, /// \brief An EnumType record. TYPE_ENUM = 20, /// \brief An ObjCInterfaceType record. TYPE_OBJC_INTERFACE = 21, /// \brief An ObjCObjectPointerType record. TYPE_OBJC_OBJECT_POINTER = 22, /// \brief a DecltypeType record. TYPE_DECLTYPE = 23, /// \brief An ElaboratedType record. TYPE_ELABORATED = 24, /// \brief A SubstTemplateTypeParmType record. TYPE_SUBST_TEMPLATE_TYPE_PARM = 25, /// \brief An UnresolvedUsingType record. TYPE_UNRESOLVED_USING = 26, /// \brief An InjectedClassNameType record. TYPE_INJECTED_CLASS_NAME = 27, /// \brief An ObjCObjectType record. TYPE_OBJC_OBJECT = 28, /// \brief An TemplateTypeParmType record. TYPE_TEMPLATE_TYPE_PARM = 29, /// \brief An TemplateSpecializationType record. TYPE_TEMPLATE_SPECIALIZATION = 30, /// \brief A DependentNameType record. TYPE_DEPENDENT_NAME = 31, /// \brief A DependentTemplateSpecializationType record. TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION = 32, /// \brief A DependentSizedArrayType record. TYPE_DEPENDENT_SIZED_ARRAY = 33, /// \brief A ParenType record. TYPE_PAREN = 34, /// \brief A PackExpansionType record. TYPE_PACK_EXPANSION = 35, /// \brief An AttributedType record. TYPE_ATTRIBUTED = 36, /// \brief A SubstTemplateTypeParmPackType record. TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK = 37, /// \brief A AutoType record. TYPE_AUTO = 38, /// \brief A UnaryTransformType record. TYPE_UNARY_TRANSFORM = 39, /// \brief An AtomicType record. TYPE_ATOMIC = 40, /// \brief A DecayedType record. TYPE_DECAYED = 41, /// \brief An AdjustedType record. TYPE_ADJUSTED = 42 }; /// \brief The type IDs for special types constructed by semantic /// analysis. /// /// The constants in this enumeration are indices into the /// SPECIAL_TYPES record. enum SpecialTypeIDs { /// \brief CFConstantString type SPECIAL_TYPE_CF_CONSTANT_STRING = 0, /// \brief C FILE typedef type SPECIAL_TYPE_FILE = 1, /// \brief C jmp_buf typedef type SPECIAL_TYPE_JMP_BUF = 2, /// \brief C sigjmp_buf typedef type SPECIAL_TYPE_SIGJMP_BUF = 3, /// \brief Objective-C "id" redefinition type SPECIAL_TYPE_OBJC_ID_REDEFINITION = 4, /// \brief Objective-C "Class" redefinition type SPECIAL_TYPE_OBJC_CLASS_REDEFINITION = 5, /// \brief Objective-C "SEL" redefinition type SPECIAL_TYPE_OBJC_SEL_REDEFINITION = 6, /// \brief C ucontext_t typedef type SPECIAL_TYPE_UCONTEXT_T = 7 }; /// \brief The number of special type IDs. const unsigned NumSpecialTypeIDs = 8; /// \brief Predefined declaration IDs. /// /// These declaration IDs correspond to predefined declarations in the AST /// context, such as the NULL declaration ID. Such declarations are never /// actually serialized, since they will be built by the AST context when /// it is created. enum PredefinedDeclIDs { /// \brief The NULL declaration. PREDEF_DECL_NULL_ID = 0, /// \brief The translation unit. PREDEF_DECL_TRANSLATION_UNIT_ID = 1, /// \brief The Objective-C 'id' type. PREDEF_DECL_OBJC_ID_ID = 2, /// \brief The Objective-C 'SEL' type. PREDEF_DECL_OBJC_SEL_ID = 3, /// \brief The Objective-C 'Class' type. PREDEF_DECL_OBJC_CLASS_ID = 4, /// \brief The Objective-C 'Protocol' type. PREDEF_DECL_OBJC_PROTOCOL_ID = 5, /// \brief The signed 128-bit integer type. PREDEF_DECL_INT_128_ID = 6, /// \brief The unsigned 128-bit integer type. PREDEF_DECL_UNSIGNED_INT_128_ID = 7, /// \brief The internal 'instancetype' typedef. PREDEF_DECL_OBJC_INSTANCETYPE_ID = 8, /// \brief The internal '__builtin_va_list' typedef. PREDEF_DECL_BUILTIN_VA_LIST_ID = 9, /// \brief The extern "C" context. PREDEF_DECL_EXTERN_C_CONTEXT_ID = 10, }; /// \brief The number of declaration IDs that are predefined. /// /// For more information about predefined declarations, see the /// \c PredefinedDeclIDs type and the PREDEF_DECL_*_ID constants. const unsigned int NUM_PREDEF_DECL_IDS = 11; /// \brief Record codes for each kind of declaration. /// /// These constants describe the declaration records that can occur within /// a declarations block (identified by DECLS_BLOCK_ID). Each /// constant describes a record for a specific declaration class /// in the AST. enum DeclCode { /// \brief A TypedefDecl record. DECL_TYPEDEF = 51, /// \brief A TypeAliasDecl record. DECL_TYPEALIAS, /// \brief An EnumDecl record. DECL_ENUM, /// \brief A RecordDecl record. DECL_RECORD, /// \brief An EnumConstantDecl record. DECL_ENUM_CONSTANT, /// \brief A FunctionDecl record. DECL_FUNCTION, /// \brief A ObjCMethodDecl record. DECL_OBJC_METHOD, /// \brief A ObjCInterfaceDecl record. DECL_OBJC_INTERFACE, /// \brief A ObjCProtocolDecl record. DECL_OBJC_PROTOCOL, /// \brief A ObjCIvarDecl record. DECL_OBJC_IVAR, /// \brief A ObjCAtDefsFieldDecl record. DECL_OBJC_AT_DEFS_FIELD, /// \brief A ObjCCategoryDecl record. DECL_OBJC_CATEGORY, /// \brief A ObjCCategoryImplDecl record. DECL_OBJC_CATEGORY_IMPL, /// \brief A ObjCImplementationDecl record. DECL_OBJC_IMPLEMENTATION, /// \brief A ObjCCompatibleAliasDecl record. DECL_OBJC_COMPATIBLE_ALIAS, /// \brief A ObjCPropertyDecl record. DECL_OBJC_PROPERTY, /// \brief A ObjCPropertyImplDecl record. DECL_OBJC_PROPERTY_IMPL, /// \brief A FieldDecl record. DECL_FIELD, /// \brief A MSPropertyDecl record. DECL_MS_PROPERTY, /// \brief A VarDecl record. DECL_VAR, /// \brief An ImplicitParamDecl record. DECL_IMPLICIT_PARAM, /// \brief A ParmVarDecl record. DECL_PARM_VAR, /// \brief A FileScopeAsmDecl record. DECL_FILE_SCOPE_ASM, /// \brief A BlockDecl record. DECL_BLOCK, /// \brief A CapturedDecl record. DECL_CAPTURED, /// \brief A record that stores the set of declarations that are /// lexically stored within a given DeclContext. /// /// The record itself is a blob that is an array of declaration IDs, /// in the order in which those declarations were added to the /// declaration context. This data is used when iterating over /// the contents of a DeclContext, e.g., via /// DeclContext::decls_begin() and DeclContext::decls_end(). DECL_CONTEXT_LEXICAL, /// \brief A record that stores the set of declarations that are /// visible from a given DeclContext. /// /// The record itself stores a set of mappings, each of which /// associates a declaration name with one or more declaration /// IDs. This data is used when performing qualified name lookup /// into a DeclContext via DeclContext::lookup. DECL_CONTEXT_VISIBLE, /// \brief A LabelDecl record. DECL_LABEL, /// \brief A NamespaceDecl record. DECL_NAMESPACE, /// \brief A NamespaceAliasDecl record. DECL_NAMESPACE_ALIAS, /// \brief A UsingDecl record. DECL_USING, /// \brief A UsingShadowDecl record. DECL_USING_SHADOW, /// \brief A UsingDirecitveDecl record. DECL_USING_DIRECTIVE, /// \brief An UnresolvedUsingValueDecl record. DECL_UNRESOLVED_USING_VALUE, /// \brief An UnresolvedUsingTypenameDecl record. DECL_UNRESOLVED_USING_TYPENAME, /// \brief A LinkageSpecDecl record. DECL_LINKAGE_SPEC, /// \brief A CXXRecordDecl record. DECL_CXX_RECORD, /// \brief A CXXMethodDecl record. DECL_CXX_METHOD, /// \brief A CXXConstructorDecl record. DECL_CXX_CONSTRUCTOR, /// \brief A CXXDestructorDecl record. DECL_CXX_DESTRUCTOR, /// \brief A CXXConversionDecl record. DECL_CXX_CONVERSION, /// \brief An AccessSpecDecl record. DECL_ACCESS_SPEC, /// \brief A FriendDecl record. DECL_FRIEND, /// \brief A FriendTemplateDecl record. DECL_FRIEND_TEMPLATE, /// \brief A ClassTemplateDecl record. DECL_CLASS_TEMPLATE, /// \brief A ClassTemplateSpecializationDecl record. DECL_CLASS_TEMPLATE_SPECIALIZATION, /// \brief A ClassTemplatePartialSpecializationDecl record. DECL_CLASS_TEMPLATE_PARTIAL_SPECIALIZATION, /// \brief A VarTemplateDecl record. DECL_VAR_TEMPLATE, /// \brief A VarTemplateSpecializationDecl record. DECL_VAR_TEMPLATE_SPECIALIZATION, /// \brief A VarTemplatePartialSpecializationDecl record. DECL_VAR_TEMPLATE_PARTIAL_SPECIALIZATION, /// \brief A FunctionTemplateDecl record. DECL_FUNCTION_TEMPLATE, /// \brief A TemplateTypeParmDecl record. DECL_TEMPLATE_TYPE_PARM, /// \brief A NonTypeTemplateParmDecl record. DECL_NON_TYPE_TEMPLATE_PARM, /// \brief A TemplateTemplateParmDecl record. DECL_TEMPLATE_TEMPLATE_PARM, /// \brief A TypeAliasTemplateDecl record. DECL_TYPE_ALIAS_TEMPLATE, /// \brief A StaticAssertDecl record. DECL_STATIC_ASSERT, /// \brief A record containing CXXBaseSpecifiers. DECL_CXX_BASE_SPECIFIERS, /// \brief A record containing CXXCtorInitializers. DECL_CXX_CTOR_INITIALIZERS, /// \brief A IndirectFieldDecl record. DECL_INDIRECTFIELD, /// \brief A NonTypeTemplateParmDecl record that stores an expanded /// non-type template parameter pack. DECL_EXPANDED_NON_TYPE_TEMPLATE_PARM_PACK, /// \brief A TemplateTemplateParmDecl record that stores an expanded /// template template parameter pack. DECL_EXPANDED_TEMPLATE_TEMPLATE_PARM_PACK, /// \brief A ClassScopeFunctionSpecializationDecl record a class scope /// function specialization. (Microsoft extension). DECL_CLASS_SCOPE_FUNCTION_SPECIALIZATION, /// \brief An ImportDecl recording a module import. DECL_IMPORT, /// \brief An OMPThreadPrivateDecl record. DECL_OMP_THREADPRIVATE, /// \brief An EmptyDecl record. DECL_EMPTY, /// \brief An ObjCTypeParamDecl record. DECL_OBJC_TYPE_PARAM, }; /// \brief Record codes for each kind of statement or expression. /// /// These constants describe the records that describe statements /// or expressions. These records occur within type and declarations /// block, so they begin with record values of 128. Each constant /// describes a record for a specific statement or expression class in the /// AST. enum StmtCode { /// \brief A marker record that indicates that we are at the end /// of an expression. STMT_STOP = 128, /// \brief A NULL expression. STMT_NULL_PTR, /// \brief A reference to a previously [de]serialized Stmt record. STMT_REF_PTR, /// \brief A NullStmt record. STMT_NULL, /// \brief A CompoundStmt record. STMT_COMPOUND, /// \brief A CaseStmt record. STMT_CASE, /// \brief A DefaultStmt record. STMT_DEFAULT, /// \brief A LabelStmt record. STMT_LABEL, /// \brief An AttributedStmt record. STMT_ATTRIBUTED, /// \brief An IfStmt record. STMT_IF, /// \brief A SwitchStmt record. STMT_SWITCH, /// \brief A WhileStmt record. STMT_WHILE, /// \brief A DoStmt record. STMT_DO, /// \brief A ForStmt record. STMT_FOR, /// \brief A GotoStmt record. STMT_GOTO, /// \brief An IndirectGotoStmt record. STMT_INDIRECT_GOTO, /// \brief A ContinueStmt record. STMT_CONTINUE, /// \brief A BreakStmt record. STMT_BREAK, /// \brief A ReturnStmt record. STMT_RETURN, /// \brief A DeclStmt record. STMT_DECL, /// \brief A CapturedStmt record. STMT_CAPTURED, /// \brief A GCC-style AsmStmt record. STMT_GCCASM, /// \brief A MS-style AsmStmt record. STMT_MSASM, /// \brief A PredefinedExpr record. EXPR_PREDEFINED, /// \brief A DeclRefExpr record. EXPR_DECL_REF, /// \brief An IntegerLiteral record. EXPR_INTEGER_LITERAL, /// \brief A FloatingLiteral record. EXPR_FLOATING_LITERAL, /// \brief An ImaginaryLiteral record. EXPR_IMAGINARY_LITERAL, /// \brief A StringLiteral record. EXPR_STRING_LITERAL, /// \brief A CharacterLiteral record. EXPR_CHARACTER_LITERAL, /// \brief A ParenExpr record. EXPR_PAREN, /// \brief A ParenListExpr record. EXPR_PAREN_LIST, /// \brief A UnaryOperator record. EXPR_UNARY_OPERATOR, /// \brief An OffsetOfExpr record. EXPR_OFFSETOF, /// \brief A SizefAlignOfExpr record. EXPR_SIZEOF_ALIGN_OF, /// \brief An ArraySubscriptExpr record. EXPR_ARRAY_SUBSCRIPT, /// \brief A CallExpr record. EXPR_CALL, /// \brief A MemberExpr record. EXPR_MEMBER, /// \brief A BinaryOperator record. EXPR_BINARY_OPERATOR, /// \brief A CompoundAssignOperator record. EXPR_COMPOUND_ASSIGN_OPERATOR, /// \brief A ConditionOperator record. EXPR_CONDITIONAL_OPERATOR, /// \brief An ImplicitCastExpr record. EXPR_IMPLICIT_CAST, /// \brief A CStyleCastExpr record. EXPR_CSTYLE_CAST, /// \brief A CompoundLiteralExpr record. EXPR_COMPOUND_LITERAL, /// \brief An ExtVectorElementExpr record. EXPR_EXT_VECTOR_ELEMENT, /// \brief An InitListExpr record. EXPR_INIT_LIST, /// \brief A DesignatedInitExpr record. EXPR_DESIGNATED_INIT, /// \brief A DesignatedInitUpdateExpr record. EXPR_DESIGNATED_INIT_UPDATE, /// \brief An ImplicitValueInitExpr record. EXPR_IMPLICIT_VALUE_INIT, /// \brief An NoInitExpr record. EXPR_NO_INIT, /// \brief A VAArgExpr record. EXPR_VA_ARG, /// \brief An AddrLabelExpr record. EXPR_ADDR_LABEL, /// \brief A StmtExpr record. EXPR_STMT, /// \brief A ChooseExpr record. EXPR_CHOOSE, /// \brief A GNUNullExpr record. EXPR_GNU_NULL, /// \brief A ShuffleVectorExpr record. EXPR_SHUFFLE_VECTOR, /// \brief A ConvertVectorExpr record. EXPR_CONVERT_VECTOR, /// \brief BlockExpr EXPR_BLOCK, /// \brief A GenericSelectionExpr record. EXPR_GENERIC_SELECTION, /// \brief A PseudoObjectExpr record. EXPR_PSEUDO_OBJECT, /// \brief An AtomicExpr record. EXPR_ATOMIC, // Objective-C /// \brief An ObjCStringLiteral record. EXPR_OBJC_STRING_LITERAL, EXPR_OBJC_BOXED_EXPRESSION, EXPR_OBJC_ARRAY_LITERAL, EXPR_OBJC_DICTIONARY_LITERAL, /// \brief An ObjCEncodeExpr record. EXPR_OBJC_ENCODE, /// \brief An ObjCSelectorExpr record. EXPR_OBJC_SELECTOR_EXPR, /// \brief An ObjCProtocolExpr record. EXPR_OBJC_PROTOCOL_EXPR, /// \brief An ObjCIvarRefExpr record. EXPR_OBJC_IVAR_REF_EXPR, /// \brief An ObjCPropertyRefExpr record. EXPR_OBJC_PROPERTY_REF_EXPR, /// \brief An ObjCSubscriptRefExpr record. EXPR_OBJC_SUBSCRIPT_REF_EXPR, /// \brief UNUSED EXPR_OBJC_KVC_REF_EXPR, /// \brief An ObjCMessageExpr record. EXPR_OBJC_MESSAGE_EXPR, /// \brief An ObjCIsa Expr record. EXPR_OBJC_ISA, /// \brief An ObjCIndirectCopyRestoreExpr record. EXPR_OBJC_INDIRECT_COPY_RESTORE, /// \brief An ObjCForCollectionStmt record. STMT_OBJC_FOR_COLLECTION, /// \brief An ObjCAtCatchStmt record. STMT_OBJC_CATCH, /// \brief An ObjCAtFinallyStmt record. STMT_OBJC_FINALLY, /// \brief An ObjCAtTryStmt record. STMT_OBJC_AT_TRY, /// \brief An ObjCAtSynchronizedStmt record. STMT_OBJC_AT_SYNCHRONIZED, /// \brief An ObjCAtThrowStmt record. STMT_OBJC_AT_THROW, /// \brief An ObjCAutoreleasePoolStmt record. STMT_OBJC_AUTORELEASE_POOL, /// \brief A ObjCBoolLiteralExpr record. EXPR_OBJC_BOOL_LITERAL, // C++ /// \brief A CXXCatchStmt record. STMT_CXX_CATCH, /// \brief A CXXTryStmt record. STMT_CXX_TRY, /// \brief A CXXForRangeStmt record. STMT_CXX_FOR_RANGE, /// \brief A CXXOperatorCallExpr record. EXPR_CXX_OPERATOR_CALL, /// \brief A CXXMemberCallExpr record. EXPR_CXX_MEMBER_CALL, /// \brief A CXXConstructExpr record. EXPR_CXX_CONSTRUCT, /// \brief A CXXTemporaryObjectExpr record. EXPR_CXX_TEMPORARY_OBJECT, /// \brief A CXXStaticCastExpr record. EXPR_CXX_STATIC_CAST, /// \brief A CXXDynamicCastExpr record. EXPR_CXX_DYNAMIC_CAST, /// \brief A CXXReinterpretCastExpr record. EXPR_CXX_REINTERPRET_CAST, /// \brief A CXXConstCastExpr record. EXPR_CXX_CONST_CAST, /// \brief A CXXFunctionalCastExpr record. EXPR_CXX_FUNCTIONAL_CAST, /// \brief A UserDefinedLiteral record. EXPR_USER_DEFINED_LITERAL, /// \brief A CXXStdInitializerListExpr record. EXPR_CXX_STD_INITIALIZER_LIST, /// \brief A CXXBoolLiteralExpr record. EXPR_CXX_BOOL_LITERAL, EXPR_CXX_NULL_PTR_LITERAL, // CXXNullPtrLiteralExpr EXPR_CXX_TYPEID_EXPR, // CXXTypeidExpr (of expr). EXPR_CXX_TYPEID_TYPE, // CXXTypeidExpr (of type). EXPR_CXX_THIS, // CXXThisExpr EXPR_CXX_THROW, // CXXThrowExpr EXPR_CXX_DEFAULT_ARG, // CXXDefaultArgExpr EXPR_CXX_DEFAULT_INIT, // CXXDefaultInitExpr EXPR_CXX_BIND_TEMPORARY, // CXXBindTemporaryExpr EXPR_CXX_SCALAR_VALUE_INIT, // CXXScalarValueInitExpr EXPR_CXX_NEW, // CXXNewExpr EXPR_CXX_DELETE, // CXXDeleteExpr EXPR_CXX_PSEUDO_DESTRUCTOR, // CXXPseudoDestructorExpr EXPR_EXPR_WITH_CLEANUPS, // ExprWithCleanups EXPR_CXX_DEPENDENT_SCOPE_MEMBER, // CXXDependentScopeMemberExpr EXPR_CXX_DEPENDENT_SCOPE_DECL_REF, // DependentScopeDeclRefExpr EXPR_CXX_UNRESOLVED_CONSTRUCT, // CXXUnresolvedConstructExpr EXPR_CXX_UNRESOLVED_MEMBER, // UnresolvedMemberExpr EXPR_CXX_UNRESOLVED_LOOKUP, // UnresolvedLookupExpr EXPR_CXX_EXPRESSION_TRAIT, // ExpressionTraitExpr EXPR_CXX_NOEXCEPT, // CXXNoexceptExpr EXPR_OPAQUE_VALUE, // OpaqueValueExpr EXPR_BINARY_CONDITIONAL_OPERATOR, // BinaryConditionalOperator EXPR_TYPE_TRAIT, // TypeTraitExpr EXPR_ARRAY_TYPE_TRAIT, // ArrayTypeTraitIntExpr EXPR_PACK_EXPANSION, // PackExpansionExpr EXPR_SIZEOF_PACK, // SizeOfPackExpr EXPR_SUBST_NON_TYPE_TEMPLATE_PARM, // SubstNonTypeTemplateParmExpr EXPR_SUBST_NON_TYPE_TEMPLATE_PARM_PACK,// SubstNonTypeTemplateParmPackExpr EXPR_FUNCTION_PARM_PACK, // FunctionParmPackExpr EXPR_MATERIALIZE_TEMPORARY, // MaterializeTemporaryExpr EXPR_CXX_FOLD, // CXXFoldExpr // CUDA EXPR_CUDA_KERNEL_CALL, // CUDAKernelCallExpr // OpenCL EXPR_ASTYPE, // AsTypeExpr // Microsoft EXPR_CXX_PROPERTY_REF_EXPR, // MSPropertyRefExpr EXPR_CXX_UUIDOF_EXPR, // CXXUuidofExpr (of expr). EXPR_CXX_UUIDOF_TYPE, // CXXUuidofExpr (of type). STMT_SEH_LEAVE, // SEHLeaveStmt STMT_SEH_EXCEPT, // SEHExceptStmt STMT_SEH_FINALLY, // SEHFinallyStmt STMT_SEH_TRY, // SEHTryStmt // OpenMP directives STMT_OMP_PARALLEL_DIRECTIVE, STMT_OMP_SIMD_DIRECTIVE, STMT_OMP_FOR_DIRECTIVE, STMT_OMP_FOR_SIMD_DIRECTIVE, STMT_OMP_SECTIONS_DIRECTIVE, STMT_OMP_SECTION_DIRECTIVE, STMT_OMP_SINGLE_DIRECTIVE, STMT_OMP_MASTER_DIRECTIVE, STMT_OMP_CRITICAL_DIRECTIVE, STMT_OMP_PARALLEL_FOR_DIRECTIVE, STMT_OMP_PARALLEL_FOR_SIMD_DIRECTIVE, STMT_OMP_PARALLEL_SECTIONS_DIRECTIVE, STMT_OMP_TASK_DIRECTIVE, STMT_OMP_TASKYIELD_DIRECTIVE, STMT_OMP_BARRIER_DIRECTIVE, STMT_OMP_TASKWAIT_DIRECTIVE, STMT_OMP_FLUSH_DIRECTIVE, STMT_OMP_ORDERED_DIRECTIVE, STMT_OMP_ATOMIC_DIRECTIVE, STMT_OMP_TARGET_DIRECTIVE, STMT_OMP_TEAMS_DIRECTIVE, STMT_OMP_TASKGROUP_DIRECTIVE, STMT_OMP_CANCELLATION_POINT_DIRECTIVE, STMT_OMP_CANCEL_DIRECTIVE, // ARC EXPR_OBJC_BRIDGED_CAST, // ObjCBridgedCastExpr STMT_MS_DEPENDENT_EXISTS, // MSDependentExistsStmt EXPR_LAMBDA, // LambdaExpr // HLSL Change: Add support for hlsl types. // HLSL STMT_DISCARD // DiscardStmt }; /// \brief The kinds of designators that can occur in a /// DesignatedInitExpr. enum DesignatorTypes { /// \brief Field designator where only the field name is known. DESIG_FIELD_NAME = 0, /// \brief Field designator where the field has been resolved to /// a declaration. DESIG_FIELD_DECL = 1, /// \brief Array designator. DESIG_ARRAY = 2, /// \brief GNU array range designator. DESIG_ARRAY_RANGE = 3 }; /// \brief The different kinds of data that can occur in a /// CtorInitializer. enum CtorInitializerType { CTOR_INITIALIZER_BASE, CTOR_INITIALIZER_DELEGATING, CTOR_INITIALIZER_MEMBER, CTOR_INITIALIZER_INDIRECT_MEMBER }; /// \brief Describes the redeclarations of a declaration. struct LocalRedeclarationsInfo { DeclID FirstID; // The ID of the first declaration unsigned Offset; // Offset into the array of redeclaration chains. friend bool operator<(const LocalRedeclarationsInfo &X, const LocalRedeclarationsInfo &Y) { return X.FirstID < Y.FirstID; } friend bool operator>(const LocalRedeclarationsInfo &X, const LocalRedeclarationsInfo &Y) { return X.FirstID > Y.FirstID; } friend bool operator<=(const LocalRedeclarationsInfo &X, const LocalRedeclarationsInfo &Y) { return X.FirstID <= Y.FirstID; } friend bool operator>=(const LocalRedeclarationsInfo &X, const LocalRedeclarationsInfo &Y) { return X.FirstID >= Y.FirstID; } }; /// \brief Describes the categories of an Objective-C class. struct ObjCCategoriesInfo { DeclID DefinitionID; // The ID of the definition unsigned Offset; // Offset into the array of category lists. friend bool operator<(const ObjCCategoriesInfo &X, const ObjCCategoriesInfo &Y) { return X.DefinitionID < Y.DefinitionID; } friend bool operator>(const ObjCCategoriesInfo &X, const ObjCCategoriesInfo &Y) { return X.DefinitionID > Y.DefinitionID; } friend bool operator<=(const ObjCCategoriesInfo &X, const ObjCCategoriesInfo &Y) { return X.DefinitionID <= Y.DefinitionID; } friend bool operator>=(const ObjCCategoriesInfo &X, const ObjCCategoriesInfo &Y) { return X.DefinitionID >= Y.DefinitionID; } }; /// @} } } // end namespace clang #endif
0
repos/DirectXShaderCompiler/tools/clang/include/clang
repos/DirectXShaderCompiler/tools/clang/include/clang/Serialization/ContinuousRangeMap.h
//===--- ContinuousRangeMap.h - Map with int range as key -------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines the ContinuousRangeMap class, which is a highly // specialized container used by serialization. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_SERIALIZATION_CONTINUOUSRANGEMAP_H #define LLVM_CLANG_SERIALIZATION_CONTINUOUSRANGEMAP_H #include "clang/Basic/LLVM.h" #include "llvm/ADT/SmallVector.h" #include <algorithm> #include <utility> namespace clang { /// \brief A map from continuous integer ranges to some value, with a very /// specialized interface. /// /// CRM maps from integer ranges to values. The ranges are continuous, i.e. /// where one ends, the next one begins. So if the map contains the stops I0-3, /// the first range is from I0 to I1, the second from I1 to I2, the third from /// I2 to I3 and the last from I3 to infinity. /// /// Ranges must be inserted in order. Inserting a new stop I4 into the map will /// shrink the fourth range to I3 to I4 and add the new range I4 to inf. template <typename Int, typename V, unsigned InitialCapacity> class ContinuousRangeMap { public: typedef std::pair<Int, V> value_type; typedef value_type &reference; typedef const value_type &const_reference; typedef value_type *pointer; typedef const value_type *const_pointer; private: typedef SmallVector<value_type, InitialCapacity> Representation; Representation Rep; struct Compare { bool operator ()(const_reference L, Int R) const { return L.first < R; } bool operator ()(Int L, const_reference R) const { return L < R.first; } bool operator ()(Int L, Int R) const { return L < R; } bool operator ()(const_reference L, const_reference R) const { return L.first < R.first; } }; public: void insert(const value_type &Val) { if (!Rep.empty() && Rep.back() == Val) return; assert((Rep.empty() || Rep.back().first < Val.first) && "Must insert keys in order."); Rep.push_back(Val); } void insertOrReplace(const value_type &Val) { iterator I = std::lower_bound(Rep.begin(), Rep.end(), Val, Compare()); if (I != Rep.end() && I->first == Val.first) { I->second = Val.second; return; } Rep.insert(I, Val); } typedef typename Representation::iterator iterator; typedef typename Representation::const_iterator const_iterator; iterator begin() { return Rep.begin(); } iterator end() { return Rep.end(); } const_iterator begin() const { return Rep.begin(); } const_iterator end() const { return Rep.end(); } iterator find(Int K) { iterator I = std::upper_bound(Rep.begin(), Rep.end(), K, Compare()); // I points to the first entry with a key > K, which is the range that // follows the one containing K. if (I == Rep.begin()) return Rep.end(); --I; return I; } const_iterator find(Int K) const { return const_cast<ContinuousRangeMap*>(this)->find(K); } reference back() { return Rep.back(); } const_reference back() const { return Rep.back(); } /// \brief An object that helps properly build a continuous range map /// from a set of values. class Builder { ContinuousRangeMap &Self; Builder(const Builder&) = delete; Builder &operator=(const Builder&) = delete; public: explicit Builder(ContinuousRangeMap &Self) : Self(Self) { } ~Builder() { std::sort(Self.Rep.begin(), Self.Rep.end(), Compare()); Self.Rep.erase( std::unique( Self.Rep.begin(), Self.Rep.end(), [](const_reference A, const_reference B) { // FIXME: we should not allow any duplicate keys, but there are // a lot of duplicate 0 -> 0 mappings to remove first. assert((A == B || A.first != B.first) && "ContinuousRangeMap::Builder given non-unique keys"); return A == B; }), Self.Rep.end()); } void insert(const value_type &Val) { Self.Rep.push_back(Val); } }; friend class Builder; }; } #endif
0
repos/DirectXShaderCompiler/tools/clang/include/clang
repos/DirectXShaderCompiler/tools/clang/include/clang/Serialization/CMakeLists.txt
clang_tablegen(AttrPCHRead.inc -gen-clang-attr-pch-read -I ${CMAKE_CURRENT_SOURCE_DIR}/../../ SOURCE ../Basic/Attr.td TARGET ClangAttrPCHRead) clang_tablegen(AttrPCHWrite.inc -gen-clang-attr-pch-write -I ${CMAKE_CURRENT_SOURCE_DIR}/../../ SOURCE ../Basic/Attr.td TARGET ClangAttrPCHWrite)
0
repos/DirectXShaderCompiler/tools/clang/include/clang
repos/DirectXShaderCompiler/tools/clang/include/clang/Serialization/ASTReader.h
//===--- ASTReader.h - AST File Reader --------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines the ASTReader class, which reads AST files. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_SERIALIZATION_ASTREADER_H #define LLVM_CLANG_SERIALIZATION_ASTREADER_H #include "clang/AST/DeclObjC.h" #include "clang/AST/DeclarationName.h" #include "clang/AST/TemplateBase.h" #include "clang/Basic/Diagnostic.h" #include "clang/Basic/FileManager.h" #include "clang/Basic/FileSystemOptions.h" #include "clang/Basic/IdentifierTable.h" #include "clang/Basic/SourceManager.h" #include "clang/Basic/Version.h" #include "clang/Lex/ExternalPreprocessorSource.h" #include "clang/Lex/HeaderSearch.h" #include "clang/Lex/PreprocessingRecord.h" #include "clang/Sema/ExternalSemaSource.h" #include "clang/Serialization/ASTBitCodes.h" #include "clang/Serialization/ContinuousRangeMap.h" #include "clang/Serialization/Module.h" #include "clang/Serialization/ModuleManager.h" #include "llvm/ADT/APFloat.h" #include "llvm/ADT/APInt.h" #include "llvm/ADT/APSInt.h" #include "llvm/ADT/MapVector.h" #include "llvm/ADT/SmallPtrSet.h" #include "llvm/ADT/SmallSet.h" #include "llvm/ADT/SmallVector.h" #include "llvm/ADT/StringRef.h" #include "llvm/ADT/TinyPtrVector.h" #include "llvm/Bitcode/BitstreamReader.h" #include "llvm/Support/DataTypes.h" #include "llvm/Support/Timer.h" #include <deque> #include <map> #include <memory> #include <string> #include <utility> #include <vector> namespace llvm { class MemoryBuffer; } namespace clang { class AddrLabelExpr; class ASTConsumer; class ASTContext; class ASTIdentifierIterator; class ASTUnit; // FIXME: Layering violation and egregious hack. class Attr; class Decl; class DeclContext; class DefMacroDirective; class DiagnosticOptions; class NestedNameSpecifier; class CXXBaseSpecifier; class CXXConstructorDecl; class CXXCtorInitializer; class GlobalModuleIndex; class GotoStmt; class MacroDefinition; class MacroDirective; class ModuleMacro; class NamedDecl; class OpaqueValueExpr; class Preprocessor; class PreprocessorOptions; class Sema; class SwitchCase; class ASTDeserializationListener; class ASTWriter; class ASTReader; class ASTDeclReader; class ASTStmtReader; class TypeLocReader; struct HeaderFileInfo; class VersionTuple; class TargetOptions; class LazyASTUnresolvedSet; /// \brief Abstract interface for callback invocations by the ASTReader. /// /// While reading an AST file, the ASTReader will call the methods of the /// listener to pass on specific information. Some of the listener methods can /// return true to indicate to the ASTReader that the information (and /// consequently the AST file) is invalid. class ASTReaderListener { public: virtual ~ASTReaderListener(); /// \brief Receives the full Clang version information. /// /// \returns true to indicate that the version is invalid. Subclasses should /// generally defer to this implementation. virtual bool ReadFullVersionInformation(StringRef FullVersion) { return FullVersion != getClangFullRepositoryVersion(); } virtual void ReadModuleName(StringRef ModuleName) {} virtual void ReadModuleMapFile(StringRef ModuleMapPath) {} /// \brief Receives the language options. /// /// \returns true to indicate the options are invalid or false otherwise. virtual bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain, bool AllowCompatibleDifferences) { return false; } /// \brief Receives the target options. /// /// \returns true to indicate the target options are invalid, or false /// otherwise. virtual bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain, bool AllowCompatibleDifferences) { return false; } /// \brief Receives the diagnostic options. /// /// \returns true to indicate the diagnostic options are invalid, or false /// otherwise. virtual bool ReadDiagnosticOptions(IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) { return false; } /// \brief Receives the file system options. /// /// \returns true to indicate the file system options are invalid, or false /// otherwise. virtual bool ReadFileSystemOptions(const FileSystemOptions &FSOpts, bool Complain) { return false; } /// \brief Receives the header search options. /// /// \returns true to indicate the header search options are invalid, or false /// otherwise. virtual bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts, StringRef SpecificModuleCachePath, bool Complain) { return false; } /// \brief Receives the preprocessor options. /// /// \param SuggestedPredefines Can be filled in with the set of predefines /// that are suggested by the preprocessor options. Typically only used when /// loading a precompiled header. /// /// \returns true to indicate the preprocessor options are invalid, or false /// otherwise. virtual bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts, bool Complain, std::string &SuggestedPredefines) { return false; } /// \brief Receives __COUNTER__ value. virtual void ReadCounter(const serialization::ModuleFile &M, unsigned Value) {} /// This is called for each AST file loaded. virtual void visitModuleFile(StringRef Filename) {} /// \brief Returns true if this \c ASTReaderListener wants to receive the /// input files of the AST file via \c visitInputFile, false otherwise. virtual bool needsInputFileVisitation() { return false; } /// \brief Returns true if this \c ASTReaderListener wants to receive the /// system input files of the AST file via \c visitInputFile, false otherwise. virtual bool needsSystemInputFileVisitation() { return false; } /// \brief if \c needsInputFileVisitation returns true, this is called for /// each non-system input file of the AST File. If /// \c needsSystemInputFileVisitation is true, then it is called for all /// system input files as well. /// /// \returns true to continue receiving the next input file, false to stop. virtual bool visitInputFile(StringRef Filename, bool isSystem, bool isOverridden) { return true; } /// \brief Returns true if this \c ASTReaderListener wants to receive the /// imports of the AST file via \c visitImport, false otherwise. virtual bool needsImportVisitation() const { return false; } /// \brief If needsImportVisitation returns \c true, this is called for each /// AST file imported by this AST file. virtual void visitImport(StringRef Filename) {} }; /// \brief Simple wrapper class for chaining listeners. class ChainedASTReaderListener : public ASTReaderListener { std::unique_ptr<ASTReaderListener> First; std::unique_ptr<ASTReaderListener> Second; public: /// Takes ownership of \p First and \p Second. ChainedASTReaderListener(std::unique_ptr<ASTReaderListener> First, std::unique_ptr<ASTReaderListener> Second) : First(std::move(First)), Second(std::move(Second)) {} std::unique_ptr<ASTReaderListener> takeFirst() { return std::move(First); } std::unique_ptr<ASTReaderListener> takeSecond() { return std::move(Second); } bool ReadFullVersionInformation(StringRef FullVersion) override; void ReadModuleName(StringRef ModuleName) override; void ReadModuleMapFile(StringRef ModuleMapPath) override; bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain, bool AllowCompatibleDifferences) override; bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain, bool AllowCompatibleDifferences) override; bool ReadDiagnosticOptions(IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) override; bool ReadFileSystemOptions(const FileSystemOptions &FSOpts, bool Complain) override; bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts, StringRef SpecificModuleCachePath, bool Complain) override; bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts, bool Complain, std::string &SuggestedPredefines) override; void ReadCounter(const serialization::ModuleFile &M, unsigned Value) override; bool needsInputFileVisitation() override; bool needsSystemInputFileVisitation() override; void visitModuleFile(StringRef Filename) override; bool visitInputFile(StringRef Filename, bool isSystem, bool isOverridden) override; }; /// \brief ASTReaderListener implementation to validate the information of /// the PCH file against an initialized Preprocessor. class PCHValidator : public ASTReaderListener { Preprocessor &PP; ASTReader &Reader; public: PCHValidator(Preprocessor &PP, ASTReader &Reader) : PP(PP), Reader(Reader) {} bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain, bool AllowCompatibleDifferences) override; bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain, bool AllowCompatibleDifferences) override; bool ReadDiagnosticOptions(IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) override; bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts, bool Complain, std::string &SuggestedPredefines) override; bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts, StringRef SpecificModuleCachePath, bool Complain) override; void ReadCounter(const serialization::ModuleFile &M, unsigned Value) override; private: void Error(const char *Msg); }; namespace serialization { class ReadMethodPoolVisitor; namespace reader { class ASTIdentifierLookupTrait; /// \brief The on-disk hash table used for the DeclContext's Name lookup table. typedef llvm::OnDiskIterableChainedHashTable<ASTDeclContextNameLookupTrait> ASTDeclContextNameLookupTable; } } // end namespace serialization /// \brief Reads an AST files chain containing the contents of a translation /// unit. /// /// The ASTReader class reads bitstreams (produced by the ASTWriter /// class) containing the serialized representation of a given /// abstract syntax tree and its supporting data structures. An /// instance of the ASTReader can be attached to an ASTContext object, /// which will provide access to the contents of the AST files. /// /// The AST reader provides lazy de-serialization of declarations, as /// required when traversing the AST. Only those AST nodes that are /// actually required will be de-serialized. class ASTReader : public ExternalPreprocessorSource, public ExternalPreprocessingRecordSource, public ExternalHeaderFileInfoSource, public ExternalSemaSource, public IdentifierInfoLookup, public ExternalSLocEntrySource { public: typedef SmallVector<uint64_t, 64> RecordData; typedef SmallVectorImpl<uint64_t> RecordDataImpl; /// \brief The result of reading the control block of an AST file, which /// can fail for various reasons. enum ASTReadResult { /// \brief The control block was read successfully. Aside from failures, /// the AST file is safe to read into the current context. Success, /// \brief The AST file itself appears corrupted. Failure, /// \brief The AST file was missing. Missing, /// \brief The AST file is out-of-date relative to its input files, /// and needs to be regenerated. OutOfDate, /// \brief The AST file was written by a different version of Clang. VersionMismatch, /// \brief The AST file was writtten with a different language/target /// configuration. ConfigurationMismatch, /// \brief The AST file has errors. HadErrors }; /// \brief Types of AST files. friend class PCHValidator; friend class ASTDeclReader; friend class ASTStmtReader; friend class ASTIdentifierIterator; friend class serialization::reader::ASTIdentifierLookupTrait; friend class TypeLocReader; friend class ASTWriter; friend class ASTUnit; // ASTUnit needs to remap source locations. friend class serialization::ReadMethodPoolVisitor; typedef serialization::ModuleFile ModuleFile; typedef serialization::ModuleKind ModuleKind; typedef serialization::ModuleManager ModuleManager; typedef ModuleManager::ModuleIterator ModuleIterator; typedef ModuleManager::ModuleConstIterator ModuleConstIterator; typedef ModuleManager::ModuleReverseIterator ModuleReverseIterator; private: /// \brief The receiver of some callbacks invoked by ASTReader. std::unique_ptr<ASTReaderListener> Listener; /// \brief The receiver of deserialization events. ASTDeserializationListener *DeserializationListener; bool OwnsDeserializationListener; SourceManager &SourceMgr; FileManager &FileMgr; const PCHContainerReader &PCHContainerRdr; DiagnosticsEngine &Diags; /// \brief The semantic analysis object that will be processing the /// AST files and the translation unit that uses it. Sema *SemaObj; /// \brief The preprocessor that will be loading the source file. Preprocessor &PP; /// \brief The AST context into which we'll read the AST files. ASTContext &Context; /// \brief The AST consumer. ASTConsumer *Consumer; /// \brief The module manager which manages modules and their dependencies ModuleManager ModuleMgr; /// \brief A timer used to track the time spent deserializing. std::unique_ptr<llvm::Timer> ReadTimer; /// \brief The location where the module file will be considered as /// imported from. For non-module AST types it should be invalid. SourceLocation CurrentImportLoc; /// \brief The global module index, if loaded. std::unique_ptr<GlobalModuleIndex> GlobalIndex; /// \brief A map of global bit offsets to the module that stores entities /// at those bit offsets. ContinuousRangeMap<uint64_t, ModuleFile*, 4> GlobalBitOffsetsMap; /// \brief A map of negated SLocEntryIDs to the modules containing them. ContinuousRangeMap<unsigned, ModuleFile*, 64> GlobalSLocEntryMap; typedef ContinuousRangeMap<unsigned, ModuleFile*, 64> GlobalSLocOffsetMapType; /// \brief A map of reversed (SourceManager::MaxLoadedOffset - SLocOffset) /// SourceLocation offsets to the modules containing them. GlobalSLocOffsetMapType GlobalSLocOffsetMap; /// \brief Types that have already been loaded from the chain. /// /// When the pointer at index I is non-NULL, the type with /// ID = (I + 1) << FastQual::Width has already been loaded std::vector<QualType> TypesLoaded; typedef ContinuousRangeMap<serialization::TypeID, ModuleFile *, 4> GlobalTypeMapType; /// \brief Mapping from global type IDs to the module in which the /// type resides along with the offset that should be added to the /// global type ID to produce a local ID. GlobalTypeMapType GlobalTypeMap; /// \brief Declarations that have already been loaded from the chain. /// /// When the pointer at index I is non-NULL, the declaration with ID /// = I + 1 has already been loaded. std::vector<Decl *> DeclsLoaded; typedef ContinuousRangeMap<serialization::DeclID, ModuleFile *, 4> GlobalDeclMapType; /// \brief Mapping from global declaration IDs to the module in which the /// declaration resides. GlobalDeclMapType GlobalDeclMap; typedef std::pair<ModuleFile *, uint64_t> FileOffset; typedef SmallVector<FileOffset, 2> FileOffsetsTy; typedef llvm::DenseMap<serialization::DeclID, FileOffsetsTy> DeclUpdateOffsetsMap; /// \brief Declarations that have modifications residing in a later file /// in the chain. DeclUpdateOffsetsMap DeclUpdateOffsets; /// \brief Declaration updates for already-loaded declarations that we need /// to apply once we finish processing an import. llvm::SmallVector<std::pair<serialization::GlobalDeclID, Decl*>, 16> PendingUpdateRecords; enum class PendingFakeDefinitionKind { NotFake, Fake, FakeLoaded }; /// \brief The DefinitionData pointers that we faked up for class definitions /// that we needed but hadn't loaded yet. llvm::DenseMap<void *, PendingFakeDefinitionKind> PendingFakeDefinitionData; /// \brief Exception specification updates that have been loaded but not yet /// propagated across the relevant redeclaration chain. The map key is the /// canonical declaration (used only for deduplication) and the value is a /// declaration that has an exception specification. llvm::SmallMapVector<Decl *, FunctionDecl *, 4> PendingExceptionSpecUpdates; struct ReplacedDeclInfo { ModuleFile *Mod; uint64_t Offset; unsigned RawLoc; ReplacedDeclInfo() : Mod(nullptr), Offset(0), RawLoc(0) {} ReplacedDeclInfo(ModuleFile *Mod, uint64_t Offset, unsigned RawLoc) : Mod(Mod), Offset(Offset), RawLoc(RawLoc) {} }; typedef llvm::DenseMap<serialization::DeclID, ReplacedDeclInfo> DeclReplacementMap; /// \brief Declarations that have been replaced in a later file in the chain. DeclReplacementMap ReplacedDecls; /// \brief Declarations that have been imported and have typedef names for /// linkage purposes. llvm::DenseMap<std::pair<DeclContext*, IdentifierInfo*>, NamedDecl*> ImportedTypedefNamesForLinkage; /// \brief Mergeable declaration contexts that have anonymous declarations /// within them, and those anonymous declarations. llvm::DenseMap<DeclContext*, llvm::SmallVector<NamedDecl*, 2>> AnonymousDeclarationsForMerging; struct FileDeclsInfo { ModuleFile *Mod; ArrayRef<serialization::LocalDeclID> Decls; FileDeclsInfo() : Mod(nullptr) {} FileDeclsInfo(ModuleFile *Mod, ArrayRef<serialization::LocalDeclID> Decls) : Mod(Mod), Decls(Decls) {} }; /// \brief Map from a FileID to the file-level declarations that it contains. llvm::DenseMap<FileID, FileDeclsInfo> FileDeclIDs; // Updates for visible decls can occur for other contexts than just the // TU, and when we read those update records, the actual context will not // be available yet (unless it's the TU), so have this pending map using the // ID as a key. It will be realized when the context is actually loaded. typedef SmallVector<std::pair<serialization::reader::ASTDeclContextNameLookupTable *, ModuleFile*>, 1> DeclContextVisibleUpdates; typedef llvm::DenseMap<serialization::DeclID, DeclContextVisibleUpdates> DeclContextVisibleUpdatesPending; /// \brief Updates to the visible declarations of declaration contexts that /// haven't been loaded yet. DeclContextVisibleUpdatesPending PendingVisibleUpdates; /// \brief The set of C++ or Objective-C classes that have forward /// declarations that have not yet been linked to their definitions. llvm::SmallPtrSet<Decl *, 4> PendingDefinitions; typedef llvm::MapVector<Decl *, uint64_t, llvm::SmallDenseMap<Decl *, unsigned, 4>, SmallVector<std::pair<Decl *, uint64_t>, 4> > PendingBodiesMap; /// \brief Functions or methods that have bodies that will be attached. PendingBodiesMap PendingBodies; /// \brief Definitions for which we have added merged definitions but not yet /// performed deduplication. llvm::SetVector<NamedDecl*> PendingMergedDefinitionsToDeduplicate; /// \brief Read the records that describe the contents of declcontexts. bool ReadDeclContextStorage(ModuleFile &M, llvm::BitstreamCursor &Cursor, const std::pair<uint64_t, uint64_t> &Offsets, serialization::DeclContextInfo &Info); /// \brief A vector containing identifiers that have already been /// loaded. /// /// If the pointer at index I is non-NULL, then it refers to the /// IdentifierInfo for the identifier with ID=I+1 that has already /// been loaded. std::vector<IdentifierInfo *> IdentifiersLoaded; typedef ContinuousRangeMap<serialization::IdentID, ModuleFile *, 4> GlobalIdentifierMapType; /// \brief Mapping from global identifier IDs to the module in which the /// identifier resides along with the offset that should be added to the /// global identifier ID to produce a local ID. GlobalIdentifierMapType GlobalIdentifierMap; /// \brief A vector containing macros that have already been /// loaded. /// /// If the pointer at index I is non-NULL, then it refers to the /// MacroInfo for the identifier with ID=I+1 that has already /// been loaded. std::vector<MacroInfo *> MacrosLoaded; typedef std::pair<IdentifierInfo *, serialization::SubmoduleID> LoadedMacroInfo; /// \brief A set of #undef directives that we have loaded; used to /// deduplicate the same #undef information coming from multiple module /// files. llvm::DenseSet<LoadedMacroInfo> LoadedUndefs; typedef ContinuousRangeMap<serialization::MacroID, ModuleFile *, 4> GlobalMacroMapType; /// \brief Mapping from global macro IDs to the module in which the /// macro resides along with the offset that should be added to the /// global macro ID to produce a local ID. GlobalMacroMapType GlobalMacroMap; /// \brief A vector containing submodules that have already been loaded. /// /// This vector is indexed by the Submodule ID (-1). NULL submodule entries /// indicate that the particular submodule ID has not yet been loaded. SmallVector<Module *, 2> SubmodulesLoaded; typedef ContinuousRangeMap<serialization::SubmoduleID, ModuleFile *, 4> GlobalSubmoduleMapType; /// \brief Mapping from global submodule IDs to the module file in which the /// submodule resides along with the offset that should be added to the /// global submodule ID to produce a local ID. GlobalSubmoduleMapType GlobalSubmoduleMap; /// \brief A set of hidden declarations. typedef SmallVector<Decl*, 2> HiddenNames; typedef llvm::DenseMap<Module *, HiddenNames> HiddenNamesMapType; /// \brief A mapping from each of the hidden submodules to the deserialized /// declarations in that submodule that could be made visible. HiddenNamesMapType HiddenNamesMap; /// \brief A module import, export, or conflict that hasn't yet been resolved. struct UnresolvedModuleRef { /// \brief The file in which this module resides. ModuleFile *File; /// \brief The module that is importing or exporting. Module *Mod; /// \brief The kind of module reference. enum { Import, Export, Conflict } Kind; /// \brief The local ID of the module that is being exported. unsigned ID; /// \brief Whether this is a wildcard export. unsigned IsWildcard : 1; /// \brief String data. StringRef String; }; /// \brief The set of module imports and exports that still need to be /// resolved. SmallVector<UnresolvedModuleRef, 2> UnresolvedModuleRefs; /// \brief A vector containing selectors that have already been loaded. /// /// This vector is indexed by the Selector ID (-1). NULL selector /// entries indicate that the particular selector ID has not yet /// been loaded. SmallVector<Selector, 16> SelectorsLoaded; typedef ContinuousRangeMap<serialization::SelectorID, ModuleFile *, 4> GlobalSelectorMapType; /// \brief Mapping from global selector IDs to the module in which the /// global selector ID to produce a local ID. GlobalSelectorMapType GlobalSelectorMap; /// \brief The generation number of the last time we loaded data from the /// global method pool for this selector. llvm::DenseMap<Selector, unsigned> SelectorGeneration; struct PendingMacroInfo { ModuleFile *M; uint64_t MacroDirectivesOffset; PendingMacroInfo(ModuleFile *M, uint64_t MacroDirectivesOffset) : M(M), MacroDirectivesOffset(MacroDirectivesOffset) {} }; typedef llvm::MapVector<IdentifierInfo *, SmallVector<PendingMacroInfo, 2> > PendingMacroIDsMap; /// \brief Mapping from identifiers that have a macro history to the global /// IDs have not yet been deserialized to the global IDs of those macros. PendingMacroIDsMap PendingMacroIDs; typedef ContinuousRangeMap<unsigned, ModuleFile *, 4> GlobalPreprocessedEntityMapType; /// \brief Mapping from global preprocessing entity IDs to the module in /// which the preprocessed entity resides along with the offset that should be /// added to the global preprocessing entitiy ID to produce a local ID. GlobalPreprocessedEntityMapType GlobalPreprocessedEntityMap; /// \name CodeGen-relevant special data /// \brief Fields containing data that is relevant to CodeGen. //@{ /// \brief The IDs of all declarations that fulfill the criteria of /// "interesting" decls. /// /// This contains the data loaded from all EAGERLY_DESERIALIZED_DECLS blocks /// in the chain. The referenced declarations are deserialized and passed to /// the consumer eagerly. SmallVector<uint64_t, 16> EagerlyDeserializedDecls; /// \brief The IDs of all tentative definitions stored in the chain. /// /// Sema keeps track of all tentative definitions in a TU because it has to /// complete them and pass them on to CodeGen. Thus, tentative definitions in /// the PCH chain must be eagerly deserialized. SmallVector<uint64_t, 16> TentativeDefinitions; /// \brief The IDs of all CXXRecordDecls stored in the chain whose VTables are /// used. /// /// CodeGen has to emit VTables for these records, so they have to be eagerly /// deserialized. SmallVector<uint64_t, 64> VTableUses; /// \brief A snapshot of the pending instantiations in the chain. /// /// This record tracks the instantiations that Sema has to perform at the /// end of the TU. It consists of a pair of values for every pending /// instantiation where the first value is the ID of the decl and the second /// is the instantiation location. SmallVector<uint64_t, 64> PendingInstantiations; //@} /// \name DiagnosticsEngine-relevant special data /// \brief Fields containing data that is used for generating diagnostics //@{ /// \brief A snapshot of Sema's unused file-scoped variable tracking, for /// generating warnings. SmallVector<uint64_t, 16> UnusedFileScopedDecls; /// \brief A list of all the delegating constructors we've seen, to diagnose /// cycles. SmallVector<uint64_t, 4> DelegatingCtorDecls; /// \brief Method selectors used in a @selector expression. Used for /// implementation of -Wselector. SmallVector<uint64_t, 64> ReferencedSelectorsData; /// \brief A snapshot of Sema's weak undeclared identifier tracking, for /// generating warnings. SmallVector<uint64_t, 64> WeakUndeclaredIdentifiers; /// \brief The IDs of type aliases for ext_vectors that exist in the chain. /// /// Used by Sema for finding sugared names for ext_vectors in diagnostics. SmallVector<uint64_t, 4> ExtVectorDecls; //@} /// \name Sema-relevant special data /// \brief Fields containing data that is used for semantic analysis //@{ /// \brief The IDs of all potentially unused typedef names in the chain. /// /// Sema tracks these to emit warnings. SmallVector<uint64_t, 16> UnusedLocalTypedefNameCandidates; /// \brief The IDs of the declarations Sema stores directly. /// /// Sema tracks a few important decls, such as namespace std, directly. SmallVector<uint64_t, 4> SemaDeclRefs; /// \brief The IDs of the types ASTContext stores directly. /// /// The AST context tracks a few important types, such as va_list, directly. SmallVector<uint64_t, 16> SpecialTypes; /// \brief The IDs of CUDA-specific declarations ASTContext stores directly. /// /// The AST context tracks a few important decls, currently cudaConfigureCall, /// directly. SmallVector<uint64_t, 2> CUDASpecialDeclRefs; /// \brief The floating point pragma option settings. SmallVector<uint64_t, 1> FPPragmaOptions; /// \brief The pragma clang optimize location (if the pragma state is "off"). SourceLocation OptimizeOffPragmaLocation; /// \brief The OpenCL extension settings. SmallVector<uint64_t, 1> OpenCLExtensions; /// \brief A list of the namespaces we've seen. SmallVector<uint64_t, 4> KnownNamespaces; /// \brief A list of undefined decls with internal linkage followed by the /// SourceLocation of a matching ODR-use. SmallVector<uint64_t, 8> UndefinedButUsed; /// \brief Delete expressions to analyze at the end of translation unit. SmallVector<uint64_t, 8> DelayedDeleteExprs; // \brief A list of late parsed template function data. SmallVector<uint64_t, 1> LateParsedTemplates; struct ImportedSubmodule { serialization::SubmoduleID ID; SourceLocation ImportLoc; ImportedSubmodule(serialization::SubmoduleID ID, SourceLocation ImportLoc) : ID(ID), ImportLoc(ImportLoc) {} }; /// \brief A list of modules that were imported by precompiled headers or /// any other non-module AST file. SmallVector<ImportedSubmodule, 2> ImportedModules; //@} /// \brief The directory that the PCH we are reading is stored in. std::string CurrentDir; /// \brief The system include root to be used when loading the /// precompiled header. std::string isysroot; /// \brief Whether to disable the normal validation performed on precompiled /// headers when they are loaded. bool DisableValidation; /// \brief Whether to accept an AST file with compiler errors. bool AllowASTWithCompilerErrors; /// \brief Whether to accept an AST file that has a different configuration /// from the current compiler instance. bool AllowConfigurationMismatch; /// \brief Whether validate system input files. bool ValidateSystemInputs; /// \brief Whether we are allowed to use the global module index. bool UseGlobalIndex; /// \brief Whether we have tried loading the global module index yet. bool TriedLoadingGlobalIndex; typedef llvm::DenseMap<unsigned, SwitchCase *> SwitchCaseMapTy; /// \brief Mapping from switch-case IDs in the chain to switch-case statements /// /// Statements usually don't have IDs, but switch cases need them, so that the /// switch statement can refer to them. SwitchCaseMapTy SwitchCaseStmts; SwitchCaseMapTy *CurrSwitchCaseStmts; /// \brief The number of source location entries de-serialized from /// the PCH file. unsigned NumSLocEntriesRead; /// \brief The number of source location entries in the chain. unsigned TotalNumSLocEntries; /// \brief The number of statements (and expressions) de-serialized /// from the chain. unsigned NumStatementsRead; /// \brief The total number of statements (and expressions) stored /// in the chain. unsigned TotalNumStatements; /// \brief The number of macros de-serialized from the chain. unsigned NumMacrosRead; /// \brief The total number of macros stored in the chain. unsigned TotalNumMacros; /// \brief The number of lookups into identifier tables. unsigned NumIdentifierLookups; /// \brief The number of lookups into identifier tables that succeed. unsigned NumIdentifierLookupHits; /// \brief The number of selectors that have been read. unsigned NumSelectorsRead; /// \brief The number of method pool entries that have been read. unsigned NumMethodPoolEntriesRead; /// \brief The number of times we have looked up a selector in the method /// pool. unsigned NumMethodPoolLookups; /// \brief The number of times we have looked up a selector in the method /// pool and found something. unsigned NumMethodPoolHits; /// \brief The number of times we have looked up a selector in the method /// pool within a specific module. unsigned NumMethodPoolTableLookups; /// \brief The number of times we have looked up a selector in the method /// pool within a specific module and found something. unsigned NumMethodPoolTableHits; /// \brief The total number of method pool entries in the selector table. unsigned TotalNumMethodPoolEntries; /// Number of lexical decl contexts read/total. unsigned NumLexicalDeclContextsRead, TotalLexicalDeclContexts; /// Number of visible decl contexts read/total. unsigned NumVisibleDeclContextsRead, TotalVisibleDeclContexts; /// Total size of modules, in bits, currently loaded uint64_t TotalModulesSizeInBits; /// \brief Number of Decl/types that are currently deserializing. unsigned NumCurrentElementsDeserializing; /// \brief Set true while we are in the process of passing deserialized /// "interesting" decls to consumer inside FinishedDeserializing(). /// This is used as a guard to avoid recursively repeating the process of /// passing decls to consumer. bool PassingDeclsToConsumer; /// \brief The set of identifiers that were read while the AST reader was /// (recursively) loading declarations. /// /// The declarations on the identifier chain for these identifiers will be /// loaded once the recursive loading has completed. llvm::MapVector<IdentifierInfo *, SmallVector<uint32_t, 4> > PendingIdentifierInfos; /// \brief The set of lookup results that we have faked in order to support /// merging of partially deserialized decls but that we have not yet removed. llvm::SmallMapVector<IdentifierInfo *, SmallVector<NamedDecl*, 2>, 16> PendingFakeLookupResults; /// \brief The generation number of each identifier, which keeps track of /// the last time we loaded information about this identifier. llvm::DenseMap<IdentifierInfo *, unsigned> IdentifierGeneration; /// \brief Contains declarations and definitions that will be /// "interesting" to the ASTConsumer, when we get that AST consumer. /// /// "Interesting" declarations are those that have data that may /// need to be emitted, such as inline function definitions or /// Objective-C protocols. std::deque<Decl *> InterestingDecls; /// \brief The set of redeclarable declarations that have been deserialized /// since the last time the declaration chains were linked. llvm::SmallPtrSet<Decl *, 16> RedeclsDeserialized; /// \brief The list of redeclaration chains that still need to be /// reconstructed. /// /// Each element is the canonical declaration of the chain. /// Elements in this vector should be unique; use /// PendingDeclChainsKnown to ensure uniqueness. SmallVector<Decl *, 16> PendingDeclChains; /// \brief Keeps track of the elements added to PendingDeclChains. llvm::SmallSet<Decl *, 16> PendingDeclChainsKnown; /// \brief The list of canonical declarations whose redeclaration chains /// need to be marked as incomplete once we're done deserializing things. SmallVector<Decl *, 16> PendingIncompleteDeclChains; /// \brief The Decl IDs for the Sema/Lexical DeclContext of a Decl that has /// been loaded but its DeclContext was not set yet. struct PendingDeclContextInfo { Decl *D; serialization::GlobalDeclID SemaDC; serialization::GlobalDeclID LexicalDC; }; /// \brief The set of Decls that have been loaded but their DeclContexts are /// not set yet. /// /// The DeclContexts for these Decls will be set once recursive loading has /// been completed. std::deque<PendingDeclContextInfo> PendingDeclContextInfos; /// \brief The set of NamedDecls that have been loaded, but are members of a /// context that has been merged into another context where the corresponding /// declaration is either missing or has not yet been loaded. /// /// We will check whether the corresponding declaration is in fact missing /// once recursing loading has been completed. llvm::SmallVector<NamedDecl *, 16> PendingOdrMergeChecks; /// \brief Record definitions in which we found an ODR violation. llvm::SmallDenseMap<CXXRecordDecl *, llvm::TinyPtrVector<CXXRecordDecl *>, 2> PendingOdrMergeFailures; /// \brief DeclContexts in which we have diagnosed an ODR violation. llvm::SmallPtrSet<DeclContext*, 2> DiagnosedOdrMergeFailures; /// \brief The set of Objective-C categories that have been deserialized /// since the last time the declaration chains were linked. llvm::SmallPtrSet<ObjCCategoryDecl *, 16> CategoriesDeserialized; /// \brief The set of Objective-C class definitions that have already been /// loaded, for which we will need to check for categories whenever a new /// module is loaded. SmallVector<ObjCInterfaceDecl *, 16> ObjCClassesLoaded; /// \brief A mapping from a primary context for a declaration chain to the /// other declarations of that entity that also have name lookup tables. /// Used when we merge together two class definitions that have different /// sets of declared special member functions. llvm::DenseMap<const DeclContext*, SmallVector<const DeclContext*, 2>> MergedLookups; typedef llvm::DenseMap<Decl *, SmallVector<serialization::DeclID, 2> > KeyDeclsMap; /// \brief A mapping from canonical declarations to the set of global /// declaration IDs for key declaration that have been merged with that /// canonical declaration. A key declaration is a formerly-canonical /// declaration whose module did not import any other key declaration for that /// entity. These are the IDs that we use as keys when finding redecl chains. KeyDeclsMap KeyDecls; /// \brief A mapping from DeclContexts to the semantic DeclContext that we /// are treating as the definition of the entity. This is used, for instance, /// when merging implicit instantiations of class templates across modules. llvm::DenseMap<DeclContext *, DeclContext *> MergedDeclContexts; /// \brief A mapping from canonical declarations of enums to their canonical /// definitions. Only populated when using modules in C++. llvm::DenseMap<EnumDecl *, EnumDecl *> EnumDefinitions; /// \brief When reading a Stmt tree, Stmt operands are placed in this stack. SmallVector<Stmt *, 16> StmtStack; /// \brief What kind of records we are reading. enum ReadingKind { Read_None, Read_Decl, Read_Type, Read_Stmt }; /// \brief What kind of records we are reading. ReadingKind ReadingKind; /// \brief RAII object to change the reading kind. class ReadingKindTracker { ASTReader &Reader; enum ReadingKind PrevKind; ReadingKindTracker(const ReadingKindTracker &) = delete; void operator=(const ReadingKindTracker &) = delete; public: ReadingKindTracker(enum ReadingKind newKind, ASTReader &reader) : Reader(reader), PrevKind(Reader.ReadingKind) { Reader.ReadingKind = newKind; } ~ReadingKindTracker() { Reader.ReadingKind = PrevKind; } }; /// \brief Suggested contents of the predefines buffer, after this /// PCH file has been processed. /// /// In most cases, this string will be empty, because the predefines /// buffer computed to build the PCH file will be identical to the /// predefines buffer computed from the command line. However, when /// there are differences that the PCH reader can work around, this /// predefines buffer may contain additional definitions. std::string SuggestedPredefines; /// \brief Reads a statement from the specified cursor. Stmt *ReadStmtFromStream(ModuleFile &F); struct InputFileInfo { std::string Filename; off_t StoredSize; time_t StoredTime; bool Overridden; }; /// \brief Reads the stored information about an input file. InputFileInfo readInputFileInfo(ModuleFile &F, unsigned ID); /// \brief A convenience method to read the filename from an input file. std::string getInputFileName(ModuleFile &F, unsigned ID); /// \brief Retrieve the file entry and 'overridden' bit for an input /// file in the given module file. serialization::InputFile getInputFile(ModuleFile &F, unsigned ID, bool Complain = true); public: void ResolveImportedPath(ModuleFile &M, std::string &Filename); static void ResolveImportedPath(std::string &Filename, StringRef Prefix); /// \brief Returns the first key declaration for the given declaration. This /// is one that is formerly-canonical (or still canonical) and whose module /// did not import any other key declaration of the entity. Decl *getKeyDeclaration(Decl *D) { D = D->getCanonicalDecl(); if (D->isFromASTFile()) return D; auto I = KeyDecls.find(D); if (I == KeyDecls.end() || I->second.empty()) return D; return GetExistingDecl(I->second[0]); } const Decl *getKeyDeclaration(const Decl *D) { return getKeyDeclaration(const_cast<Decl*>(D)); } /// \brief Run a callback on each imported key declaration of \p D. template <typename Fn> void forEachImportedKeyDecl(const Decl *D, Fn Visit) { D = D->getCanonicalDecl(); if (D->isFromASTFile()) Visit(D); auto It = KeyDecls.find(const_cast<Decl*>(D)); if (It != KeyDecls.end()) for (auto ID : It->second) Visit(GetExistingDecl(ID)); } private: struct ImportedModule { ModuleFile *Mod; ModuleFile *ImportedBy; SourceLocation ImportLoc; ImportedModule(ModuleFile *Mod, ModuleFile *ImportedBy, SourceLocation ImportLoc) : Mod(Mod), ImportedBy(ImportedBy), ImportLoc(ImportLoc) { } }; ASTReadResult ReadASTCore(StringRef FileName, ModuleKind Type, SourceLocation ImportLoc, ModuleFile *ImportedBy, SmallVectorImpl<ImportedModule> &Loaded, off_t ExpectedSize, time_t ExpectedModTime, serialization::ASTFileSignature ExpectedSignature, unsigned ClientLoadCapabilities); ASTReadResult ReadControlBlock(ModuleFile &F, SmallVectorImpl<ImportedModule> &Loaded, const ModuleFile *ImportedBy, unsigned ClientLoadCapabilities); ASTReadResult ReadASTBlock(ModuleFile &F, unsigned ClientLoadCapabilities); bool ParseLineTable(ModuleFile &F, const RecordData &Record); bool ReadSourceManagerBlock(ModuleFile &F); llvm::BitstreamCursor &SLocCursorForID(int ID); SourceLocation getImportLocation(ModuleFile *F); ASTReadResult ReadModuleMapFileBlock(RecordData &Record, ModuleFile &F, const ModuleFile *ImportedBy, unsigned ClientLoadCapabilities); ASTReadResult ReadSubmoduleBlock(ModuleFile &F, unsigned ClientLoadCapabilities); static bool ParseLanguageOptions(const RecordData &Record, bool Complain, ASTReaderListener &Listener, bool AllowCompatibleDifferences); static bool ParseTargetOptions(const RecordData &Record, bool Complain, ASTReaderListener &Listener, bool AllowCompatibleDifferences); static bool ParseDiagnosticOptions(const RecordData &Record, bool Complain, ASTReaderListener &Listener); static bool ParseFileSystemOptions(const RecordData &Record, bool Complain, ASTReaderListener &Listener); static bool ParseHeaderSearchOptions(const RecordData &Record, bool Complain, ASTReaderListener &Listener); static bool ParsePreprocessorOptions(const RecordData &Record, bool Complain, ASTReaderListener &Listener, std::string &SuggestedPredefines); struct RecordLocation { RecordLocation(ModuleFile *M, uint64_t O) : F(M), Offset(O) {} ModuleFile *F; uint64_t Offset; }; QualType readTypeRecord(unsigned Index); void readExceptionSpec(ModuleFile &ModuleFile, SmallVectorImpl<QualType> &ExceptionStorage, FunctionProtoType::ExceptionSpecInfo &ESI, const RecordData &Record, unsigned &Index); RecordLocation TypeCursorForIndex(unsigned Index); void LoadedDecl(unsigned Index, Decl *D); Decl *ReadDeclRecord(serialization::DeclID ID); void markIncompleteDeclChain(Decl *Canon); /// \brief Returns the most recent declaration of a declaration (which must be /// of a redeclarable kind) that is either local or has already been loaded /// merged into its redecl chain. Decl *getMostRecentExistingDecl(Decl *D); RecordLocation DeclCursorForID(serialization::DeclID ID, unsigned &RawLocation); void loadDeclUpdateRecords(serialization::DeclID ID, Decl *D); void loadPendingDeclChain(Decl *D); void loadObjCCategories(serialization::GlobalDeclID ID, ObjCInterfaceDecl *D, unsigned PreviousGeneration = 0); RecordLocation getLocalBitOffset(uint64_t GlobalOffset); uint64_t getGlobalBitOffset(ModuleFile &M, uint32_t LocalOffset); /// \brief Returns the first preprocessed entity ID that begins or ends after /// \arg Loc. serialization::PreprocessedEntityID findPreprocessedEntity(SourceLocation Loc, bool EndsAfter) const; /// \brief Find the next module that contains entities and return the ID /// of the first entry. /// /// \param SLocMapI points at a chunk of a module that contains no /// preprocessed entities or the entities it contains are not the /// ones we are looking for. serialization::PreprocessedEntityID findNextPreprocessedEntity( GlobalSLocOffsetMapType::const_iterator SLocMapI) const; /// \brief Returns (ModuleFile, Local index) pair for \p GlobalIndex of a /// preprocessed entity. std::pair<ModuleFile *, unsigned> getModulePreprocessedEntity(unsigned GlobalIndex); /// \brief Returns (begin, end) pair for the preprocessed entities of a /// particular module. llvm::iterator_range<PreprocessingRecord::iterator> getModulePreprocessedEntities(ModuleFile &Mod) const; class ModuleDeclIterator : public llvm::iterator_adaptor_base< ModuleDeclIterator, const serialization::LocalDeclID *, std::random_access_iterator_tag, const Decl *, ptrdiff_t, const Decl *, const Decl *> { ASTReader *Reader; ModuleFile *Mod; public: ModuleDeclIterator() : iterator_adaptor_base(nullptr), Reader(nullptr), Mod(nullptr) {} ModuleDeclIterator(ASTReader *Reader, ModuleFile *Mod, const serialization::LocalDeclID *Pos) : iterator_adaptor_base(Pos), Reader(Reader), Mod(Mod) {} value_type operator*() const { return Reader->GetDecl(Reader->getGlobalDeclID(*Mod, *I)); } value_type operator->() const { return **this; } bool operator==(const ModuleDeclIterator &RHS) const { assert(Reader == RHS.Reader && Mod == RHS.Mod); return I == RHS.I; } }; llvm::iterator_range<ModuleDeclIterator> getModuleFileLevelDecls(ModuleFile &Mod); void PassInterestingDeclsToConsumer(); void PassInterestingDeclToConsumer(Decl *D); void finishPendingActions(); void diagnoseOdrViolations(); void pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name); void addPendingDeclContextInfo(Decl *D, serialization::GlobalDeclID SemaDC, serialization::GlobalDeclID LexicalDC) { assert(D); PendingDeclContextInfo Info = { D, SemaDC, LexicalDC }; PendingDeclContextInfos.push_back(Info); } /// \brief Produce an error diagnostic and return true. /// /// This routine should only be used for fatal errors that have to /// do with non-routine failures (e.g., corrupted AST file). void Error(StringRef Msg); void Error(unsigned DiagID, StringRef Arg1 = StringRef(), StringRef Arg2 = StringRef()); ASTReader(const ASTReader &) = delete; void operator=(const ASTReader &) = delete; public: /// \brief Load the AST file and validate its contents against the given /// Preprocessor. /// /// \param PP the preprocessor associated with the context in which this /// precompiled header will be loaded. /// /// \param Context the AST context that this precompiled header will be /// loaded into. /// /// \param PCHContainerOps the PCHContainerOperations to use for loading and /// creating modules. /// /// \param isysroot If non-NULL, the system include path specified by the /// user. This is only used with relocatable PCH files. If non-NULL, /// a relocatable PCH file will use the default path "/". /// /// \param DisableValidation If true, the AST reader will suppress most /// of its regular consistency checking, allowing the use of precompiled /// headers that cannot be determined to be compatible. /// /// \param AllowASTWithCompilerErrors If true, the AST reader will accept an /// AST file the was created out of an AST with compiler errors, /// otherwise it will reject it. /// /// \param AllowConfigurationMismatch If true, the AST reader will not check /// for configuration differences between the AST file and the invocation. /// /// \param ValidateSystemInputs If true, the AST reader will validate /// system input files in addition to user input files. This is only /// meaningful if \p DisableValidation is false. /// /// \param UseGlobalIndex If true, the AST reader will try to load and use /// the global module index. /// /// \param ReadTimer If non-null, a timer used to track the time spent /// deserializing. ASTReader(Preprocessor &PP, ASTContext &Context, const PCHContainerReader &PCHContainerRdr, StringRef isysroot = "", bool DisableValidation = false, bool AllowASTWithCompilerErrors = false, bool AllowConfigurationMismatch = false, bool ValidateSystemInputs = false, bool UseGlobalIndex = true, std::unique_ptr<llvm::Timer> ReadTimer = {}); ~ASTReader() override; SourceManager &getSourceManager() const { return SourceMgr; } FileManager &getFileManager() const { return FileMgr; } /// \brief Flags that indicate what kind of AST loading failures the client /// of the AST reader can directly handle. /// /// When a client states that it can handle a particular kind of failure, /// the AST reader will not emit errors when producing that kind of failure. enum LoadFailureCapabilities { /// \brief The client can't handle any AST loading failures. ARR_None = 0, /// \brief The client can handle an AST file that cannot load because it /// is missing. ARR_Missing = 0x1, /// \brief The client can handle an AST file that cannot load because it /// is out-of-date relative to its input files. ARR_OutOfDate = 0x2, /// \brief The client can handle an AST file that cannot load because it /// was built with a different version of Clang. ARR_VersionMismatch = 0x4, /// \brief The client can handle an AST file that cannot load because it's /// compiled configuration doesn't match that of the context it was /// loaded into. ARR_ConfigurationMismatch = 0x8 }; /// \brief Load the AST file designated by the given file name. /// /// \param FileName The name of the AST file to load. /// /// \param Type The kind of AST being loaded, e.g., PCH, module, main file, /// or preamble. /// /// \param ImportLoc the location where the module file will be considered as /// imported from. For non-module AST types it should be invalid. /// /// \param ClientLoadCapabilities The set of client load-failure /// capabilities, represented as a bitset of the enumerators of /// LoadFailureCapabilities. ASTReadResult ReadAST(const std::string &FileName, ModuleKind Type, SourceLocation ImportLoc, unsigned ClientLoadCapabilities); /// \brief Make the entities in the given module and any of its (non-explicit) /// submodules visible to name lookup. /// /// \param Mod The module whose names should be made visible. /// /// \param NameVisibility The level of visibility to give the names in the /// module. Visibility can only be increased over time. /// /// \param ImportLoc The location at which the import occurs. void makeModuleVisible(Module *Mod, Module::NameVisibilityKind NameVisibility, SourceLocation ImportLoc); /// \brief Make the names within this set of hidden names visible. void makeNamesVisible(const HiddenNames &Names, Module *Owner); /// \brief Take the AST callbacks listener. std::unique_ptr<ASTReaderListener> takeListener() { return std::move(Listener); } /// \brief Set the AST callbacks listener. void setListener(std::unique_ptr<ASTReaderListener> Listener) { this->Listener = std::move(Listener); } /// \brief Add an AST callback listener. /// /// Takes ownership of \p L. void addListener(std::unique_ptr<ASTReaderListener> L) { if (Listener) L = llvm::make_unique<ChainedASTReaderListener>(std::move(L), std::move(Listener)); Listener = std::move(L); } /// RAII object to temporarily add an AST callback listener. class ListenerScope { ASTReader &Reader; bool Chained; public: ListenerScope(ASTReader &Reader, std::unique_ptr<ASTReaderListener> L) : Reader(Reader), Chained(false) { auto Old = Reader.takeListener(); if (Old) { Chained = true; L = llvm::make_unique<ChainedASTReaderListener>(std::move(L), std::move(Old)); } Reader.setListener(std::move(L)); } ~ListenerScope() { auto New = Reader.takeListener(); if (Chained) Reader.setListener(static_cast<ChainedASTReaderListener *>(New.get()) ->takeSecond()); } }; /// \brief Set the AST deserialization listener. void setDeserializationListener(ASTDeserializationListener *Listener, bool TakeOwnership = false); /// \brief Determine whether this AST reader has a global index. bool hasGlobalIndex() const { return (bool)GlobalIndex; } /// \brief Return global module index. GlobalModuleIndex *getGlobalIndex() { return GlobalIndex.get(); } /// \brief Reset reader for a reload try. void resetForReload() { TriedLoadingGlobalIndex = false; } /// \brief Attempts to load the global index. /// /// \returns true if loading the global index has failed for any reason. bool loadGlobalIndex(); /// \brief Determine whether we tried to load the global index, but failed, /// e.g., because it is out-of-date or does not exist. bool isGlobalIndexUnavailable() const; /// \brief Initializes the ASTContext void InitializeContext(); /// \brief Update the state of Sema after loading some additional modules. void UpdateSema(); /// \brief Add in-memory (virtual file) buffer. void addInMemoryBuffer(StringRef &FileName, std::unique_ptr<llvm::MemoryBuffer> Buffer) { ModuleMgr.addInMemoryBuffer(FileName, std::move(Buffer)); } /// \brief Finalizes the AST reader's state before writing an AST file to /// disk. /// /// This operation may undo temporary state in the AST that should not be /// emitted. void finalizeForWriting(); /// \brief Retrieve the module manager. ModuleManager &getModuleManager() { return ModuleMgr; } /// \brief Retrieve the preprocessor. Preprocessor &getPreprocessor() const { return PP; } /// \brief Retrieve the name of the original source file name for the primary /// module file. StringRef getOriginalSourceFile() { return ModuleMgr.getPrimaryModule().OriginalSourceFileName; } /// \brief Retrieve the name of the original source file name directly from /// the AST file, without actually loading the AST file. static std::string getOriginalSourceFile(const std::string &ASTFileName, FileManager &FileMgr, const PCHContainerReader &PCHContainerRdr, DiagnosticsEngine &Diags); /// \brief Read the control block for the named AST file. /// /// \returns true if an error occurred, false otherwise. static bool readASTFileControlBlock(StringRef Filename, FileManager &FileMgr, const PCHContainerReader &PCHContainerRdr, ASTReaderListener &Listener); /// \brief Determine whether the given AST file is acceptable to load into a /// translation unit with the given language and target options. static bool isAcceptableASTFile(StringRef Filename, FileManager &FileMgr, const PCHContainerReader &PCHContainerRdr, const LangOptions &LangOpts, const TargetOptions &TargetOpts, const PreprocessorOptions &PPOpts, std::string ExistingModuleCachePath); /// \brief Returns the suggested contents of the predefines buffer, /// which contains a (typically-empty) subset of the predefines /// build prior to including the precompiled header. const std::string &getSuggestedPredefines() { return SuggestedPredefines; } /// \brief Read a preallocated preprocessed entity from the external source. /// /// \returns null if an error occurred that prevented the preprocessed /// entity from being loaded. PreprocessedEntity *ReadPreprocessedEntity(unsigned Index) override; /// \brief Returns a pair of [Begin, End) indices of preallocated /// preprocessed entities that \p Range encompasses. std::pair<unsigned, unsigned> findPreprocessedEntitiesInRange(SourceRange Range) override; /// \brief Optionally returns true or false if the preallocated preprocessed /// entity with index \p Index came from file \p FID. Optional<bool> isPreprocessedEntityInFileID(unsigned Index, FileID FID) override; /// \brief Read the header file information for the given file entry. HeaderFileInfo GetHeaderFileInfo(const FileEntry *FE) override; void ReadPragmaDiagnosticMappings(DiagnosticsEngine &Diag); /// \brief Returns the number of source locations found in the chain. unsigned getTotalNumSLocs() const { return TotalNumSLocEntries; } /// \brief Returns the number of identifiers found in the chain. unsigned getTotalNumIdentifiers() const { return static_cast<unsigned>(IdentifiersLoaded.size()); } /// \brief Returns the number of macros found in the chain. unsigned getTotalNumMacros() const { return static_cast<unsigned>(MacrosLoaded.size()); } /// \brief Returns the number of types found in the chain. unsigned getTotalNumTypes() const { return static_cast<unsigned>(TypesLoaded.size()); } /// \brief Returns the number of declarations found in the chain. unsigned getTotalNumDecls() const { return static_cast<unsigned>(DeclsLoaded.size()); } /// \brief Returns the number of submodules known. unsigned getTotalNumSubmodules() const { return static_cast<unsigned>(SubmodulesLoaded.size()); } /// \brief Returns the number of selectors found in the chain. unsigned getTotalNumSelectors() const { return static_cast<unsigned>(SelectorsLoaded.size()); } /// \brief Returns the number of preprocessed entities known to the AST /// reader. unsigned getTotalNumPreprocessedEntities() const { unsigned Result = 0; for (ModuleConstIterator I = ModuleMgr.begin(), E = ModuleMgr.end(); I != E; ++I) { Result += (*I)->NumPreprocessedEntities; } return Result; } /// \brief Reads a TemplateArgumentLocInfo appropriate for the /// given TemplateArgument kind. TemplateArgumentLocInfo GetTemplateArgumentLocInfo(ModuleFile &F, TemplateArgument::ArgKind Kind, const RecordData &Record, unsigned &Idx); /// \brief Reads a TemplateArgumentLoc. TemplateArgumentLoc ReadTemplateArgumentLoc(ModuleFile &F, const RecordData &Record, unsigned &Idx); const ASTTemplateArgumentListInfo* ReadASTTemplateArgumentListInfo(ModuleFile &F, const RecordData &Record, unsigned &Index); /// \brief Reads a declarator info from the given record. TypeSourceInfo *GetTypeSourceInfo(ModuleFile &F, const RecordData &Record, unsigned &Idx); /// \brief Resolve a type ID into a type, potentially building a new /// type. QualType GetType(serialization::TypeID ID); /// \brief Resolve a local type ID within a given AST file into a type. QualType getLocalType(ModuleFile &F, unsigned LocalID); /// \brief Map a local type ID within a given AST file into a global type ID. serialization::TypeID getGlobalTypeID(ModuleFile &F, unsigned LocalID) const; /// \brief Read a type from the current position in the given record, which /// was read from the given AST file. QualType readType(ModuleFile &F, const RecordData &Record, unsigned &Idx) { if (Idx >= Record.size()) return QualType(); return getLocalType(F, Record[Idx++]); } /// \brief Map from a local declaration ID within a given module to a /// global declaration ID. serialization::DeclID getGlobalDeclID(ModuleFile &F, serialization::LocalDeclID LocalID) const; /// \brief Returns true if global DeclID \p ID originated from module \p M. bool isDeclIDFromModule(serialization::GlobalDeclID ID, ModuleFile &M) const; /// \brief Retrieve the module file that owns the given declaration, or NULL /// if the declaration is not from a module file. ModuleFile *getOwningModuleFile(const Decl *D); /// \brief Get the best name we know for the module that owns the given /// declaration, or an empty string if the declaration is not from a module. std::string getOwningModuleNameForDiagnostic(const Decl *D); /// \brief Returns the source location for the decl \p ID. SourceLocation getSourceLocationForDeclID(serialization::GlobalDeclID ID); /// \brief Resolve a declaration ID into a declaration, potentially /// building a new declaration. Decl *GetDecl(serialization::DeclID ID); Decl *GetExternalDecl(uint32_t ID) override; /// \brief Resolve a declaration ID into a declaration. Return 0 if it's not /// been loaded yet. Decl *GetExistingDecl(serialization::DeclID ID); /// \brief Reads a declaration with the given local ID in the given module. Decl *GetLocalDecl(ModuleFile &F, uint32_t LocalID) { return GetDecl(getGlobalDeclID(F, LocalID)); } /// \brief Reads a declaration with the given local ID in the given module. /// /// \returns The requested declaration, casted to the given return type. template<typename T> T *GetLocalDeclAs(ModuleFile &F, uint32_t LocalID) { return cast_or_null<T>(GetLocalDecl(F, LocalID)); } /// \brief Map a global declaration ID into the declaration ID used to /// refer to this declaration within the given module fule. /// /// \returns the global ID of the given declaration as known in the given /// module file. serialization::DeclID mapGlobalIDToModuleFileGlobalID(ModuleFile &M, serialization::DeclID GlobalID); /// \brief Reads a declaration ID from the given position in a record in the /// given module. /// /// \returns The declaration ID read from the record, adjusted to a global ID. serialization::DeclID ReadDeclID(ModuleFile &F, const RecordData &Record, unsigned &Idx); /// \brief Reads a declaration from the given position in a record in the /// given module. Decl *ReadDecl(ModuleFile &F, const RecordData &R, unsigned &I) { return GetDecl(ReadDeclID(F, R, I)); } /// \brief Reads a declaration from the given position in a record in the /// given module. /// /// \returns The declaration read from this location, casted to the given /// result type. template<typename T> T *ReadDeclAs(ModuleFile &F, const RecordData &R, unsigned &I) { return cast_or_null<T>(GetDecl(ReadDeclID(F, R, I))); } /// \brief If any redeclarations of \p D have been imported since it was /// last checked, this digs out those redeclarations and adds them to the /// redeclaration chain for \p D. void CompleteRedeclChain(const Decl *D) override; /// \brief Read a CXXBaseSpecifiers ID form the given record and /// return its global bit offset. uint64_t readCXXBaseSpecifiers(ModuleFile &M, const RecordData &Record, unsigned &Idx); CXXBaseSpecifier *GetExternalCXXBaseSpecifiers(uint64_t Offset) override; /// \brief Resolve the offset of a statement into a statement. /// /// This operation will read a new statement from the external /// source each time it is called, and is meant to be used via a /// LazyOffsetPtr (which is used by Decls for the body of functions, etc). Stmt *GetExternalDeclStmt(uint64_t Offset) override; /// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the /// specified cursor. Read the abbreviations that are at the top of the block /// and then leave the cursor pointing into the block. bool ReadBlockAbbrevs(llvm::BitstreamCursor &Cursor, unsigned BlockID); /// \brief Finds all the visible declarations with a given name. /// The current implementation of this method just loads the entire /// lookup table as unmaterialized references. bool FindExternalVisibleDeclsByName(const DeclContext *DC, DeclarationName Name) override; /// \brief Read all of the declarations lexically stored in a /// declaration context. /// /// \param DC The declaration context whose declarations will be /// read. /// /// \param Decls Vector that will contain the declarations loaded /// from the external source. The caller is responsible for merging /// these declarations with any declarations already stored in the /// declaration context. /// /// \returns true if there was an error while reading the /// declarations for this declaration context. ExternalLoadResult FindExternalLexicalDecls(const DeclContext *DC, bool (*isKindWeWant)(Decl::Kind), SmallVectorImpl<Decl*> &Decls) override; /// \brief Get the decls that are contained in a file in the Offset/Length /// range. \p Length can be 0 to indicate a point at \p Offset instead of /// a range. void FindFileRegionDecls(FileID File, unsigned Offset, unsigned Length, SmallVectorImpl<Decl *> &Decls) override; /// \brief Notify ASTReader that we started deserialization of /// a decl or type so until FinishedDeserializing is called there may be /// decls that are initializing. Must be paired with FinishedDeserializing. void StartedDeserializing() override; /// \brief Notify ASTReader that we finished the deserialization of /// a decl or type. Must be paired with StartedDeserializing. void FinishedDeserializing() override; /// \brief Function that will be invoked when we begin parsing a new /// translation unit involving this external AST source. /// /// This function will provide all of the external definitions to /// the ASTConsumer. void StartTranslationUnit(ASTConsumer *Consumer) override; /// \brief Print some statistics about AST usage. void PrintStats() override; /// \brief Dump information about the AST reader to standard error. void dump(); /// Return the amount of memory used by memory buffers, breaking down /// by heap-backed versus mmap'ed memory. void getMemoryBufferSizes(MemoryBufferSizes &sizes) const override; /// \brief Initialize the semantic source with the Sema instance /// being used to perform semantic analysis on the abstract syntax /// tree. void InitializeSema(Sema &S) override; /// \brief Inform the semantic consumer that Sema is no longer available. void ForgetSema() override { SemaObj = nullptr; } /// \brief Retrieve the IdentifierInfo for the named identifier. /// /// This routine builds a new IdentifierInfo for the given identifier. If any /// declarations with this name are visible from translation unit scope, their /// declarations will be deserialized and introduced into the declaration /// chain of the identifier. virtual IdentifierInfo *get(const char *NameStart, const char *NameEnd); IdentifierInfo *get(StringRef Name) override { return get(Name.begin(), Name.end()); } /// \brief Retrieve an iterator into the set of all identifiers /// in all loaded AST files. IdentifierIterator *getIdentifiers() override; /// \brief Load the contents of the global method pool for a given /// selector. void ReadMethodPool(Selector Sel) override; /// \brief Load the set of namespaces that are known to the external source, /// which will be used during typo correction. void ReadKnownNamespaces( SmallVectorImpl<NamespaceDecl *> &Namespaces) override; void ReadUndefinedButUsed( llvm::DenseMap<NamedDecl *, SourceLocation> &Undefined) override; void ReadMismatchingDeleteExpressions(llvm::MapVector< FieldDecl *, llvm::SmallVector<std::pair<SourceLocation, bool>, 4>> & Exprs) override; void ReadTentativeDefinitions( SmallVectorImpl<VarDecl *> &TentativeDefs) override; void ReadUnusedFileScopedDecls( SmallVectorImpl<const DeclaratorDecl *> &Decls) override; void ReadDelegatingConstructors( SmallVectorImpl<CXXConstructorDecl *> &Decls) override; void ReadExtVectorDecls(SmallVectorImpl<TypedefNameDecl *> &Decls) override; void ReadUnusedLocalTypedefNameCandidates( llvm::SmallSetVector<const TypedefNameDecl *, 4> &Decls) override; void ReadReferencedSelectors( SmallVectorImpl<std::pair<Selector, SourceLocation> > &Sels) override; void ReadWeakUndeclaredIdentifiers( SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo> > &WI) override; void ReadUsedVTables(SmallVectorImpl<ExternalVTableUse> &VTables) override; void ReadPendingInstantiations( SmallVectorImpl<std::pair<ValueDecl *, SourceLocation> > &Pending) override; void ReadLateParsedTemplates( llvm::MapVector<const FunctionDecl *, LateParsedTemplate *> &LPTMap) override; /// \brief Load a selector from disk, registering its ID if it exists. void LoadSelector(Selector Sel); void SetIdentifierInfo(unsigned ID, IdentifierInfo *II); void SetGloballyVisibleDecls(IdentifierInfo *II, const SmallVectorImpl<uint32_t> &DeclIDs, SmallVectorImpl<Decl *> *Decls = nullptr); /// \brief Report a diagnostic. DiagnosticBuilder Diag(unsigned DiagID); /// \brief Report a diagnostic. DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID); IdentifierInfo *DecodeIdentifierInfo(serialization::IdentifierID ID); IdentifierInfo *GetIdentifierInfo(ModuleFile &M, const RecordData &Record, unsigned &Idx) { return DecodeIdentifierInfo(getGlobalIdentifierID(M, Record[Idx++])); } IdentifierInfo *GetIdentifier(serialization::IdentifierID ID) override { // Note that we are loading an identifier. Deserializing AnIdentifier(this); return DecodeIdentifierInfo(ID); } IdentifierInfo *getLocalIdentifier(ModuleFile &M, unsigned LocalID); serialization::IdentifierID getGlobalIdentifierID(ModuleFile &M, unsigned LocalID); void resolvePendingMacro(IdentifierInfo *II, const PendingMacroInfo &PMInfo); /// \brief Retrieve the macro with the given ID. MacroInfo *getMacro(serialization::MacroID ID); /// \brief Retrieve the global macro ID corresponding to the given local /// ID within the given module file. serialization::MacroID getGlobalMacroID(ModuleFile &M, unsigned LocalID); /// \brief Read the source location entry with index ID. bool ReadSLocEntry(int ID) override; /// \brief Retrieve the module import location and module name for the /// given source manager entry ID. std::pair<SourceLocation, StringRef> getModuleImportLoc(int ID) override; /// \brief Retrieve the global submodule ID given a module and its local ID /// number. serialization::SubmoduleID getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID); /// \brief Retrieve the submodule that corresponds to a global submodule ID. /// Module *getSubmodule(serialization::SubmoduleID GlobalID); /// \brief Retrieve the module that corresponds to the given module ID. /// /// Note: overrides method in ExternalASTSource Module *getModule(unsigned ID) override; /// \brief Return a descriptor for the corresponding module. llvm::Optional<ASTSourceDescriptor> getSourceDescriptor(unsigned ID) override; /// \brief Return a descriptor for the module. ASTSourceDescriptor getSourceDescriptor(const Module &M) override; /// \brief Retrieve a selector from the given module with its local ID /// number. Selector getLocalSelector(ModuleFile &M, unsigned LocalID); Selector DecodeSelector(serialization::SelectorID Idx); Selector GetExternalSelector(serialization::SelectorID ID) override; uint32_t GetNumExternalSelectors() override; Selector ReadSelector(ModuleFile &M, const RecordData &Record, unsigned &Idx) { return getLocalSelector(M, Record[Idx++]); } /// \brief Retrieve the global selector ID that corresponds to this /// the local selector ID in a given module. serialization::SelectorID getGlobalSelectorID(ModuleFile &F, unsigned LocalID) const; /// \brief Read a declaration name. DeclarationName ReadDeclarationName(ModuleFile &F, const RecordData &Record, unsigned &Idx); void ReadDeclarationNameLoc(ModuleFile &F, DeclarationNameLoc &DNLoc, DeclarationName Name, const RecordData &Record, unsigned &Idx); void ReadDeclarationNameInfo(ModuleFile &F, DeclarationNameInfo &NameInfo, const RecordData &Record, unsigned &Idx); void ReadQualifierInfo(ModuleFile &F, QualifierInfo &Info, const RecordData &Record, unsigned &Idx); NestedNameSpecifier *ReadNestedNameSpecifier(ModuleFile &F, const RecordData &Record, unsigned &Idx); NestedNameSpecifierLoc ReadNestedNameSpecifierLoc(ModuleFile &F, const RecordData &Record, unsigned &Idx); /// \brief Read a template name. TemplateName ReadTemplateName(ModuleFile &F, const RecordData &Record, unsigned &Idx); /// \brief Read a template argument. TemplateArgument ReadTemplateArgument(ModuleFile &F, const RecordData &Record,unsigned &Idx); /// \brief Read a template parameter list. TemplateParameterList *ReadTemplateParameterList(ModuleFile &F, const RecordData &Record, unsigned &Idx); /// \brief Read a template argument array. void ReadTemplateArgumentList(SmallVectorImpl<TemplateArgument> &TemplArgs, ModuleFile &F, const RecordData &Record, unsigned &Idx); /// \brief Read a UnresolvedSet structure. void ReadUnresolvedSet(ModuleFile &F, LazyASTUnresolvedSet &Set, const RecordData &Record, unsigned &Idx); /// \brief Read a C++ base specifier. CXXBaseSpecifier ReadCXXBaseSpecifier(ModuleFile &F, const RecordData &Record,unsigned &Idx); /// \brief Read a CXXCtorInitializer array. CXXCtorInitializer ** ReadCXXCtorInitializers(ModuleFile &F, const RecordData &Record, unsigned &Idx); /// \brief Read a CXXCtorInitializers ID from the given record and /// return its global bit offset. uint64_t ReadCXXCtorInitializersRef(ModuleFile &M, const RecordData &Record, unsigned &Idx); /// \brief Read the contents of a CXXCtorInitializer array. CXXCtorInitializer **GetExternalCXXCtorInitializers(uint64_t Offset) override; /// \brief Read a source location from raw form. SourceLocation ReadSourceLocation(ModuleFile &ModuleFile, unsigned Raw) const { SourceLocation Loc = SourceLocation::getFromRawEncoding(Raw); assert(ModuleFile.SLocRemap.find(Loc.getOffset()) != ModuleFile.SLocRemap.end() && "Cannot find offset to remap."); int Remap = ModuleFile.SLocRemap.find(Loc.getOffset())->second; return Loc.getLocWithOffset(Remap); } /// \brief Read a source location. SourceLocation ReadSourceLocation(ModuleFile &ModuleFile, const RecordDataImpl &Record, unsigned &Idx) { return ReadSourceLocation(ModuleFile, Record[Idx++]); } /// \brief Read a source range. SourceRange ReadSourceRange(ModuleFile &F, const RecordData &Record, unsigned &Idx); /// \brief Read an integral value llvm::APInt ReadAPInt(const RecordData &Record, unsigned &Idx); /// \brief Read a signed integral value llvm::APSInt ReadAPSInt(const RecordData &Record, unsigned &Idx); /// \brief Read a floating-point value llvm::APFloat ReadAPFloat(const RecordData &Record, const llvm::fltSemantics &Sem, unsigned &Idx); // \brief Read a string static std::string ReadString(const RecordData &Record, unsigned &Idx); // \brief Read a path std::string ReadPath(ModuleFile &F, const RecordData &Record, unsigned &Idx); /// \brief Read a version tuple. static VersionTuple ReadVersionTuple(const RecordData &Record, unsigned &Idx); CXXTemporary *ReadCXXTemporary(ModuleFile &F, const RecordData &Record, unsigned &Idx); /// \brief Reads attributes from the current stream position. void ReadAttributes(ModuleFile &F, AttrVec &Attrs, const RecordData &Record, unsigned &Idx); /// \brief Reads a statement. Stmt *ReadStmt(ModuleFile &F); /// \brief Reads an expression. Expr *ReadExpr(ModuleFile &F); /// \brief Reads a sub-statement operand during statement reading. Stmt *ReadSubStmt() { assert(ReadingKind == Read_Stmt && "Should be called only during statement reading!"); // Subexpressions are stored from last to first, so the next Stmt we need // is at the back of the stack. assert(!StmtStack.empty() && "Read too many sub-statements!"); return StmtStack.pop_back_val(); } /// \brief Reads a sub-expression operand during statement reading. Expr *ReadSubExpr(); /// \brief Reads a token out of a record. Token ReadToken(ModuleFile &M, const RecordDataImpl &Record, unsigned &Idx); /// \brief Reads the macro record located at the given offset. MacroInfo *ReadMacroRecord(ModuleFile &F, uint64_t Offset); /// \brief Determine the global preprocessed entity ID that corresponds to /// the given local ID within the given module. serialization::PreprocessedEntityID getGlobalPreprocessedEntityID(ModuleFile &M, unsigned LocalID) const; /// \brief Add a macro to deserialize its macro directive history. /// /// \param II The name of the macro. /// \param M The module file. /// \param MacroDirectivesOffset Offset of the serialized macro directive /// history. void addPendingMacro(IdentifierInfo *II, ModuleFile *M, uint64_t MacroDirectivesOffset); /// \brief Read the set of macros defined by this external macro source. void ReadDefinedMacros() override; /// \brief Update an out-of-date identifier. void updateOutOfDateIdentifier(IdentifierInfo &II) override; /// \brief Note that this identifier is up-to-date. void markIdentifierUpToDate(IdentifierInfo *II); /// \brief Load all external visible decls in the given DeclContext. void completeVisibleDeclsMap(const DeclContext *DC) override; /// \brief Retrieve the AST context that this AST reader supplements. ASTContext &getContext() { return Context; } // \brief Contains the IDs for declarations that were requested before we have // access to a Sema object. SmallVector<uint64_t, 16> PreloadedDeclIDs; /// \brief Retrieve the semantic analysis object used to analyze the /// translation unit in which the precompiled header is being /// imported. Sema *getSema() { return SemaObj; } /// \brief Retrieve the identifier table associated with the /// preprocessor. IdentifierTable &getIdentifierTable(); /// \brief Record that the given ID maps to the given switch-case /// statement. void RecordSwitchCaseID(SwitchCase *SC, unsigned ID); /// \brief Retrieve the switch-case statement with the given ID. SwitchCase *getSwitchCaseWithID(unsigned ID); void ClearSwitchCaseIDs(); /// \brief Cursors for comments blocks. SmallVector<std::pair<llvm::BitstreamCursor, serialization::ModuleFile *>, 8> CommentsCursors; //RIDErief Loads comments ranges. void ReadComments() override; /// Return all input files for the given module file. void getInputFiles(ModuleFile &F, SmallVectorImpl<serialization::InputFile> &Files); }; /// \brief Helper class that saves the current stream position and /// then restores it when destroyed. struct SavedStreamPosition { explicit SavedStreamPosition(llvm::BitstreamCursor &Cursor) : Cursor(Cursor), Offset(Cursor.GetCurrentBitNo()) { } ~SavedStreamPosition() { Cursor.JumpToBit(Offset); } private: llvm::BitstreamCursor &Cursor; uint64_t Offset; }; inline void PCHValidator::Error(const char *Msg) { Reader.Error(Msg); } } // end namespace clang #endif
0
repos/DirectXShaderCompiler/tools/clang/include/clang
repos/DirectXShaderCompiler/tools/clang/include/clang/Serialization/ASTDeserializationListener.h
//===- ASTDeserializationListener.h - Decl/Type PCH Read Events -*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines the ASTDeserializationListener class, which is notified // by the ASTReader whenever a type or declaration is deserialized. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_SERIALIZATION_ASTDESERIALIZATIONLISTENER_H #define LLVM_CLANG_SERIALIZATION_ASTDESERIALIZATIONLISTENER_H #include "clang/Basic/IdentifierTable.h" #include "clang/Serialization/ASTBitCodes.h" namespace clang { class Decl; class ASTReader; class QualType; class MacroDefinitionRecord; class MacroInfo; class Module; class ASTDeserializationListener { public: virtual ~ASTDeserializationListener(); /// \brief The ASTReader was initialized. virtual void ReaderInitialized(ASTReader *Reader) { } /// \brief An identifier was deserialized from the AST file. virtual void IdentifierRead(serialization::IdentID ID, IdentifierInfo *II) { } /// \brief A macro was read from the AST file. virtual void MacroRead(serialization::MacroID ID, MacroInfo *MI) { } /// \brief A type was deserialized from the AST file. The ID here has the /// qualifier bits already removed, and T is guaranteed to be locally /// unqualified. virtual void TypeRead(serialization::TypeIdx Idx, QualType T) { } /// \brief A decl was deserialized from the AST file. virtual void DeclRead(serialization::DeclID ID, const Decl *D) { } /// \brief A selector was read from the AST file. virtual void SelectorRead(serialization::SelectorID iD, Selector Sel) {} /// \brief A macro definition was read from the AST file. virtual void MacroDefinitionRead(serialization::PreprocessedEntityID, MacroDefinitionRecord *MD) {} /// \brief A module definition was read from the AST file. virtual void ModuleRead(serialization::SubmoduleID ID, Module *Mod) {} }; } #endif
0
repos/DirectXShaderCompiler/tools/clang/include/clang
repos/DirectXShaderCompiler/tools/clang/include/clang/Serialization/SerializationDiagnostic.h
//===--- SerializationDiagnostic.h - Serialization Diagnostics -*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_SERIALIZATION_SERIALIZATIONDIAGNOSTIC_H #define LLVM_CLANG_SERIALIZATION_SERIALIZATIONDIAGNOSTIC_H #include "clang/Basic/Diagnostic.h" namespace clang { namespace diag { enum { #define DIAG(ENUM,FLAGS,DEFAULT_MAPPING,DESC,GROUP,\ SFINAE,NOWERROR,SHOWINSYSHEADER,CATEGORY) ENUM, #define SERIALIZATIONSTART #include "clang/Basic/DiagnosticSerializationKinds.inc" #undef DIAG NUM_BUILTIN_SERIALIZATION_DIAGNOSTICS }; } // end namespace diag } // end namespace clang #endif
0
repos/DirectXShaderCompiler/tools/clang/include/clang
repos/DirectXShaderCompiler/tools/clang/include/clang/Serialization/Module.h
//===--- Module.h - Module description --------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines the Module class, which describes a module that has // been loaded from an AST file. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_SERIALIZATION_MODULE_H #define LLVM_CLANG_SERIALIZATION_MODULE_H #include "clang/Basic/SourceLocation.h" #include "clang/Serialization/ASTBitCodes.h" #include "clang/Serialization/ContinuousRangeMap.h" #include "llvm/ADT/SetVector.h" #include "llvm/Bitcode/BitstreamReader.h" #include "llvm/Support/Endian.h" #include <memory> #include <string> namespace llvm { template <typename Info> class OnDiskChainedHashTable; template <typename Info> class OnDiskIterableChainedHashTable; } namespace clang { class FileEntry; class DeclContext; class Module; namespace serialization { namespace reader { class ASTDeclContextNameLookupTrait; } /// \brief Specifies the kind of module that has been loaded. enum ModuleKind { MK_ImplicitModule, ///< File is an implicitly-loaded module. MK_ExplicitModule, ///< File is an explicitly-loaded module. MK_PCH, ///< File is a PCH file treated as such. MK_Preamble, ///< File is a PCH file treated as the preamble. MK_MainFile ///< File is a PCH file treated as the actual main file. }; /// \brief Information about the contents of a DeclContext. struct DeclContextInfo { DeclContextInfo() : NameLookupTableData(), LexicalDecls(), NumLexicalDecls() {} llvm::OnDiskIterableChainedHashTable<reader::ASTDeclContextNameLookupTrait> *NameLookupTableData; // an ASTDeclContextNameLookupTable. const KindDeclIDPair *LexicalDecls; unsigned NumLexicalDecls; }; /// \brief The input file that has been loaded from this AST file, along with /// bools indicating whether this was an overridden buffer or if it was /// out-of-date or not-found. class InputFile { enum { Overridden = 1, OutOfDate = 2, NotFound = 3 }; llvm::PointerIntPair<const FileEntry *, 2, unsigned> Val; public: InputFile() {} InputFile(const FileEntry *File, bool isOverridden = false, bool isOutOfDate = false) { assert(!(isOverridden && isOutOfDate) && "an overridden cannot be out-of-date"); unsigned intVal = 0; if (isOverridden) intVal = Overridden; else if (isOutOfDate) intVal = OutOfDate; Val.setPointerAndInt(File, intVal); } static InputFile getNotFound() { InputFile File; File.Val.setInt(NotFound); return File; } const FileEntry *getFile() const { return Val.getPointer(); } bool isOverridden() const { return Val.getInt() == Overridden; } bool isOutOfDate() const { return Val.getInt() == OutOfDate; } bool isNotFound() const { return Val.getInt() == NotFound; } }; typedef unsigned ASTFileSignature; /// \brief Information about a module that has been loaded by the ASTReader. /// /// Each instance of the Module class corresponds to a single AST file, which /// may be a precompiled header, precompiled preamble, a module, or an AST file /// of some sort loaded as the main file, all of which are specific formulations /// of the general notion of a "module". A module may depend on any number of /// other modules. class ModuleFile { public: ModuleFile(ModuleKind Kind, unsigned Generation); ~ModuleFile(); // === General information === /// \brief The index of this module in the list of modules. unsigned Index; /// \brief The type of this module. ModuleKind Kind; /// \brief The file name of the module file. std::string FileName; /// \brief The name of the module. std::string ModuleName; /// \brief The base directory of the module. std::string BaseDirectory; std::string getTimestampFilename() const { return FileName + ".timestamp"; } /// \brief The original source file name that was used to build the /// primary AST file, which may have been modified for /// relocatable-pch support. std::string OriginalSourceFileName; /// \brief The actual original source file name that was used to /// build this AST file. std::string ActualOriginalSourceFileName; /// \brief The file ID for the original source file that was used to /// build this AST file. FileID OriginalSourceFileID; /// \brief The directory that the PCH was originally created in. Used to /// allow resolving headers even after headers+PCH was moved to a new path. std::string OriginalDir; std::string ModuleMapPath; /// \brief Whether this precompiled header is a relocatable PCH file. bool RelocatablePCH; /// \brief The file entry for the module file. const FileEntry *File; /// \brief The signature of the module file, which may be used along with size /// and modification time to identify this particular file. ASTFileSignature Signature; /// \brief Whether this module has been directly imported by the /// user. bool DirectlyImported; /// \brief The generation of which this module file is a part. unsigned Generation; /// \brief The memory buffer that stores the data associated with /// this AST file. std::unique_ptr<llvm::MemoryBuffer> Buffer; /// \brief The size of this file, in bits. uint64_t SizeInBits; /// \brief The global bit offset (or base) of this module uint64_t GlobalBitOffset; /// \brief The bitstream reader from which we'll read the AST file. llvm::BitstreamReader StreamFile; /// \brief The main bitstream cursor for the main block. llvm::BitstreamCursor Stream; /// \brief The source location where the module was explicitly or implicitly /// imported in the local translation unit. /// /// If module A depends on and imports module B, both modules will have the /// same DirectImportLoc, but different ImportLoc (B's ImportLoc will be a /// source location inside module A). /// /// WARNING: This is largely useless. It doesn't tell you when a module was /// made visible, just when the first submodule of that module was imported. SourceLocation DirectImportLoc; /// \brief The source location where this module was first imported. SourceLocation ImportLoc; /// \brief The first source location in this module. SourceLocation FirstLoc; // === Input Files === /// \brief The cursor to the start of the input-files block. llvm::BitstreamCursor InputFilesCursor; /// \brief Offsets for all of the input file entries in the AST file. const llvm::support::unaligned_uint64_t *InputFileOffsets; /// \brief The input files that have been loaded from this AST file. std::vector<InputFile> InputFilesLoaded; /// \brief If non-zero, specifies the time when we last validated input /// files. Zero means we never validated them. /// /// The time is specified in seconds since the start of the Epoch. uint64_t InputFilesValidationTimestamp; // === Source Locations === /// \brief Cursor used to read source location entries. llvm::BitstreamCursor SLocEntryCursor; /// \brief The number of source location entries in this AST file. unsigned LocalNumSLocEntries; /// \brief The base ID in the source manager's view of this module. int SLocEntryBaseID; /// \brief The base offset in the source manager's view of this module. unsigned SLocEntryBaseOffset; /// \brief Offsets for all of the source location entries in the /// AST file. const uint32_t *SLocEntryOffsets; /// \brief SLocEntries that we're going to preload. SmallVector<uint64_t, 4> PreloadSLocEntries; /// \brief Remapping table for source locations in this module. ContinuousRangeMap<uint32_t, int, 2> SLocRemap; // === Identifiers === /// \brief The number of identifiers in this AST file. unsigned LocalNumIdentifiers; /// \brief Offsets into the identifier table data. /// /// This array is indexed by the identifier ID (-1), and provides /// the offset into IdentifierTableData where the string data is /// stored. const uint32_t *IdentifierOffsets; /// \brief Base identifier ID for identifiers local to this module. serialization::IdentID BaseIdentifierID; /// \brief Remapping table for identifier IDs in this module. ContinuousRangeMap<uint32_t, int, 2> IdentifierRemap; /// \brief Actual data for the on-disk hash table of identifiers. /// /// This pointer points into a memory buffer, where the on-disk hash /// table for identifiers actually lives. const char *IdentifierTableData; /// \brief A pointer to an on-disk hash table of opaque type /// IdentifierHashTable. void *IdentifierLookupTable; // === Macros === /// \brief The cursor to the start of the preprocessor block, which stores /// all of the macro definitions. llvm::BitstreamCursor MacroCursor; /// \brief The number of macros in this AST file. unsigned LocalNumMacros; /// \brief Offsets of macros in the preprocessor block. /// /// This array is indexed by the macro ID (-1), and provides /// the offset into the preprocessor block where macro definitions are /// stored. const uint32_t *MacroOffsets; /// \brief Base macro ID for macros local to this module. serialization::MacroID BaseMacroID; /// \brief Remapping table for macro IDs in this module. ContinuousRangeMap<uint32_t, int, 2> MacroRemap; /// \brief The offset of the start of the set of defined macros. uint64_t MacroStartOffset; // === Detailed PreprocessingRecord === /// \brief The cursor to the start of the (optional) detailed preprocessing /// record block. llvm::BitstreamCursor PreprocessorDetailCursor; /// \brief The offset of the start of the preprocessor detail cursor. uint64_t PreprocessorDetailStartOffset; /// \brief Base preprocessed entity ID for preprocessed entities local to /// this module. serialization::PreprocessedEntityID BasePreprocessedEntityID; /// \brief Remapping table for preprocessed entity IDs in this module. ContinuousRangeMap<uint32_t, int, 2> PreprocessedEntityRemap; const PPEntityOffset *PreprocessedEntityOffsets; unsigned NumPreprocessedEntities; // === Header search information === /// \brief The number of local HeaderFileInfo structures. unsigned LocalNumHeaderFileInfos; /// \brief Actual data for the on-disk hash table of header file /// information. /// /// This pointer points into a memory buffer, where the on-disk hash /// table for header file information actually lives. const char *HeaderFileInfoTableData; /// \brief The on-disk hash table that contains information about each of /// the header files. void *HeaderFileInfoTable; // === Submodule information === /// \brief The number of submodules in this module. unsigned LocalNumSubmodules; /// \brief Base submodule ID for submodules local to this module. serialization::SubmoduleID BaseSubmoduleID; /// \brief Remapping table for submodule IDs in this module. ContinuousRangeMap<uint32_t, int, 2> SubmoduleRemap; // === Selectors === /// \brief The number of selectors new to this file. /// /// This is the number of entries in SelectorOffsets. unsigned LocalNumSelectors; /// \brief Offsets into the selector lookup table's data array /// where each selector resides. const uint32_t *SelectorOffsets; /// \brief Base selector ID for selectors local to this module. serialization::SelectorID BaseSelectorID; /// \brief Remapping table for selector IDs in this module. ContinuousRangeMap<uint32_t, int, 2> SelectorRemap; /// \brief A pointer to the character data that comprises the selector table /// /// The SelectorOffsets table refers into this memory. const unsigned char *SelectorLookupTableData; /// \brief A pointer to an on-disk hash table of opaque type /// ASTSelectorLookupTable. /// /// This hash table provides the IDs of all selectors, and the associated /// instance and factory methods. void *SelectorLookupTable; // === Declarations === /// DeclsCursor - This is a cursor to the start of the DECLS_BLOCK block. It /// has read all the abbreviations at the start of the block and is ready to /// jump around with these in context. llvm::BitstreamCursor DeclsCursor; /// \brief The number of declarations in this AST file. unsigned LocalNumDecls; /// \brief Offset of each declaration within the bitstream, indexed /// by the declaration ID (-1). const DeclOffset *DeclOffsets; /// \brief Base declaration ID for declarations local to this module. serialization::DeclID BaseDeclID; /// \brief Remapping table for declaration IDs in this module. ContinuousRangeMap<uint32_t, int, 2> DeclRemap; /// \brief Mapping from the module files that this module file depends on /// to the base declaration ID for that module as it is understood within this /// module. /// /// This is effectively a reverse global-to-local mapping for declaration /// IDs, so that we can interpret a true global ID (for this translation unit) /// as a local ID (for this module file). llvm::DenseMap<ModuleFile *, serialization::DeclID> GlobalToLocalDeclIDs; /// \brief The number of C++ base specifier sets in this AST file. unsigned LocalNumCXXBaseSpecifiers; /// \brief Offset of each C++ base specifier set within the bitstream, /// indexed by the C++ base specifier set ID (-1). const uint32_t *CXXBaseSpecifiersOffsets; /// \brief The number of C++ ctor initializer lists in this AST file. unsigned LocalNumCXXCtorInitializers; /// \brief Offset of each C++ ctor initializer list within the bitstream, /// indexed by the C++ ctor initializer list ID minus 1. const uint32_t *CXXCtorInitializersOffsets; typedef llvm::DenseMap<const DeclContext *, DeclContextInfo> DeclContextInfosMap; /// \brief Information about the lexical and visible declarations /// for each DeclContext. DeclContextInfosMap DeclContextInfos; /// \brief Array of file-level DeclIDs sorted by file. const serialization::DeclID *FileSortedDecls; unsigned NumFileSortedDecls; /// \brief Array of redeclaration chain location information within this /// module file, sorted by the first declaration ID. const serialization::LocalRedeclarationsInfo *RedeclarationsMap; /// \brief The number of redeclaration info entries in RedeclarationsMap. unsigned LocalNumRedeclarationsInMap; /// \brief The redeclaration chains for declarations local to this /// module file. SmallVector<uint64_t, 1> RedeclarationChains; /// \brief Array of category list location information within this /// module file, sorted by the definition ID. const serialization::ObjCCategoriesInfo *ObjCCategoriesMap; /// \brief The number of redeclaration info entries in ObjCCategoriesMap. unsigned LocalNumObjCCategoriesInMap; /// \brief The Objective-C category lists for categories known to this /// module. SmallVector<uint64_t, 1> ObjCCategories; // === Types === /// \brief The number of types in this AST file. unsigned LocalNumTypes; /// \brief Offset of each type within the bitstream, indexed by the /// type ID, or the representation of a Type*. const uint32_t *TypeOffsets; /// \brief Base type ID for types local to this module as represented in /// the global type ID space. serialization::TypeID BaseTypeIndex; /// \brief Remapping table for type IDs in this module. ContinuousRangeMap<uint32_t, int, 2> TypeRemap; // === Miscellaneous === /// \brief Diagnostic IDs and their mappings that the user changed. SmallVector<uint64_t, 8> PragmaDiagMappings; /// \brief List of modules which depend on this module llvm::SetVector<ModuleFile *> ImportedBy; /// \brief List of modules which this module depends on llvm::SetVector<ModuleFile *> Imports; /// \brief Determine whether this module was directly imported at /// any point during translation. bool isDirectlyImported() const { return DirectlyImported; } /// \brief Dump debugging output for this module. void dump(); }; } // end namespace serialization } // end namespace clang #endif
0
repos/DirectXShaderCompiler/tools/clang/include/clang
repos/DirectXShaderCompiler/tools/clang/include/clang/Serialization/ModuleManager.h
//===--- ModuleManager.cpp - Module Manager ---------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines the ModuleManager class, which manages a set of loaded // modules for the ASTReader. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_SERIALIZATION_MODULEMANAGER_H #define LLVM_CLANG_SERIALIZATION_MODULEMANAGER_H #include "clang/Basic/FileManager.h" #include "clang/Serialization/Module.h" #include "llvm/ADT/DenseMap.h" #include "llvm/ADT/SmallPtrSet.h" namespace clang { class GlobalModuleIndex; class ModuleMap; class PCHContainerReader; namespace serialization { /// \brief Manages the set of modules loaded by an AST reader. class ModuleManager { /// \brief The chain of AST files. The first entry is the one named by the /// user, the last one is the one that doesn't depend on anything further. SmallVector<ModuleFile *, 2> Chain; // \brief The roots of the dependency DAG of AST files. This is used // to implement short-circuiting logic when running DFS over the dependencies. SmallVector<ModuleFile *, 2> Roots; /// \brief All loaded modules, indexed by name. llvm::DenseMap<const FileEntry *, ModuleFile *> Modules; typedef llvm::SetVector<const FileEntry *> AdditionalKnownModuleFileSet; /// \brief Additional module files that are known but not loaded. Tracked /// here so that we can re-export them if necessary. AdditionalKnownModuleFileSet AdditionalKnownModuleFiles; /// \brief FileManager that handles translating between filenames and /// FileEntry *. FileManager &FileMgr; /// \brief Knows how to unwrap module containers. const PCHContainerReader &PCHContainerRdr; /// \brief A lookup of in-memory (virtual file) buffers llvm::DenseMap<const FileEntry *, std::unique_ptr<llvm::MemoryBuffer>> InMemoryBuffers; /// \brief The visitation order. SmallVector<ModuleFile *, 4> VisitOrder; /// \brief The list of module files that both we and the global module index /// know about. /// /// Either the global index or the module manager may have modules that the /// other does not know about, because the global index can be out-of-date /// (in which case the module manager could have modules it does not) and /// this particular translation unit might not have loaded all of the modules /// known to the global index. SmallVector<ModuleFile *, 4> ModulesInCommonWithGlobalIndex; /// \brief The global module index, if one is attached. /// /// The global module index will actually be owned by the ASTReader; this is /// just an non-owning pointer. GlobalModuleIndex *GlobalIndex; /// \brief State used by the "visit" operation to avoid malloc traffic in /// calls to visit(). struct VisitState { explicit VisitState(unsigned N) : VisitNumber(N, 0), NextVisitNumber(1), NextState(nullptr) { Stack.reserve(N); } ~VisitState() { delete NextState; } /// \brief The stack used when marking the imports of a particular module /// as not-to-be-visited. SmallVector<ModuleFile *, 4> Stack; /// \brief The visit number of each module file, which indicates when /// this module file was last visited. SmallVector<unsigned, 4> VisitNumber; /// \brief The next visit number to use to mark visited module files. unsigned NextVisitNumber; /// \brief The next visit state. VisitState *NextState; }; /// \brief The first visit() state in the chain. VisitState *FirstVisitState; VisitState *allocateVisitState(); void returnVisitState(VisitState *State); public: typedef SmallVectorImpl<ModuleFile*>::iterator ModuleIterator; typedef SmallVectorImpl<ModuleFile*>::const_iterator ModuleConstIterator; typedef SmallVectorImpl<ModuleFile*>::reverse_iterator ModuleReverseIterator; typedef std::pair<uint32_t, StringRef> ModuleOffset; explicit ModuleManager(FileManager &FileMgr, const PCHContainerReader &PCHContainerRdr); ~ModuleManager(); /// \brief Forward iterator to traverse all loaded modules. This is reverse /// source-order. ModuleIterator begin() { return Chain.begin(); } /// \brief Forward iterator end-point to traverse all loaded modules ModuleIterator end() { return Chain.end(); } /// \brief Const forward iterator to traverse all loaded modules. This is /// in reverse source-order. ModuleConstIterator begin() const { return Chain.begin(); } /// \brief Const forward iterator end-point to traverse all loaded modules ModuleConstIterator end() const { return Chain.end(); } /// \brief Reverse iterator to traverse all loaded modules. This is in /// source order. ModuleReverseIterator rbegin() { return Chain.rbegin(); } /// \brief Reverse iterator end-point to traverse all loaded modules. ModuleReverseIterator rend() { return Chain.rend(); } /// \brief Returns the primary module associated with the manager, that is, /// the first module loaded ModuleFile &getPrimaryModule() { return *Chain[0]; } /// \brief Returns the primary module associated with the manager, that is, /// the first module loaded. ModuleFile &getPrimaryModule() const { return *Chain[0]; } /// \brief Returns the module associated with the given index ModuleFile &operator[](unsigned Index) const { return *Chain[Index]; } /// \brief Returns the module associated with the given name ModuleFile *lookup(StringRef Name); /// \brief Returns the module associated with the given module file. ModuleFile *lookup(const FileEntry *File); /// \brief Returns the in-memory (virtual file) buffer with the given name std::unique_ptr<llvm::MemoryBuffer> lookupBuffer(StringRef Name); /// \brief Number of modules loaded unsigned size() const { return Chain.size(); } /// \brief The result of attempting to add a new module. enum AddModuleResult { /// \brief The module file had already been loaded. AlreadyLoaded, /// \brief The module file was just loaded in response to this call. NewlyLoaded, /// \brief The module file is missing. Missing, /// \brief The module file is out-of-date. OutOfDate }; typedef ASTFileSignature(*ASTFileSignatureReader)(llvm::BitstreamReader &); /// \brief Attempts to create a new module and add it to the list of known /// modules. /// /// \param FileName The file name of the module to be loaded. /// /// \param Type The kind of module being loaded. /// /// \param ImportLoc The location at which the module is imported. /// /// \param ImportedBy The module that is importing this module, or NULL if /// this module is imported directly by the user. /// /// \param Generation The generation in which this module was loaded. /// /// \param ExpectedSize The expected size of the module file, used for /// validation. This will be zero if unknown. /// /// \param ExpectedModTime The expected modification time of the module /// file, used for validation. This will be zero if unknown. /// /// \param ExpectedSignature The expected signature of the module file, used /// for validation. This will be zero if unknown. /// /// \param ReadSignature Reads the signature from an AST file without actually /// loading it. /// /// \param Module A pointer to the module file if the module was successfully /// loaded. /// /// \param ErrorStr Will be set to a non-empty string if any errors occurred /// while trying to load the module. /// /// \return A pointer to the module that corresponds to this file name, /// and a value indicating whether the module was loaded. AddModuleResult addModule(StringRef FileName, ModuleKind Type, SourceLocation ImportLoc, ModuleFile *ImportedBy, unsigned Generation, off_t ExpectedSize, time_t ExpectedModTime, ASTFileSignature ExpectedSignature, ASTFileSignatureReader ReadSignature, ModuleFile *&Module, std::string &ErrorStr); /// \brief Remove the given set of modules. void removeModules(ModuleIterator first, ModuleIterator last, llvm::SmallPtrSetImpl<ModuleFile *> &LoadedSuccessfully, ModuleMap *modMap); /// \brief Add an in-memory buffer the list of known buffers void addInMemoryBuffer(StringRef FileName, std::unique_ptr<llvm::MemoryBuffer> Buffer); /// \brief Set the global module index. void setGlobalIndex(GlobalModuleIndex *Index); /// \brief Notification from the AST reader that the given module file /// has been "accepted", and will not (can not) be unloaded. void moduleFileAccepted(ModuleFile *MF); /// \brief Notification from the frontend that the given module file is /// part of this compilation (even if not imported) and, if this compilation /// is exported, should be made available to importers of it. bool addKnownModuleFile(StringRef FileName); /// \brief Get a list of additional module files that are not currently /// loaded but are considered to be part of the current compilation. llvm::iterator_range<AdditionalKnownModuleFileSet::const_iterator> getAdditionalKnownModuleFiles() { return llvm::make_range(AdditionalKnownModuleFiles.begin(), AdditionalKnownModuleFiles.end()); } /// \brief Visit each of the modules. /// /// This routine visits each of the modules, starting with the /// "root" modules that no other loaded modules depend on, and /// proceeding to the leaf modules, visiting each module only once /// during the traversal. /// /// This traversal is intended to support various "lookup" /// operations that can find data in any of the loaded modules. /// /// \param Visitor A visitor function that will be invoked with each /// module and the given user data pointer. The return value must be /// convertible to bool; when false, the visitation continues to /// modules that the current module depends on. When true, the /// visitation skips any modules that the current module depends on. /// /// \param UserData User data associated with the visitor object, which /// will be passed along to the visitor. /// /// \param ModuleFilesHit If non-NULL, contains the set of module files /// that we know we need to visit because the global module index told us to. /// Any module that is known to both the global module index and the module /// manager that is *not* in this set can be skipped. void visit(bool (*Visitor)(ModuleFile &M, void *UserData), void *UserData, llvm::SmallPtrSetImpl<ModuleFile *> *ModuleFilesHit = nullptr); /// \brief Control DFS behavior during preorder visitation. enum DFSPreorderControl { Continue, /// Continue visiting all nodes. Abort, /// Stop the visitation immediately. SkipImports, /// Do not visit imports of the current node. }; /// \brief Visit each of the modules with a depth-first traversal. /// /// This routine visits each of the modules known to the module /// manager using a depth-first search, starting with the first /// loaded module. The traversal invokes one callback before /// traversing the imports (preorder traversal) and one after /// traversing the imports (postorder traversal). /// /// \param PreorderVisitor A visitor function that will be invoked with each /// module before visiting its imports. The visitor can control how to /// continue the visitation through its return value. /// /// \param PostorderVisitor A visitor function taht will be invoked with each /// module after visiting its imports. The visitor may return true at any time /// to abort the depth-first visitation. /// /// \param UserData User data ssociated with the visitor object, /// which will be passed along to the user. void visitDepthFirst(DFSPreorderControl (*PreorderVisitor)(ModuleFile &M, void *UserData), bool (*PostorderVisitor)(ModuleFile &M, void *UserData), void *UserData); /// \brief Attempt to resolve the given module file name to a file entry. /// /// \param FileName The name of the module file. /// /// \param ExpectedSize The size that the module file is expected to have. /// If the actual size differs, the resolver should return \c true. /// /// \param ExpectedModTime The modification time that the module file is /// expected to have. If the actual modification time differs, the resolver /// should return \c true. /// /// \param File Will be set to the file if there is one, or null /// otherwise. /// /// \returns True if a file exists but does not meet the size/ /// modification time criteria, false if the file is either available and /// suitable, or is missing. bool lookupModuleFile(StringRef FileName, off_t ExpectedSize, time_t ExpectedModTime, const FileEntry *&File); /// \brief View the graphviz representation of the module graph. void viewGraph(); }; } } // end namespace clang::serialization #endif
0
repos/DirectXShaderCompiler/tools/clang/include/clang
repos/DirectXShaderCompiler/tools/clang/include/clang/Tooling/Refactoring.h
//===--- Refactoring.h - Framework for clang refactoring tools --*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // Interfaces supporting refactorings that span multiple translation units. // While single translation unit refactorings are supported via the Rewriter, // when refactoring multiple translation units changes must be stored in a // SourceManager independent form, duplicate changes need to be removed, and // all changes must be applied at once at the end of the refactoring so that // the code is always parseable. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_TOOLING_REFACTORING_H #define LLVM_CLANG_TOOLING_REFACTORING_H #include "clang/Tooling/Core/Replacement.h" #include "clang/Tooling/Tooling.h" #include <string> namespace clang { class Rewriter; namespace tooling { /// \brief A tool to run refactorings. /// /// This is a refactoring specific version of \see ClangTool. FrontendActions /// passed to run() and runAndSave() should add replacements to /// getReplacements(). class RefactoringTool : public ClangTool { public: /// \see ClangTool::ClangTool. RefactoringTool(const CompilationDatabase &Compilations, ArrayRef<std::string> SourcePaths, std::shared_ptr<PCHContainerOperations> PCHContainerOps = std::make_shared<PCHContainerOperations>()); /// \brief Returns the set of replacements to which replacements should /// be added during the run of the tool. Replacements &getReplacements(); /// \brief Call run(), apply all generated replacements, and immediately save /// the results to disk. /// /// \returns 0 upon success. Non-zero upon failure. int runAndSave(FrontendActionFactory *ActionFactory); /// \brief Apply all stored replacements to the given Rewriter. /// /// Replacement applications happen independently of the success of other /// applications. /// /// \returns true if all replacements apply. false otherwise. bool applyAllReplacements(Rewriter &Rewrite); private: /// \brief Write all refactored files to disk. int saveRewrittenFiles(Rewriter &Rewrite); private: Replacements Replace; }; } // end namespace tooling } // end namespace clang #endif // LLVM_CLANG_TOOLING_REFACTORING_H
0
repos/DirectXShaderCompiler/tools/clang/include/clang
repos/DirectXShaderCompiler/tools/clang/include/clang/Tooling/ArgumentsAdjusters.h
//===--- ArgumentsAdjusters.h - Command line arguments adjuster -*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file declares typedef ArgumentsAdjuster and functions to create several // useful argument adjusters. // ArgumentsAdjusters modify command line arguments obtained from a compilation // database before they are used to run a frontend action. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_TOOLING_ARGUMENTSADJUSTERS_H #define LLVM_CLANG_TOOLING_ARGUMENTSADJUSTERS_H #include <functional> #include <string> #include <vector> namespace clang { namespace tooling { /// \brief A sequence of command line arguments. typedef std::vector<std::string> CommandLineArguments; /// \brief A prototype of a command line adjuster. /// /// Command line argument adjuster is responsible for command line arguments /// modification before the arguments are used to run a frontend action. typedef std::function<CommandLineArguments(const CommandLineArguments &)> ArgumentsAdjuster; /// \brief Gets an argument adjuster that converts input command line arguments /// to the "syntax check only" variant. ArgumentsAdjuster getClangSyntaxOnlyAdjuster(); /// \brief Gets an argument adjuster which removes output-related command line /// arguments. ArgumentsAdjuster getClangStripOutputAdjuster(); enum class ArgumentInsertPosition { BEGIN, END }; /// \brief Gets an argument adjuster which inserts \p Extra arguments in the /// specified position. ArgumentsAdjuster getInsertArgumentAdjuster(const CommandLineArguments &Extra, ArgumentInsertPosition Pos); /// \brief Gets an argument adjuster which inserts an \p Extra argument in the /// specified position. ArgumentsAdjuster getInsertArgumentAdjuster( const char *Extra, ArgumentInsertPosition Pos = ArgumentInsertPosition::END); /// \brief Gets an argument adjuster which adjusts the arguments in sequence /// with the \p First adjuster and then with the \p Second one. ArgumentsAdjuster combineAdjusters(ArgumentsAdjuster First, ArgumentsAdjuster Second); } // namespace tooling } // namespace clang #endif // LLVM_CLANG_TOOLING_ARGUMENTSADJUSTERS_H
0
repos/DirectXShaderCompiler/tools/clang/include/clang
repos/DirectXShaderCompiler/tools/clang/include/clang/Tooling/ReplacementsYaml.h
//===-- ReplacementsYaml.h -- Serialiazation for Replacements ---*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// /// /// \file /// \brief This file defines the structure of a YAML document for serializing /// replacements. /// //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_TOOLING_REPLACEMENTSYAML_H #define LLVM_CLANG_TOOLING_REPLACEMENTSYAML_H #include "clang/Tooling/Refactoring.h" #include "llvm/Support/YAMLTraits.h" #include <string> #include <vector> LLVM_YAML_IS_SEQUENCE_VECTOR(clang::tooling::Replacement) namespace llvm { namespace yaml { /// \brief Specialized MappingTraits to describe how a Replacement is /// (de)serialized. template <> struct MappingTraits<clang::tooling::Replacement> { /// \brief Helper to (de)serialize a Replacement since we don't have direct /// access to its data members. struct NormalizedReplacement { NormalizedReplacement(const IO &) : FilePath(""), Offset(0), Length(0), ReplacementText("") {} NormalizedReplacement(const IO &, const clang::tooling::Replacement &R) : FilePath(R.getFilePath()), Offset(R.getOffset()), Length(R.getLength()), ReplacementText(R.getReplacementText()) {} clang::tooling::Replacement denormalize(const IO &) { return clang::tooling::Replacement(FilePath, Offset, Length, ReplacementText); } std::string FilePath; unsigned int Offset; unsigned int Length; std::string ReplacementText; }; static void mapping(IO &Io, clang::tooling::Replacement &R) { MappingNormalization<NormalizedReplacement, clang::tooling::Replacement> Keys(Io, R); Io.mapRequired("FilePath", Keys->FilePath); Io.mapRequired("Offset", Keys->Offset); Io.mapRequired("Length", Keys->Length); Io.mapRequired("ReplacementText", Keys->ReplacementText); } }; /// \brief Specialized MappingTraits to describe how a /// TranslationUnitReplacements is (de)serialized. template <> struct MappingTraits<clang::tooling::TranslationUnitReplacements> { static void mapping(IO &Io, clang::tooling::TranslationUnitReplacements &Doc) { Io.mapRequired("MainSourceFile", Doc.MainSourceFile); Io.mapOptional("Context", Doc.Context, std::string()); Io.mapRequired("Replacements", Doc.Replacements); } }; } // end namespace yaml } // end namespace llvm #endif
0
repos/DirectXShaderCompiler/tools/clang/include/clang
repos/DirectXShaderCompiler/tools/clang/include/clang/Tooling/RefactoringCallbacks.h
//===--- RefactoringCallbacks.h - Structural query framework ----*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // Provides callbacks to make common kinds of refactorings easy. // // The general idea is to construct a matcher expression that describes a // subtree match on the AST and then replace the corresponding source code // either by some specific text or some other AST node. // // Example: // int main(int argc, char **argv) { // ClangTool Tool(argc, argv); // MatchFinder Finder; // ReplaceStmtWithText Callback("integer", "42"); // Finder.AddMatcher(id("integer", expression(integerLiteral())), Callback); // return Tool.run(newFrontendActionFactory(&Finder)); // } // // This will replace all integer literals with "42". // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_TOOLING_REFACTORINGCALLBACKS_H #define LLVM_CLANG_TOOLING_REFACTORINGCALLBACKS_H #include "clang/ASTMatchers/ASTMatchFinder.h" #include "clang/Tooling/Refactoring.h" namespace clang { namespace tooling { /// \brief Base class for RefactoringCallbacks. /// /// Collects \c tooling::Replacements while running. class RefactoringCallback : public ast_matchers::MatchFinder::MatchCallback { public: RefactoringCallback(); Replacements &getReplacements(); protected: Replacements Replace; }; /// \brief Replace the text of the statement bound to \c FromId with the text in /// \c ToText. class ReplaceStmtWithText : public RefactoringCallback { public: ReplaceStmtWithText(StringRef FromId, StringRef ToText); void run(const ast_matchers::MatchFinder::MatchResult &Result) override; private: std::string FromId; std::string ToText; }; /// \brief Replace the text of the statement bound to \c FromId with the text of /// the statement bound to \c ToId. class ReplaceStmtWithStmt : public RefactoringCallback { public: ReplaceStmtWithStmt(StringRef FromId, StringRef ToId); void run(const ast_matchers::MatchFinder::MatchResult &Result) override; private: std::string FromId; std::string ToId; }; /// \brief Replace an if-statement bound to \c Id with the outdented text of its /// body, choosing the consequent or the alternative based on whether /// \c PickTrueBranch is true. class ReplaceIfStmtWithItsBody : public RefactoringCallback { public: ReplaceIfStmtWithItsBody(StringRef Id, bool PickTrueBranch); void run(const ast_matchers::MatchFinder::MatchResult &Result) override; private: std::string Id; const bool PickTrueBranch; }; } // end namespace tooling } // end namespace clang #endif
0
repos/DirectXShaderCompiler/tools/clang/include/clang
repos/DirectXShaderCompiler/tools/clang/include/clang/Tooling/CompilationDatabasePluginRegistry.h
//===--- CompilationDatabasePluginRegistry.h - ------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_TOOLING_COMPILATIONDATABASEPLUGINREGISTRY_H #define LLVM_CLANG_TOOLING_COMPILATIONDATABASEPLUGINREGISTRY_H #include "clang/Tooling/CompilationDatabase.h" #include "llvm/Support/Registry.h" namespace clang { namespace tooling { class CompilationDatabasePlugin; typedef llvm::Registry<CompilationDatabasePlugin> CompilationDatabasePluginRegistry; } // end namespace tooling } // end namespace clang #endif
0
repos/DirectXShaderCompiler/tools/clang/include/clang
repos/DirectXShaderCompiler/tools/clang/include/clang/Tooling/CompilationDatabase.h
//===--- CompilationDatabase.h - --------------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file provides an interface and multiple implementations for // CompilationDatabases. // // While C++ refactoring and analysis tools are not compilers, and thus // don't run as part of the build system, they need the exact information // of a build in order to be able to correctly understand the C++ code of // the project. This information is provided via the CompilationDatabase // interface. // // To create a CompilationDatabase from a build directory one can call // CompilationDatabase::loadFromDirectory(), which deduces the correct // compilation database from the root of the build tree. // // See the concrete subclasses of CompilationDatabase for currently supported // formats. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_TOOLING_COMPILATIONDATABASE_H #define LLVM_CLANG_TOOLING_COMPILATIONDATABASE_H #include "clang/Basic/LLVM.h" #include "llvm/ADT/ArrayRef.h" #include "llvm/ADT/StringRef.h" #include "llvm/ADT/Twine.h" #include <memory> #include <string> #include <vector> namespace clang { namespace tooling { /// \brief Specifies the working directory and command of a compilation. struct CompileCommand { CompileCommand() {} CompileCommand(Twine Directory, std::vector<std::string> CommandLine) : Directory(Directory.str()), CommandLine(std::move(CommandLine)) {} /// \brief The working directory the command was executed from. std::string Directory; /// \brief The command line that was executed. std::vector<std::string> CommandLine; /// \brief An optional mapping from each file's path to its content for all /// files needed for the compilation that are not available via the file /// system. /// /// Note that a tool implementation is required to fall back to the file /// system if a source file is not provided in the mapped sources, as /// compilation databases will usually not provide all files in mapped sources /// for performance reasons. std::vector<std::pair<std::string, std::string> > MappedSources; }; /// \brief Interface for compilation databases. /// /// A compilation database allows the user to retrieve all compile command lines /// that a specified file is compiled with in a project. /// The retrieved compile command lines can be used to run clang tools over /// a subset of the files in a project. class CompilationDatabase { public: virtual ~CompilationDatabase(); /// \brief Loads a compilation database from a build directory. /// /// Looks at the specified 'BuildDirectory' and creates a compilation database /// that allows to query compile commands for source files in the /// corresponding source tree. /// /// Returns NULL and sets ErrorMessage if we were not able to build up a /// compilation database for the build directory. /// /// FIXME: Currently only supports JSON compilation databases, which /// are named 'compile_commands.json' in the given directory. Extend this /// for other build types (like ninja build files). static std::unique_ptr<CompilationDatabase> loadFromDirectory(StringRef BuildDirectory, std::string &ErrorMessage); /// \brief Tries to detect a compilation database location and load it. /// /// Looks for a compilation database in all parent paths of file 'SourceFile' /// by calling loadFromDirectory. static std::unique_ptr<CompilationDatabase> autoDetectFromSource(StringRef SourceFile, std::string &ErrorMessage); /// \brief Tries to detect a compilation database location and load it. /// /// Looks for a compilation database in directory 'SourceDir' and all /// its parent paths by calling loadFromDirectory. static std::unique_ptr<CompilationDatabase> autoDetectFromDirectory(StringRef SourceDir, std::string &ErrorMessage); /// \brief Returns all compile commands in which the specified file was /// compiled. /// /// This includes compile comamnds that span multiple source files. /// For example, consider a project with the following compilations: /// $ clang++ -o test a.cc b.cc t.cc /// $ clang++ -o production a.cc b.cc -DPRODUCTION /// A compilation database representing the project would return both command /// lines for a.cc and b.cc and only the first command line for t.cc. virtual std::vector<CompileCommand> getCompileCommands( StringRef FilePath) const = 0; /// \brief Returns the list of all files available in the compilation database. virtual std::vector<std::string> getAllFiles() const = 0; /// \brief Returns all compile commands for all the files in the compilation /// database. /// /// FIXME: Add a layer in Tooling that provides an interface to run a tool /// over all files in a compilation database. Not all build systems have the /// ability to provide a feasible implementation for \c getAllCompileCommands. virtual std::vector<CompileCommand> getAllCompileCommands() const = 0; }; /// \brief Interface for compilation database plugins. /// /// A compilation database plugin allows the user to register custom compilation /// databases that are picked up as compilation database if the corresponding /// library is linked in. To register a plugin, declare a static variable like: /// /// \code /// static CompilationDatabasePluginRegistry::Add<MyDatabasePlugin> /// X("my-compilation-database", "Reads my own compilation database"); /// \endcode class CompilationDatabasePlugin { public: virtual ~CompilationDatabasePlugin(); /// \brief Loads a compilation database from a build directory. /// /// \see CompilationDatabase::loadFromDirectory(). virtual std::unique_ptr<CompilationDatabase> loadFromDirectory(StringRef Directory, std::string &ErrorMessage) = 0; }; /// \brief A compilation database that returns a single compile command line. /// /// Useful when we want a tool to behave more like a compiler invocation. class FixedCompilationDatabase : public CompilationDatabase { public: /// \brief Creates a FixedCompilationDatabase from the arguments after "--". /// /// Parses the given command line for "--". If "--" is found, the rest of /// the arguments will make up the command line in the returned /// FixedCompilationDatabase. /// The arguments after "--" must not include positional parameters or the /// argv[0] of the tool. Those will be added by the FixedCompilationDatabase /// when a CompileCommand is requested. The argv[0] of the returned command /// line will be "clang-tool". /// /// Returns NULL in case "--" is not found. /// /// The argument list is meant to be compatible with normal llvm command line /// parsing in main methods. /// int main(int argc, char **argv) { /// std::unique_ptr<FixedCompilationDatabase> Compilations( /// FixedCompilationDatabase::loadFromCommandLine(argc, argv)); /// cl::ParseCommandLineOptions(argc, argv); /// ... /// } /// /// \param Argc The number of command line arguments - will be changed to /// the number of arguments before "--", if "--" was found in the argument /// list. /// \param Argv Points to the command line arguments. /// \param Directory The base directory used in the FixedCompilationDatabase. static FixedCompilationDatabase *loadFromCommandLine(int &Argc, const char *const *Argv, Twine Directory = "."); /// \brief Constructs a compilation data base from a specified directory /// and command line. FixedCompilationDatabase(Twine Directory, ArrayRef<std::string> CommandLine); /// \brief Returns the given compile command. /// /// Will always return a vector with one entry that contains the directory /// and command line specified at construction with "clang-tool" as argv[0] /// and 'FilePath' as positional argument. std::vector<CompileCommand> getCompileCommands(StringRef FilePath) const override; /// \brief Returns the list of all files available in the compilation database. /// /// Note: This is always an empty list for the fixed compilation database. std::vector<std::string> getAllFiles() const override; /// \brief Returns all compile commands for all the files in the compilation /// database. /// /// Note: This is always an empty list for the fixed compilation database. std::vector<CompileCommand> getAllCompileCommands() const override; private: /// This is built up to contain a single entry vector to be returned from /// getCompileCommands after adding the positional argument. std::vector<CompileCommand> CompileCommands; }; } // end namespace tooling } // end namespace clang #endif
0
repos/DirectXShaderCompiler/tools/clang/include/clang
repos/DirectXShaderCompiler/tools/clang/include/clang/Tooling/CommonOptionsParser.h
//===- CommonOptionsParser.h - common options for clang tools -*- C++ -*-=====// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the CommonOptionsParser class used to parse common // command-line options for clang tools, so that they can be run as separate // command-line applications with a consistent common interface for handling // compilation database and input files. // // It provides a common subset of command-line options, common algorithm // for locating a compilation database and source files, and help messages // for the basic command-line interface. // // It creates a CompilationDatabase and reads common command-line options. // // This class uses the Clang Tooling infrastructure, see // http://clang.llvm.org/docs/HowToSetupToolingForLLVM.html // for details on setting it up with LLVM source tree. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_TOOLING_COMMONOPTIONSPARSER_H #define LLVM_CLANG_TOOLING_COMMONOPTIONSPARSER_H #include "clang/Tooling/CompilationDatabase.h" #include "llvm/Support/CommandLine.h" namespace clang { namespace tooling { /// \brief A parser for options common to all command-line Clang tools. /// /// Parses a common subset of command-line arguments, locates and loads a /// compilation commands database and runs a tool with user-specified action. It /// also contains a help message for the common command-line options. /// /// An example of usage: /// \code /// #include "clang/Frontend/FrontendActions.h" /// #include "clang/Tooling/CommonOptionsParser.h" /// #include "llvm/Support/CommandLine.h" /// /// using namespace clang::tooling; /// using namespace llvm; /// /// static cl::OptionCategory MyToolCategory("My tool options"); /// static cl::extrahelp CommonHelp(CommonOptionsParser::HelpMessage); /// static cl::extrahelp MoreHelp("\nMore help text..."); /// static cl::opt<bool> YourOwnOption(...); /// ... /// /// int main(int argc, const char **argv) { /// CommonOptionsParser OptionsParser(argc, argv, MyToolCategory); /// ClangTool Tool(OptionsParser.getCompilations(), /// OptionsParser.getSourcePathListi()); /// return Tool.run(newFrontendActionFactory<clang::SyntaxOnlyAction>()); /// } /// \endcode class CommonOptionsParser { public: /// \brief Parses command-line, initializes a compilation database. /// /// This constructor can change argc and argv contents, e.g. consume /// command-line options used for creating FixedCompilationDatabase. /// /// All options not belonging to \p Category become hidden. /// /// This constructor exits program in case of error. CommonOptionsParser(int &argc, const char **argv, llvm::cl::OptionCategory &Category, const char *Overview = nullptr); /// Returns a reference to the loaded compilations database. CompilationDatabase &getCompilations() { return *Compilations; } /// Returns a list of source file paths to process. std::vector<std::string> getSourcePathList() { return SourcePathList; } static const char *const HelpMessage; private: std::unique_ptr<CompilationDatabase> Compilations; std::vector<std::string> SourcePathList; std::vector<std::string> ExtraArgsBefore; std::vector<std::string> ExtraArgsAfter; }; } // namespace tooling } // namespace clang #endif // LLVM_TOOLS_CLANG_INCLUDE_CLANG_TOOLING_COMMONOPTIONSPARSER_H
0
repos/DirectXShaderCompiler/tools/clang/include/clang
repos/DirectXShaderCompiler/tools/clang/include/clang/Tooling/Tooling.h
//===--- Tooling.h - Framework for standalone Clang tools -------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements functions to run clang tools standalone instead // of running them as a plugin. // // A ClangTool is initialized with a CompilationDatabase and a set of files // to run over. The tool will then run a user-specified FrontendAction over // all TUs in which the given files are compiled. // // It is also possible to run a FrontendAction over a snippet of code by // calling runToolOnCode, which is useful for unit testing. // // Applications that need more fine grained control over how to run // multiple FrontendActions over code can use ToolInvocation. // // Example tools: // - running clang -fsyntax-only over source code from an editor to get // fast syntax checks // - running match/replace tools over C++ code // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_TOOLING_TOOLING_H #define LLVM_CLANG_TOOLING_TOOLING_H #include "clang/AST/ASTConsumer.h" #include "clang/Frontend/PCHContainerOperations.h" #include "clang/Basic/Diagnostic.h" #include "clang/Basic/FileManager.h" #include "clang/Basic/LLVM.h" #include "clang/Driver/Util.h" #include "clang/Frontend/FrontendAction.h" #include "clang/Lex/ModuleLoader.h" #include "clang/Tooling/ArgumentsAdjusters.h" #include "clang/Tooling/CompilationDatabase.h" #include "llvm/ADT/StringMap.h" #include "llvm/ADT/Twine.h" #include "llvm/Option/Option.h" #include <memory> #include <string> #include <vector> namespace clang { namespace driver { class Compilation; } // end namespace driver class CompilerInvocation; class SourceManager; class FrontendAction; namespace tooling { /// \brief Interface to process a clang::CompilerInvocation. /// /// If your tool is based on FrontendAction, you should be deriving from /// FrontendActionFactory instead. class ToolAction { public: virtual ~ToolAction(); /// \brief Perform an action for an invocation. virtual bool runInvocation(clang::CompilerInvocation *Invocation, FileManager *Files, std::shared_ptr<PCHContainerOperations> PCHContainerOps, DiagnosticConsumer *DiagConsumer) = 0; }; /// \brief Interface to generate clang::FrontendActions. /// /// Having a factory interface allows, for example, a new FrontendAction to be /// created for each translation unit processed by ClangTool. This class is /// also a ToolAction which uses the FrontendActions created by create() to /// process each translation unit. class FrontendActionFactory : public ToolAction { public: ~FrontendActionFactory() override; /// \brief Invokes the compiler with a FrontendAction created by create(). bool runInvocation(clang::CompilerInvocation *Invocation, FileManager *Files, std::shared_ptr<PCHContainerOperations> PCHContainerOps, DiagnosticConsumer *DiagConsumer) override; /// \brief Returns a new clang::FrontendAction. /// /// The caller takes ownership of the returned action. virtual clang::FrontendAction *create() = 0; }; /// \brief Returns a new FrontendActionFactory for a given type. /// /// T must derive from clang::FrontendAction. /// /// Example: /// FrontendActionFactory *Factory = /// newFrontendActionFactory<clang::SyntaxOnlyAction>(); template <typename T> std::unique_ptr<FrontendActionFactory> newFrontendActionFactory(); /// \brief Callbacks called before and after each source file processed by a /// FrontendAction created by the FrontedActionFactory returned by \c /// newFrontendActionFactory. class SourceFileCallbacks { public: virtual ~SourceFileCallbacks() {} /// \brief Called before a source file is processed by a FrontEndAction. /// \see clang::FrontendAction::BeginSourceFileAction virtual bool handleBeginSource(CompilerInstance &CI, StringRef Filename) { return true; } /// \brief Called after a source file is processed by a FrontendAction. /// \see clang::FrontendAction::EndSourceFileAction virtual void handleEndSource() {} }; /// \brief Returns a new FrontendActionFactory for any type that provides an /// implementation of newASTConsumer(). /// /// FactoryT must implement: ASTConsumer *newASTConsumer(). /// /// Example: /// struct ProvidesASTConsumers { /// clang::ASTConsumer *newASTConsumer(); /// } Factory; /// std::unique_ptr<FrontendActionFactory> FactoryAdapter( /// newFrontendActionFactory(&Factory)); template <typename FactoryT> inline std::unique_ptr<FrontendActionFactory> newFrontendActionFactory( FactoryT *ConsumerFactory, SourceFileCallbacks *Callbacks = nullptr); /// \brief Runs (and deletes) the tool on 'Code' with the -fsyntax-only flag. /// /// \param ToolAction The action to run over the code. /// \param Code C++ code. /// \param FileName The file name which 'Code' will be mapped as. /// \param PCHContainerOps The PCHContainerOperations for loading and creating /// clang modules. /// /// \return - True if 'ToolAction' was successfully executed. bool runToolOnCode(clang::FrontendAction *ToolAction, const Twine &Code, const Twine &FileName = "input.cc", std::shared_ptr<PCHContainerOperations> PCHContainerOps = std::make_shared<PCHContainerOperations>()); /// The first part of the pair is the filename, the second part the /// file-content. typedef std::vector<std::pair<std::string, std::string>> FileContentMappings; /// \brief Runs (and deletes) the tool on 'Code' with the -fsyntax-only flag and /// with additional other flags. /// /// \param ToolAction The action to run over the code. /// \param Code C++ code. /// \param Args Additional flags to pass on. /// \param FileName The file name which 'Code' will be mapped as. /// \param PCHContainerOps The PCHContainerOperations for loading and creating /// clang modules. /// /// \return - True if 'ToolAction' was successfully executed. bool runToolOnCodeWithArgs( clang::FrontendAction *ToolAction, const Twine &Code, const std::vector<std::string> &Args, const Twine &FileName = "input.cc", std::shared_ptr<PCHContainerOperations> PCHContainerOps = std::make_shared<PCHContainerOperations>(), const FileContentMappings &VirtualMappedFiles = FileContentMappings()); /// \brief Builds an AST for 'Code'. /// /// \param Code C++ code. /// \param FileName The file name which 'Code' will be mapped as. /// \param PCHContainerOps The PCHContainerOperations for loading and creating /// clang modules. /// /// \return The resulting AST or null if an error occurred. std::unique_ptr<ASTUnit> buildASTFromCode(const Twine &Code, const Twine &FileName = "input.cc", std::shared_ptr<PCHContainerOperations> PCHContainerOps = std::make_shared<PCHContainerOperations>()); /// \brief Builds an AST for 'Code' with additional flags. /// /// \param Code C++ code. /// \param Args Additional flags to pass on. /// \param FileName The file name which 'Code' will be mapped as. /// \param PCHContainerOps The PCHContainerOperations for loading and creating /// clang modules. /// /// \return The resulting AST or null if an error occurred. std::unique_ptr<ASTUnit> buildASTFromCodeWithArgs( const Twine &Code, const std::vector<std::string> &Args, const Twine &FileName = "input.cc", std::shared_ptr<PCHContainerOperations> PCHContainerOps = std::make_shared<PCHContainerOperations>()); /// \brief Utility to run a FrontendAction in a single clang invocation. class ToolInvocation { public: /// \brief Create a tool invocation. /// /// \param CommandLine The command line arguments to clang. Note that clang /// uses its binary name (CommandLine[0]) to locate its builtin headers. /// Callers have to ensure that they are installed in a compatible location /// (see clang driver implementation) or mapped in via mapVirtualFile. /// \param FAction The action to be executed. Class takes ownership. /// \param Files The FileManager used for the execution. Class does not take /// ownership. /// \param PCHContainerOps The PCHContainerOperations for loading and creating /// clang modules. ToolInvocation(std::vector<std::string> CommandLine, FrontendAction *FAction, FileManager *Files, std::shared_ptr<PCHContainerOperations> PCHContainerOps = std::make_shared<PCHContainerOperations>()); /// \brief Create a tool invocation. /// /// \param CommandLine The command line arguments to clang. /// \param Action The action to be executed. /// \param Files The FileManager used for the execution. /// \param PCHContainerOps The PCHContainerOperations for loading and creating /// clang modules. ToolInvocation(std::vector<std::string> CommandLine, ToolAction *Action, FileManager *Files, std::shared_ptr<PCHContainerOperations> PCHContainerOps); ~ToolInvocation(); /// \brief Set a \c DiagnosticConsumer to use during parsing. void setDiagnosticConsumer(DiagnosticConsumer *DiagConsumer) { this->DiagConsumer = DiagConsumer; } /// \brief Map a virtual file to be used while running the tool. /// /// \param FilePath The path at which the content will be mapped. /// \param Content A null terminated buffer of the file's content. void mapVirtualFile(StringRef FilePath, StringRef Content); /// \brief Run the clang invocation. /// /// \returns True if there were no errors during execution. bool run(); private: void addFileMappingsTo(SourceManager &SourceManager); bool runInvocation(const char *BinaryName, clang::driver::Compilation *Compilation, clang::CompilerInvocation *Invocation, std::shared_ptr<PCHContainerOperations> PCHContainerOps); std::vector<std::string> CommandLine; ToolAction *Action; bool OwnsAction; FileManager *Files; std::shared_ptr<PCHContainerOperations> PCHContainerOps; // Maps <file name> -> <file content>. llvm::StringMap<StringRef> MappedFileContents; DiagnosticConsumer *DiagConsumer; }; /// \brief Utility to run a FrontendAction over a set of files. /// /// This class is written to be usable for command line utilities. /// By default the class uses ClangSyntaxOnlyAdjuster to modify /// command line arguments before the arguments are used to run /// a frontend action. One could install an additional command line /// arguments adjuster by calling the appendArgumentsAdjuster() method. class ClangTool { public: /// \brief Constructs a clang tool to run over a list of files. /// /// \param Compilations The CompilationDatabase which contains the compile /// command lines for the given source paths. /// \param SourcePaths The source files to run over. If a source files is /// not found in Compilations, it is skipped. /// \param PCHContainerOps The PCHContainerOperations for loading and creating /// clang modules. ClangTool(const CompilationDatabase &Compilations, ArrayRef<std::string> SourcePaths, std::shared_ptr<PCHContainerOperations> PCHContainerOps = std::make_shared<PCHContainerOperations>()); ~ClangTool(); /// \brief Set a \c DiagnosticConsumer to use during parsing. void setDiagnosticConsumer(DiagnosticConsumer *DiagConsumer) { this->DiagConsumer = DiagConsumer; } /// \brief Map a virtual file to be used while running the tool. /// /// \param FilePath The path at which the content will be mapped. /// \param Content A null terminated buffer of the file's content. void mapVirtualFile(StringRef FilePath, StringRef Content); /// \brief Append a command line arguments adjuster to the adjuster chain. /// /// \param Adjuster An argument adjuster, which will be run on the output of /// previous argument adjusters. void appendArgumentsAdjuster(ArgumentsAdjuster Adjuster); /// \brief Clear the command line arguments adjuster chain. void clearArgumentsAdjusters(); /// Runs an action over all files specified in the command line. /// /// \param Action Tool action. int run(ToolAction *Action); /// \brief Create an AST for each file specified in the command line and /// append them to ASTs. int buildASTs(std::vector<std::unique_ptr<ASTUnit>> &ASTs); /// \brief Returns the file manager used in the tool. /// /// The file manager is shared between all translation units. FileManager &getFiles() { return *Files; } private: const CompilationDatabase &Compilations; std::vector<std::string> SourcePaths; std::shared_ptr<PCHContainerOperations> PCHContainerOps; llvm::IntrusiveRefCntPtr<FileManager> Files; // Contains a list of pairs (<file name>, <file content>). std::vector< std::pair<StringRef, StringRef> > MappedFileContents; ArgumentsAdjuster ArgsAdjuster; DiagnosticConsumer *DiagConsumer; }; template <typename T> std::unique_ptr<FrontendActionFactory> newFrontendActionFactory() { class SimpleFrontendActionFactory : public FrontendActionFactory { public: clang::FrontendAction *create() override { return new T; } }; return std::unique_ptr<FrontendActionFactory>( new SimpleFrontendActionFactory); } template <typename FactoryT> inline std::unique_ptr<FrontendActionFactory> newFrontendActionFactory( FactoryT *ConsumerFactory, SourceFileCallbacks *Callbacks) { class FrontendActionFactoryAdapter : public FrontendActionFactory { public: explicit FrontendActionFactoryAdapter(FactoryT *ConsumerFactory, SourceFileCallbacks *Callbacks) : ConsumerFactory(ConsumerFactory), Callbacks(Callbacks) {} clang::FrontendAction *create() override { return new ConsumerFactoryAdaptor(ConsumerFactory, Callbacks); } private: class ConsumerFactoryAdaptor : public clang::ASTFrontendAction { public: ConsumerFactoryAdaptor(FactoryT *ConsumerFactory, SourceFileCallbacks *Callbacks) : ConsumerFactory(ConsumerFactory), Callbacks(Callbacks) {} std::unique_ptr<clang::ASTConsumer> CreateASTConsumer(clang::CompilerInstance &, StringRef) override { return ConsumerFactory->newASTConsumer(); } protected: bool BeginSourceFileAction(CompilerInstance &CI, StringRef Filename) override { if (!clang::ASTFrontendAction::BeginSourceFileAction(CI, Filename)) return false; if (Callbacks) return Callbacks->handleBeginSource(CI, Filename); return true; } void EndSourceFileAction() override { if (Callbacks) Callbacks->handleEndSource(); clang::ASTFrontendAction::EndSourceFileAction(); } private: FactoryT *ConsumerFactory; SourceFileCallbacks *Callbacks; }; FactoryT *ConsumerFactory; SourceFileCallbacks *Callbacks; }; return std::unique_ptr<FrontendActionFactory>( new FrontendActionFactoryAdapter(ConsumerFactory, Callbacks)); } /// \brief Returns the absolute path of \c File, by prepending it with /// the current directory if \c File is not absolute. /// /// Otherwise returns \c File. /// If 'File' starts with "./", the returned path will not contain the "./". /// Otherwise, the returned path will contain the literal path-concatenation of /// the current directory and \c File. /// /// The difference to llvm::sys::fs::make_absolute is the canonicalization this /// does by removing "./" and computing native paths. /// /// \param File Either an absolute or relative path. std::string getAbsolutePath(StringRef File); /// \brief Creates a \c CompilerInvocation. clang::CompilerInvocation *newInvocation( clang::DiagnosticsEngine *Diagnostics, const llvm::opt::ArgStringList &CC1Args); } // end namespace tooling } // end namespace clang #endif // LLVM_CLANG_TOOLING_TOOLING_H
0
repos/DirectXShaderCompiler/tools/clang/include/clang
repos/DirectXShaderCompiler/tools/clang/include/clang/Tooling/JSONCompilationDatabase.h
//===--- JSONCompilationDatabase.h - ----------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // The JSONCompilationDatabase finds compilation databases supplied as a file // 'compile_commands.json'. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_TOOLING_JSONCOMPILATIONDATABASE_H #define LLVM_CLANG_TOOLING_JSONCOMPILATIONDATABASE_H #include "clang/Basic/LLVM.h" #include "clang/Tooling/CompilationDatabase.h" #include "clang/Tooling/FileMatchTrie.h" #include "llvm/ADT/StringMap.h" #include "llvm/ADT/StringRef.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/SourceMgr.h" #include "llvm/Support/YAMLParser.h" #include <memory> #include <string> #include <vector> namespace clang { namespace tooling { /// \brief A JSON based compilation database. /// /// JSON compilation database files must contain a list of JSON objects which /// provide the command lines in the attributes 'directory', 'command' and /// 'file': /// [ /// { "directory": "<working directory of the compile>", /// "command": "<compile command line>", /// "file": "<path to source file>" /// }, /// ... /// ] /// Each object entry defines one compile action. The specified file is /// considered to be the main source file for the translation unit. /// /// JSON compilation databases can for example be generated in CMake projects /// by setting the flag -DCMAKE_EXPORT_COMPILE_COMMANDS. class JSONCompilationDatabase : public CompilationDatabase { public: /// \brief Loads a JSON compilation database from the specified file. /// /// Returns NULL and sets ErrorMessage if the database could not be /// loaded from the given file. static std::unique_ptr<JSONCompilationDatabase> loadFromFile(StringRef FilePath, std::string &ErrorMessage); /// \brief Loads a JSON compilation database from a data buffer. /// /// Returns NULL and sets ErrorMessage if the database could not be loaded. static std::unique_ptr<JSONCompilationDatabase> loadFromBuffer(StringRef DatabaseString, std::string &ErrorMessage); /// \brief Returns all compile comamnds in which the specified file was /// compiled. /// /// FIXME: Currently FilePath must be an absolute path inside the /// source directory which does not have symlinks resolved. std::vector<CompileCommand> getCompileCommands(StringRef FilePath) const override; /// \brief Returns the list of all files available in the compilation database. /// /// These are the 'file' entries of the JSON objects. std::vector<std::string> getAllFiles() const override; /// \brief Returns all compile commands for all the files in the compilation /// database. std::vector<CompileCommand> getAllCompileCommands() const override; private: /// \brief Constructs a JSON compilation database on a memory buffer. JSONCompilationDatabase(std::unique_ptr<llvm::MemoryBuffer> Database) : Database(std::move(Database)), YAMLStream(this->Database->getBuffer(), SM) {} /// \brief Parses the database file and creates the index. /// /// Returns whether parsing succeeded. Sets ErrorMessage if parsing /// failed. bool parse(std::string &ErrorMessage); // Tuple (directory, commandline) where 'commandline' pointing to the // corresponding nodes in the YAML stream. typedef std::pair<llvm::yaml::ScalarNode*, llvm::yaml::ScalarNode*> CompileCommandRef; /// \brief Converts the given array of CompileCommandRefs to CompileCommands. void getCommands(ArrayRef<CompileCommandRef> CommandsRef, std::vector<CompileCommand> &Commands) const; // Maps file paths to the compile command lines for that file. llvm::StringMap< std::vector<CompileCommandRef> > IndexByFile; FileMatchTrie MatchTrie; std::unique_ptr<llvm::MemoryBuffer> Database; llvm::SourceMgr SM; llvm::yaml::Stream YAMLStream; }; } // end namespace tooling } // end namespace clang #endif
0
repos/DirectXShaderCompiler/tools/clang/include/clang
repos/DirectXShaderCompiler/tools/clang/include/clang/Tooling/FileMatchTrie.h
//===--- FileMatchTrie.h - --------------------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements a match trie to find the matching file in a compilation // database based on a given path in the presence of symlinks. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_TOOLING_FILEMATCHTRIE_H #define LLVM_CLANG_TOOLING_FILEMATCHTRIE_H #include "clang/Basic/LLVM.h" #include "llvm/ADT/StringRef.h" #include <memory> #include <string> #include <vector> namespace clang { namespace tooling { struct PathComparator { virtual ~PathComparator() {} virtual bool equivalent(StringRef FileA, StringRef FileB) const = 0; }; class FileMatchTrieNode; /// \brief A trie to efficiently match against the entries of the compilation /// database in order of matching suffix length. /// /// When a clang tool is supposed to operate on a specific file, we have to /// find the corresponding file in the compilation database. Although entries /// in the compilation database are keyed by filename, a simple string match /// is insufficient because of symlinks. Commonly, a project hierarchy looks /// like this: /// /<project-root>/src/<path>/<somefile>.cc (used as input for the tool) /// /<project-root>/build/<symlink-to-src>/<path>/<somefile>.cc (stored in DB) /// /// Furthermore, there might be symlinks inside the source folder or inside the /// database, so that the same source file is translated with different build /// options. /// /// For a given input file, the \c FileMatchTrie finds its entries in order /// of matching suffix length. For each suffix length, there might be one or /// more entries in the database. For each of those entries, it calls /// \c llvm::sys::fs::equivalent() (injected as \c PathComparator). There might /// be zero or more entries with the same matching suffix length that are /// equivalent to the input file. Three cases are distinguished: /// 0 equivalent files: Continue with the next suffix length. /// 1 equivalent file: Best match found, return it. /// >1 equivalent files: Match is ambiguous, return error. class FileMatchTrie { public: FileMatchTrie(); /// \brief Construct a new \c FileMatchTrie with the given \c PathComparator. /// /// The \c FileMatchTrie takes ownership of 'Comparator'. Used for testing. FileMatchTrie(PathComparator* Comparator); ~FileMatchTrie(); /// \brief Insert a new absolute path. Relative paths are ignored. void insert(StringRef NewPath); /// \brief Finds the corresponding file in this trie. /// /// Returns file name stored in this trie that is equivalent to 'FileName' /// according to 'Comparator', if it can be uniquely identified. If there /// are no matches an empty \c StringRef is returned. If there are ambigious /// matches, an empty \c StringRef is returned and a corresponding message /// written to 'Error'. StringRef findEquivalent(StringRef FileName, raw_ostream &Error) const; private: FileMatchTrieNode *Root; std::unique_ptr<PathComparator> Comparator; }; } // end namespace tooling } // end namespace clang #endif
0
repos/DirectXShaderCompiler/tools/clang/include/clang/Tooling
repos/DirectXShaderCompiler/tools/clang/include/clang/Tooling/Core/Replacement.h
//===--- Replacement.h - Framework for clang refactoring tools --*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // Classes supporting refactorings that span multiple translation units. // While single translation unit refactorings are supported via the Rewriter, // when refactoring multiple translation units changes must be stored in a // SourceManager independent form, duplicate changes need to be removed, and // all changes must be applied at once at the end of the refactoring so that // the code is always parseable. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_TOOLING_CORE_REPLACEMENT_H #define LLVM_CLANG_TOOLING_CORE_REPLACEMENT_H #include "clang/Basic/LangOptions.h" #include "clang/Basic/SourceLocation.h" #include "llvm/ADT/StringRef.h" #include <set> #include <string> #include <vector> namespace clang { class Rewriter; namespace tooling { /// \brief A source range independent of the \c SourceManager. class Range { public: Range() : Offset(0), Length(0) {} Range(unsigned Offset, unsigned Length) : Offset(Offset), Length(Length) {} /// \brief Accessors. /// @{ unsigned getOffset() const { return Offset; } unsigned getLength() const { return Length; } /// @} /// \name Range Predicates /// @{ /// \brief Whether this range overlaps with \p RHS or not. bool overlapsWith(Range RHS) const { return Offset + Length > RHS.Offset && Offset < RHS.Offset + RHS.Length; } /// \brief Whether this range contains \p RHS or not. bool contains(Range RHS) const { return RHS.Offset >= Offset && (RHS.Offset + RHS.Length) <= (Offset + Length); } /// @} private: unsigned Offset; unsigned Length; }; /// \brief A text replacement. /// /// Represents a SourceManager independent replacement of a range of text in a /// specific file. class Replacement { public: /// \brief Creates an invalid (not applicable) replacement. Replacement(); /// \brief Creates a replacement of the range [Offset, Offset+Length) in /// FilePath with ReplacementText. /// /// \param FilePath A source file accessible via a SourceManager. /// \param Offset The byte offset of the start of the range in the file. /// \param Length The length of the range in bytes. Replacement(StringRef FilePath, unsigned Offset, unsigned Length, StringRef ReplacementText); /// \brief Creates a Replacement of the range [Start, Start+Length) with /// ReplacementText. Replacement(const SourceManager &Sources, SourceLocation Start, unsigned Length, StringRef ReplacementText); /// \brief Creates a Replacement of the given range with ReplacementText. Replacement(const SourceManager &Sources, const CharSourceRange &Range, StringRef ReplacementText, const LangOptions &LangOpts = LangOptions()); /// \brief Creates a Replacement of the node with ReplacementText. template <typename Node> Replacement(const SourceManager &Sources, const Node &NodeToReplace, StringRef ReplacementText, const LangOptions &LangOpts = LangOptions()); /// \brief Returns whether this replacement can be applied to a file. /// /// Only replacements that are in a valid file can be applied. bool isApplicable() const; /// \brief Accessors. /// @{ StringRef getFilePath() const { return FilePath; } unsigned getOffset() const { return ReplacementRange.getOffset(); } unsigned getLength() const { return ReplacementRange.getLength(); } StringRef getReplacementText() const { return ReplacementText; } /// @} /// \brief Applies the replacement on the Rewriter. bool apply(Rewriter &Rewrite) const; /// \brief Returns a human readable string representation. std::string toString() const; private: void setFromSourceLocation(const SourceManager &Sources, SourceLocation Start, unsigned Length, StringRef ReplacementText); void setFromSourceRange(const SourceManager &Sources, const CharSourceRange &Range, StringRef ReplacementText, const LangOptions &LangOpts); std::string FilePath; Range ReplacementRange; std::string ReplacementText; }; /// \brief Less-than operator between two Replacements. bool operator<(const Replacement &LHS, const Replacement &RHS); /// \brief Equal-to operator between two Replacements. bool operator==(const Replacement &LHS, const Replacement &RHS); /// \brief A set of Replacements. /// FIXME: Change to a vector and deduplicate in the RefactoringTool. typedef std::set<Replacement> Replacements; /// \brief Apply all replacements in \p Replaces to the Rewriter \p Rewrite. /// /// Replacement applications happen independently of the success of /// other applications. /// /// \returns true if all replacements apply. false otherwise. bool applyAllReplacements(const Replacements &Replaces, Rewriter &Rewrite); /// \brief Apply all replacements in \p Replaces to the Rewriter \p Rewrite. /// /// Replacement applications happen independently of the success of /// other applications. /// /// \returns true if all replacements apply. false otherwise. bool applyAllReplacements(const std::vector<Replacement> &Replaces, Rewriter &Rewrite); /// \brief Applies all replacements in \p Replaces to \p Code. /// /// This completely ignores the path stored in each replacement. If one or more /// replacements cannot be applied, this returns an empty \c string. std::string applyAllReplacements(StringRef Code, const Replacements &Replaces); /// \brief Calculates how a code \p Position is shifted when \p Replaces are /// applied. unsigned shiftedCodePosition(const Replacements& Replaces, unsigned Position); /// \brief Calculates how a code \p Position is shifted when \p Replaces are /// applied. /// /// \pre Replaces[i].getOffset() <= Replaces[i+1].getOffset(). unsigned shiftedCodePosition(const std::vector<Replacement> &Replaces, unsigned Position); /// \brief Removes duplicate Replacements and reports if Replacements conflict /// with one another. All Replacements are assumed to be in the same file. /// /// \post Replaces[i].getOffset() <= Replaces[i+1].getOffset(). /// /// This function sorts \p Replaces so that conflicts can be reported simply by /// offset into \p Replaces and number of elements in the conflict. void deduplicate(std::vector<Replacement> &Replaces, std::vector<Range> &Conflicts); /// \brief Collection of Replacements generated from a single translation unit. struct TranslationUnitReplacements { /// Name of the main source for the translation unit. std::string MainSourceFile; /// A freeform chunk of text to describe the context of the replacements. /// Will be printed, for example, when detecting conflicts during replacement /// deduplication. std::string Context; std::vector<Replacement> Replacements; }; /// \brief Apply all replacements in \p Replaces to the Rewriter \p Rewrite. /// /// Replacement applications happen independently of the success of /// other applications. /// /// \returns true if all replacements apply. false otherwise. bool applyAllReplacements(const Replacements &Replaces, Rewriter &Rewrite); /// \brief Apply all replacements in \p Replaces to the Rewriter \p Rewrite. /// /// Replacement applications happen independently of the success of /// other applications. /// /// \returns true if all replacements apply. false otherwise. bool applyAllReplacements(const std::vector<Replacement> &Replaces, Rewriter &Rewrite); /// \brief Applies all replacements in \p Replaces to \p Code. /// /// This completely ignores the path stored in each replacement. If one or more /// replacements cannot be applied, this returns an empty \c string. std::string applyAllReplacements(StringRef Code, const Replacements &Replaces); template <typename Node> Replacement::Replacement(const SourceManager &Sources, const Node &NodeToReplace, StringRef ReplacementText, const LangOptions &LangOpts) { const CharSourceRange Range = CharSourceRange::getTokenRange(NodeToReplace->getSourceRange()); setFromSourceRange(Sources, Range, ReplacementText, LangOpts); } } // end namespace tooling } // end namespace clang #endif // LLVM_CLANG_TOOLING_CORE_REPLACEMENT_H
0
repos/DirectXShaderCompiler/tools/clang/include/clang
repos/DirectXShaderCompiler/tools/clang/include/clang/Lex/PreprocessorOptions.h
//===--- PreprocessorOptions.h ----------------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_LEX_PREPROCESSOROPTIONS_H_ #define LLVM_CLANG_LEX_PREPROCESSOROPTIONS_H_ #include "clang/Basic/SourceLocation.h" #include "llvm/ADT/IntrusiveRefCntPtr.h" #include "llvm/ADT/SmallVector.h" #include "llvm/ADT/StringRef.h" #include "llvm/ADT/StringSet.h" #include <cassert> #include <set> #include <string> #include <utility> #include <vector> namespace llvm { class MemoryBuffer; } namespace clang { class Preprocessor; class LangOptions; /// \brief Enumerate the kinds of standard library that enum ObjCXXARCStandardLibraryKind { ARCXX_nolib, /// \brief libc++ ARCXX_libcxx, /// \brief libstdc++ ARCXX_libstdcxx }; /// PreprocessorOptions - This class is used for passing the various options /// used in preprocessor initialization to InitializePreprocessor(). class PreprocessorOptions : public RefCountedBase<PreprocessorOptions> { public: std::vector<std::pair<std::string, bool/*isUndef*/> > Macros; std::vector<std::string> Includes; std::vector<std::string> MacroIncludes; /// \brief Initialize the preprocessor with the compiler and target specific /// predefines. unsigned UsePredefines : 1; /// \brief Whether we should maintain a detailed record of all macro /// definitions and expansions. unsigned DetailedRecord : 1; // HLSL Change Begin - ignore line directives. /// \brief Whether we should ignore #line directives. unsigned IgnoreLineDirectives : 1; /// \brief Expand the operands before performing token-pasting (fxc behavior) unsigned ExpandTokPastingArg : 1; // HLSL Change End /// The implicit PCH included at the start of the translation unit, or empty. std::string ImplicitPCHInclude; /// \brief Headers that will be converted to chained PCHs in memory. std::vector<std::string> ChainedIncludes; /// \brief When true, disables most of the normal validation performed on /// precompiled headers. bool DisablePCHValidation; /// \brief When true, a PCH with compiler errors will not be rejected. bool AllowPCHWithCompilerErrors; /// \brief Dump declarations that are deserialized from PCH, for testing. bool DumpDeserializedPCHDecls; /// \brief This is a set of names for decls that we do not want to be /// deserialized, and we emit an error if they are; for testing purposes. std::set<std::string> DeserializedPCHDeclsToErrorOn; /// \brief If non-zero, the implicit PCH include is actually a precompiled /// preamble that covers this number of bytes in the main source file. /// /// The boolean indicates whether the preamble ends at the start of a new /// line. std::pair<unsigned, bool> PrecompiledPreambleBytes; /// The implicit PTH input included at the start of the translation unit, or /// empty. std::string ImplicitPTHInclude; /// If given, a PTH cache file to use for speeding up header parsing. std::string TokenCache; /// \brief True if the SourceManager should report the original file name for /// contents of files that were remapped to other files. Defaults to true. bool RemappedFilesKeepOriginalName; /// \brief The set of file remappings, which take existing files on /// the system (the first part of each pair) and gives them the /// contents of other files on the system (the second part of each /// pair). std::vector<std::pair<std::string, std::string>> RemappedFiles; /// \brief The set of file-to-buffer remappings, which take existing files /// on the system (the first part of each pair) and gives them the contents /// of the specified memory buffer (the second part of each pair). std::vector<std::pair<std::string, llvm::MemoryBuffer *>> RemappedFileBuffers; /// \brief Whether the compiler instance should retain (i.e., not free) /// the buffers associated with remapped files. /// /// This flag defaults to false; it can be set true only through direct /// manipulation of the compiler invocation object, in cases where the /// compiler invocation and its buffers will be reused. bool RetainRemappedFileBuffers; /// \brief The Objective-C++ ARC standard library that we should support, /// by providing appropriate definitions to retrofit the standard library /// with support for lifetime-qualified pointers. ObjCXXARCStandardLibraryKind ObjCXXARCStandardLibrary; /// \brief Records the set of modules class FailedModulesSet : public RefCountedBase<FailedModulesSet> { llvm::StringSet<> Failed; public: bool hasAlreadyFailed(StringRef mod) { return Failed.count(mod) > 0; } void addFailed(StringRef mod) { Failed.insert(mod); } }; /// \brief The set of modules that failed to build. /// /// This pointer will be shared among all of the compiler instances created /// to (re)build modules, so that once a module fails to build anywhere, /// other instances will see that the module has failed and won't try to /// build it again. IntrusiveRefCntPtr<FailedModulesSet> FailedModules; public: PreprocessorOptions() : UsePredefines(true), DetailedRecord(false), IgnoreLineDirectives(false), // HLSL Change - ignore line directives. DisablePCHValidation(false), AllowPCHWithCompilerErrors(false), DumpDeserializedPCHDecls(false), PrecompiledPreambleBytes(0, true), RemappedFilesKeepOriginalName(true), RetainRemappedFileBuffers(false), ObjCXXARCStandardLibrary(ARCXX_nolib) { } void addMacroDef(StringRef Name) { Macros.emplace_back(Name, false); } void addMacroUndef(StringRef Name) { Macros.emplace_back(Name, true); } void addRemappedFile(StringRef From, StringRef To) { RemappedFiles.emplace_back(From, To); } void addRemappedFile(StringRef From, llvm::MemoryBuffer *To) { RemappedFileBuffers.emplace_back(From, To); } void clearRemappedFiles() { RemappedFiles.clear(); RemappedFileBuffers.clear(); } /// \brief Reset any options that are not considered when building a /// module. void resetNonModularOptions() { Includes.clear(); MacroIncludes.clear(); ChainedIncludes.clear(); DumpDeserializedPCHDecls = false; ImplicitPCHInclude.clear(); ImplicitPTHInclude.clear(); TokenCache.clear(); RetainRemappedFileBuffers = true; PrecompiledPreambleBytes.first = 0; PrecompiledPreambleBytes.second = 0; } }; } // end namespace clang #endif
0
repos/DirectXShaderCompiler/tools/clang/include/clang
repos/DirectXShaderCompiler/tools/clang/include/clang/Lex/MultipleIncludeOpt.h
//===--- MultipleIncludeOpt.h - Header Multiple-Include Optzn ---*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// /// /// \file /// \brief Defines the MultipleIncludeOpt interface. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_LEX_MULTIPLEINCLUDEOPT_H #define LLVM_CLANG_LEX_MULTIPLEINCLUDEOPT_H #include "clang/Basic/SourceLocation.h" namespace clang { class IdentifierInfo; /// \brief Implements the simple state machine that the Lexer class uses to /// detect files subject to the 'multiple-include' optimization. /// /// The public methods in this class are triggered by various /// events that occur when a file is lexed, and after the entire file is lexed, /// information about which macro (if any) controls the header is returned. class MultipleIncludeOpt { /// ReadAnyTokens - This is set to false when a file is first opened and true /// any time a token is returned to the client or a (non-multiple-include) /// directive is parsed. When the final \#endif is parsed this is reset back /// to false, that way any tokens before the first \#ifdef or after the last /// \#endif can be easily detected. bool ReadAnyTokens; /// ImmediatelyAfterTopLevelIfndef - This is true when the only tokens /// processed in the file so far is an #ifndef and an identifier. Used in /// the detection of header guards in a file. bool ImmediatelyAfterTopLevelIfndef; /// ReadAnyTokens - This is set to false when a file is first opened and true /// any time a token is returned to the client or a (non-multiple-include) /// directive is parsed. When the final #endif is parsed this is reset back /// to false, that way any tokens before the first #ifdef or after the last /// #endif can be easily detected. bool DidMacroExpansion; /// TheMacro - The controlling macro for a file, if valid. /// const IdentifierInfo *TheMacro; /// DefinedMacro - The macro defined right after TheMacro, if any. const IdentifierInfo *DefinedMacro; SourceLocation MacroLoc; SourceLocation DefinedLoc; public: MultipleIncludeOpt() { ReadAnyTokens = false; ImmediatelyAfterTopLevelIfndef = false; DidMacroExpansion = false; TheMacro = nullptr; DefinedMacro = nullptr; } SourceLocation GetMacroLocation() const { return MacroLoc; } SourceLocation GetDefinedLocation() const { return DefinedLoc; } void resetImmediatelyAfterTopLevelIfndef() { ImmediatelyAfterTopLevelIfndef = false; } void SetDefinedMacro(IdentifierInfo *M, SourceLocation Loc) { DefinedMacro = M; DefinedLoc = Loc; } /// Invalidate - Permanently mark this file as not being suitable for the /// include-file optimization. void Invalidate() { // If we have read tokens but have no controlling macro, the state-machine // below can never "accept". ReadAnyTokens = true; ImmediatelyAfterTopLevelIfndef = false; DefinedMacro = nullptr; TheMacro = nullptr; } /// getHasReadAnyTokensVal - This is used for the \#ifndef hande-shake at the /// top of the file when reading preprocessor directives. Otherwise, reading /// the "ifndef x" would count as reading tokens. bool getHasReadAnyTokensVal() const { return ReadAnyTokens; } /// getImmediatelyAfterTopLevelIfndef - returns true if the last directive /// was an #ifndef at the beginning of the file. bool getImmediatelyAfterTopLevelIfndef() const { return ImmediatelyAfterTopLevelIfndef; } // If a token is read, remember that we have seen a side-effect in this file. void ReadToken() { ReadAnyTokens = true; ImmediatelyAfterTopLevelIfndef = false; } /// ExpandedMacro - When a macro is expanded with this lexer as the current /// buffer, this method is called to disable the MIOpt if needed. void ExpandedMacro() { DidMacroExpansion = true; } /// \brief Called when entering a top-level \#ifndef directive (or the /// "\#if !defined" equivalent) without any preceding tokens. /// /// Note, we don't care about the input value of 'ReadAnyTokens'. The caller /// ensures that this is only called if there are no tokens read before the /// \#ifndef. The caller is required to do this, because reading the \#if /// line obviously reads in in tokens. void EnterTopLevelIfndef(const IdentifierInfo *M, SourceLocation Loc) { // If the macro is already set, this is after the top-level #endif. if (TheMacro) return Invalidate(); // If we have already expanded a macro by the end of the #ifndef line, then // there is a macro expansion *in* the #ifndef line. This means that the // condition could evaluate differently when subsequently #included. Reject // this. if (DidMacroExpansion) return Invalidate(); // Remember that we're in the #if and that we have the macro. ReadAnyTokens = true; ImmediatelyAfterTopLevelIfndef = true; TheMacro = M; MacroLoc = Loc; } /// \brief Invoked when a top level conditional (except \#ifndef) is found. void EnterTopLevelConditional() { // If a conditional directive (except #ifndef) is found at the top level, // there is a chunk of the file not guarded by the controlling macro. Invalidate(); } /// \brief Called when the lexer exits the top-level conditional. void ExitTopLevelConditional() { // If we have a macro, that means the top of the file was ok. Set our state // back to "not having read any tokens" so we can detect anything after the // #endif. if (!TheMacro) return Invalidate(); // At this point, we haven't "read any tokens" but we do have a controlling // macro. ReadAnyTokens = false; ImmediatelyAfterTopLevelIfndef = false; } /// \brief Once the entire file has been lexed, if there is a controlling /// macro, return it. const IdentifierInfo *GetControllingMacroAtEndOfFile() const { // If we haven't read any tokens after the #endif, return the controlling // macro if it's valid (if it isn't, it will be null). if (!ReadAnyTokens) return TheMacro; return nullptr; } /// \brief If the ControllingMacro is followed by a macro definition, return /// the macro that was defined. const IdentifierInfo *GetDefinedMacro() const { return DefinedMacro; } }; } // end namespace clang #endif
0
repos/DirectXShaderCompiler/tools/clang/include/clang
repos/DirectXShaderCompiler/tools/clang/include/clang/Lex/LexDiagnostic.h
//===--- DiagnosticLex.h - Diagnostics for liblex ---------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_LEX_LEXDIAGNOSTIC_H #define LLVM_CLANG_LEX_LEXDIAGNOSTIC_H #include "clang/Basic/Diagnostic.h" namespace clang { namespace diag { enum { #define DIAG(ENUM,FLAGS,DEFAULT_MAPPING,DESC,GROUP,\ SFINAE,NOWERROR,SHOWINSYSHEADER,CATEGORY) ENUM, #define LEXSTART #include "clang/Basic/DiagnosticLexKinds.inc" #undef DIAG NUM_BUILTIN_LEX_DIAGNOSTICS }; } // end namespace diag } // end namespace clang #endif
0
repos/DirectXShaderCompiler/tools/clang/include/clang
repos/DirectXShaderCompiler/tools/clang/include/clang/Lex/PreprocessingRecord.h
//===--- PreprocessingRecord.h - Record of Preprocessing --------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines the PreprocessingRecord class, which maintains a record // of what occurred during preprocessing. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_LEX_PREPROCESSINGRECORD_H #define LLVM_CLANG_LEX_PREPROCESSINGRECORD_H #include "clang/Basic/IdentifierTable.h" #include "clang/Basic/SourceLocation.h" #include "clang/Lex/PPCallbacks.h" #include "llvm/ADT/DenseMap.h" #include "llvm/ADT/Optional.h" #include "llvm/ADT/SmallVector.h" #include "llvm/ADT/iterator.h" #include "llvm/Support/Allocator.h" #include "llvm/Support/Compiler.h" #include <vector> namespace clang { class IdentifierInfo; class MacroInfo; class PreprocessingRecord; } /// \brief Allocates memory within a Clang preprocessing record. void* operator new(size_t bytes, clang::PreprocessingRecord& PR, unsigned alignment = 8) throw(); /// \brief Frees memory allocated in a Clang preprocessing record. void operator delete(void *ptr, clang::PreprocessingRecord &PR, unsigned) throw(); namespace clang { class MacroDefinitionRecord; class FileEntry; /// \brief Base class that describes a preprocessed entity, which may be a /// preprocessor directive or macro expansion. class PreprocessedEntity { public: /// \brief The kind of preprocessed entity an object describes. enum EntityKind { /// \brief Indicates a problem trying to load the preprocessed entity. InvalidKind, /// \brief A macro expansion. MacroExpansionKind, /// \defgroup Preprocessing directives /// @{ /// \brief A macro definition. MacroDefinitionKind, /// \brief An inclusion directive, such as \c \#include, \c /// \#import, or \c \#include_next. InclusionDirectiveKind, /// @} FirstPreprocessingDirective = MacroDefinitionKind, LastPreprocessingDirective = InclusionDirectiveKind }; private: /// \brief The kind of preprocessed entity that this object describes. EntityKind Kind; /// \brief The source range that covers this preprocessed entity. SourceRange Range; protected: PreprocessedEntity(EntityKind Kind, SourceRange Range) : Kind(Kind), Range(Range) { } friend class PreprocessingRecord; public: /// \brief Retrieve the kind of preprocessed entity stored in this object. EntityKind getKind() const { return Kind; } /// \brief Retrieve the source range that covers this entire preprocessed /// entity. SourceRange getSourceRange() const LLVM_READONLY { return Range; } /// \brief Returns true if there was a problem loading the preprocessed /// entity. bool isInvalid() const { return Kind == InvalidKind; } // Only allow allocation of preprocessed entities using the allocator // in PreprocessingRecord or by doing a placement new. void* operator new(size_t bytes, PreprocessingRecord& PR, unsigned alignment = 8) throw() { return ::operator new(bytes, PR, alignment); } void* operator new(size_t bytes, void* mem) throw() { return mem; } void operator delete(void* ptr, PreprocessingRecord& PR, unsigned alignment) throw() { return ::operator delete(ptr, PR, alignment); } void operator delete(void*, std::size_t) throw() { } void operator delete(void*, void*) throw() { } private: // Make vanilla 'new' and 'delete' illegal for preprocessed entities. void* operator new(size_t bytes) throw(); void operator delete(void* data) throw(); }; /// \brief Records the presence of a preprocessor directive. class PreprocessingDirective : public PreprocessedEntity { public: PreprocessingDirective(EntityKind Kind, SourceRange Range) : PreprocessedEntity(Kind, Range) { } // Implement isa/cast/dyncast/etc. static bool classof(const PreprocessedEntity *PD) { return PD->getKind() >= FirstPreprocessingDirective && PD->getKind() <= LastPreprocessingDirective; } }; /// \brief Record the location of a macro definition. class MacroDefinitionRecord : public PreprocessingDirective { /// \brief The name of the macro being defined. const IdentifierInfo *Name; public: explicit MacroDefinitionRecord(const IdentifierInfo *Name, SourceRange Range) : PreprocessingDirective(MacroDefinitionKind, Range), Name(Name) {} /// \brief Retrieve the name of the macro being defined. const IdentifierInfo *getName() const { return Name; } /// \brief Retrieve the location of the macro name in the definition. SourceLocation getLocation() const { return getSourceRange().getBegin(); } // Implement isa/cast/dyncast/etc. static bool classof(const PreprocessedEntity *PE) { return PE->getKind() == MacroDefinitionKind; } }; /// \brief Records the location of a macro expansion. class MacroExpansion : public PreprocessedEntity { /// \brief The definition of this macro or the name of the macro if it is /// a builtin macro. llvm::PointerUnion<IdentifierInfo *, MacroDefinitionRecord *> NameOrDef; public: MacroExpansion(IdentifierInfo *BuiltinName, SourceRange Range) : PreprocessedEntity(MacroExpansionKind, Range), NameOrDef(BuiltinName) {} MacroExpansion(MacroDefinitionRecord *Definition, SourceRange Range) : PreprocessedEntity(MacroExpansionKind, Range), NameOrDef(Definition) { } /// \brief True if it is a builtin macro. bool isBuiltinMacro() const { return NameOrDef.is<IdentifierInfo *>(); } /// \brief The name of the macro being expanded. const IdentifierInfo *getName() const { if (MacroDefinitionRecord *Def = getDefinition()) return Def->getName(); return NameOrDef.get<IdentifierInfo *>(); } /// \brief The definition of the macro being expanded. May return null if /// this is a builtin macro. MacroDefinitionRecord *getDefinition() const { return NameOrDef.dyn_cast<MacroDefinitionRecord *>(); } // Implement isa/cast/dyncast/etc. static bool classof(const PreprocessedEntity *PE) { return PE->getKind() == MacroExpansionKind; } }; /// \brief Record the location of an inclusion directive, such as an /// \c \#include or \c \#import statement. class InclusionDirective : public PreprocessingDirective { public: /// \brief The kind of inclusion directives known to the /// preprocessor. enum InclusionKind { /// \brief An \c \#include directive. Include, /// \brief An Objective-C \c \#import directive. Import, /// \brief A GNU \c \#include_next directive. IncludeNext, /// \brief A Clang \c \#__include_macros directive. IncludeMacros }; private: /// \brief The name of the file that was included, as written in /// the source. StringRef FileName; /// \brief Whether the file name was in quotation marks; otherwise, it was /// in angle brackets. unsigned InQuotes : 1; /// \brief The kind of inclusion directive we have. /// /// This is a value of type InclusionKind. unsigned Kind : 2; /// \brief Whether the inclusion directive was automatically turned into /// a module import. unsigned ImportedModule : 1; /// \brief The file that was included. const FileEntry *File; public: InclusionDirective(PreprocessingRecord &PPRec, InclusionKind Kind, StringRef FileName, bool InQuotes, bool ImportedModule, const FileEntry *File, SourceRange Range); /// \brief Determine what kind of inclusion directive this is. InclusionKind getKind() const { return static_cast<InclusionKind>(Kind); } /// \brief Retrieve the included file name as it was written in the source. StringRef getFileName() const { return FileName; } /// \brief Determine whether the included file name was written in quotes; /// otherwise, it was written in angle brackets. bool wasInQuotes() const { return InQuotes; } /// \brief Determine whether the inclusion directive was automatically /// turned into a module import. bool importedModule() const { return ImportedModule; } /// \brief Retrieve the file entry for the actual file that was included /// by this directive. const FileEntry *getFile() const { return File; } // Implement isa/cast/dyncast/etc. static bool classof(const PreprocessedEntity *PE) { return PE->getKind() == InclusionDirectiveKind; } }; /// \brief An abstract class that should be subclassed by any external source /// of preprocessing record entries. class ExternalPreprocessingRecordSource { public: virtual ~ExternalPreprocessingRecordSource(); /// \brief Read a preallocated preprocessed entity from the external source. /// /// \returns null if an error occurred that prevented the preprocessed /// entity from being loaded. virtual PreprocessedEntity *ReadPreprocessedEntity(unsigned Index) = 0; /// \brief Returns a pair of [Begin, End) indices of preallocated /// preprocessed entities that \p Range encompasses. virtual std::pair<unsigned, unsigned> findPreprocessedEntitiesInRange(SourceRange Range) = 0; /// \brief Optionally returns true or false if the preallocated preprocessed /// entity with index \p Index came from file \p FID. virtual Optional<bool> isPreprocessedEntityInFileID(unsigned Index, FileID FID) { return None; } }; /// \brief A record of the steps taken while preprocessing a source file, /// including the various preprocessing directives processed, macros /// expanded, etc. class PreprocessingRecord : public PPCallbacks { SourceManager &SourceMgr; /// \brief Allocator used to store preprocessing objects. llvm::BumpPtrAllocator BumpAlloc; /// \brief The set of preprocessed entities in this record, in order they /// were seen. std::vector<PreprocessedEntity *> PreprocessedEntities; /// \brief The set of preprocessed entities in this record that have been /// loaded from external sources. /// /// The entries in this vector are loaded lazily from the external source, /// and are referenced by the iterator using negative indices. std::vector<PreprocessedEntity *> LoadedPreprocessedEntities; /// \brief The set of ranges that were skipped by the preprocessor, std::vector<SourceRange> SkippedRanges; /// \brief Global (loaded or local) ID for a preprocessed entity. /// Negative values are used to indicate preprocessed entities /// loaded from the external source while non-negative values are used to /// indicate preprocessed entities introduced by the current preprocessor. /// Value -1 corresponds to element 0 in the loaded entities vector, /// value -2 corresponds to element 1 in the loaded entities vector, etc. /// Value 0 is an invalid value, the index to local entities is 1-based, /// value 1 corresponds to element 0 in the local entities vector, /// value 2 corresponds to element 1 in the local entities vector, etc. class PPEntityID { int ID; explicit PPEntityID(int ID) : ID(ID) {} friend class PreprocessingRecord; public: PPEntityID() : ID(0) {} }; static PPEntityID getPPEntityID(unsigned Index, bool isLoaded) { return isLoaded ? PPEntityID(-int(Index)-1) : PPEntityID(Index+1); } /// \brief Mapping from MacroInfo structures to their definitions. llvm::DenseMap<const MacroInfo *, MacroDefinitionRecord *> MacroDefinitions; /// \brief External source of preprocessed entities. ExternalPreprocessingRecordSource *ExternalSource; /// \brief Retrieve the preprocessed entity at the given ID. PreprocessedEntity *getPreprocessedEntity(PPEntityID PPID); /// \brief Retrieve the loaded preprocessed entity at the given index. PreprocessedEntity *getLoadedPreprocessedEntity(unsigned Index); /// \brief Determine the number of preprocessed entities that were /// loaded (or can be loaded) from an external source. unsigned getNumLoadedPreprocessedEntities() const { return LoadedPreprocessedEntities.size(); } /// \brief Returns a pair of [Begin, End) indices of local preprocessed /// entities that \p Range encompasses. std::pair<unsigned, unsigned> findLocalPreprocessedEntitiesInRange(SourceRange Range) const; unsigned findBeginLocalPreprocessedEntity(SourceLocation Loc) const; unsigned findEndLocalPreprocessedEntity(SourceLocation Loc) const; /// \brief Allocate space for a new set of loaded preprocessed entities. /// /// \returns The index into the set of loaded preprocessed entities, which /// corresponds to the first newly-allocated entity. unsigned allocateLoadedEntities(unsigned NumEntities); /// \brief Register a new macro definition. void RegisterMacroDefinition(MacroInfo *Macro, MacroDefinitionRecord *Def); public: /// \brief Construct a new preprocessing record. explicit PreprocessingRecord(SourceManager &SM); /// \brief Allocate memory in the preprocessing record. void *Allocate(unsigned Size, unsigned Align = 8) { return BumpAlloc.Allocate(Size, Align); } /// \brief Deallocate memory in the preprocessing record. void Deallocate(void *Ptr) { } size_t getTotalMemory() const; SourceManager &getSourceManager() const { return SourceMgr; } /// Iteration over the preprocessed entities. /// /// In a complete iteration, the iterator walks the range [-M, N), /// where negative values are used to indicate preprocessed entities /// loaded from the external source while non-negative values are used to /// indicate preprocessed entities introduced by the current preprocessor. /// However, to provide iteration in source order (for, e.g., chained /// precompiled headers), dereferencing the iterator flips the negative /// values (corresponding to loaded entities), so that position -M /// corresponds to element 0 in the loaded entities vector, position -M+1 /// corresponds to element 1 in the loaded entities vector, etc. This /// gives us a reasonably efficient, source-order walk. /// /// We define this as a wrapping iterator around an int. The /// iterator_adaptor_base class forwards the iterator methods to basic /// integer arithmetic. class iterator : public llvm::iterator_adaptor_base< iterator, int, std::random_access_iterator_tag, PreprocessedEntity *, int, PreprocessedEntity *, PreprocessedEntity *> { PreprocessingRecord *Self; iterator(PreprocessingRecord *Self, int Position) : iterator::iterator_adaptor_base(Position), Self(Self) {} friend class PreprocessingRecord; public: iterator() : iterator(nullptr, 0) {} PreprocessedEntity *operator*() const { bool isLoaded = this->I < 0; unsigned Index = isLoaded ? Self->LoadedPreprocessedEntities.size() + this->I : this->I; PPEntityID ID = Self->getPPEntityID(Index, isLoaded); return Self->getPreprocessedEntity(ID); } PreprocessedEntity *operator->() const { return **this; } }; /// \brief Begin iterator for all preprocessed entities. iterator begin() { return iterator(this, -(int)LoadedPreprocessedEntities.size()); } /// \brief End iterator for all preprocessed entities. iterator end() { return iterator(this, PreprocessedEntities.size()); } /// \brief Begin iterator for local, non-loaded, preprocessed entities. iterator local_begin() { return iterator(this, 0); } /// \brief End iterator for local, non-loaded, preprocessed entities. iterator local_end() { return iterator(this, PreprocessedEntities.size()); } /// \brief iterator range for the given range of loaded /// preprocessed entities. llvm::iterator_range<iterator> getIteratorsForLoadedRange(unsigned start, unsigned count) { unsigned end = start + count; assert(end <= LoadedPreprocessedEntities.size()); return llvm::make_range( iterator(this, int(start) - LoadedPreprocessedEntities.size()), iterator(this, int(end) - LoadedPreprocessedEntities.size())); } /// \brief Returns a range of preprocessed entities that source range \p R /// encompasses. /// /// \param R the range to look for preprocessed entities. /// llvm::iterator_range<iterator> getPreprocessedEntitiesInRange(SourceRange R); /// \brief Returns true if the preprocessed entity that \p PPEI iterator /// points to is coming from the file \p FID. /// /// Can be used to avoid implicit deserializations of preallocated /// preprocessed entities if we only care about entities of a specific file /// and not from files \#included in the range given at /// \see getPreprocessedEntitiesInRange. bool isEntityInFileID(iterator PPEI, FileID FID); /// \brief Add a new preprocessed entity to this record. PPEntityID addPreprocessedEntity(PreprocessedEntity *Entity); /// \brief Set the external source for preprocessed entities. void SetExternalSource(ExternalPreprocessingRecordSource &Source); /// \brief Retrieve the external source for preprocessed entities. ExternalPreprocessingRecordSource *getExternalSource() const { return ExternalSource; } /// \brief Retrieve the macro definition that corresponds to the given /// \c MacroInfo. MacroDefinitionRecord *findMacroDefinition(const MacroInfo *MI); /// \brief Retrieve all ranges that got skipped while preprocessing. const std::vector<SourceRange> &getSkippedRanges() const { return SkippedRanges; } private: void MacroExpands(const Token &Id, const MacroDefinition &MD, SourceRange Range, const MacroArgs *Args) override; void MacroDefined(const Token &Id, const MacroDirective *MD) override; void MacroUndefined(const Token &Id, const MacroDefinition &MD) override; void InclusionDirective(SourceLocation HashLoc, const Token &IncludeTok, StringRef FileName, bool IsAngled, CharSourceRange FilenameRange, const FileEntry *File, StringRef SearchPath, StringRef RelativePath, const Module *Imported) override; void Ifdef(SourceLocation Loc, const Token &MacroNameTok, const MacroDefinition &MD) override; void Ifndef(SourceLocation Loc, const Token &MacroNameTok, const MacroDefinition &MD) override; /// \brief Hook called whenever the 'defined' operator is seen. void Defined(const Token &MacroNameTok, const MacroDefinition &MD, SourceRange Range) override; void SourceRangeSkipped(SourceRange Range) override; void addMacroExpansion(const Token &Id, const MacroInfo *MI, SourceRange Range); /// \brief Cached result of the last \see getPreprocessedEntitiesInRange /// query. struct { SourceRange Range; std::pair<int, int> Result; } CachedRangeQuery; std::pair<int, int> getPreprocessedEntitiesInRangeSlow(SourceRange R); friend class ASTReader; friend class ASTWriter; }; } // end namespace clang inline void* operator new(size_t bytes, clang::PreprocessingRecord& PR, unsigned alignment) throw() { return PR.Allocate(bytes, alignment); } inline void operator delete(void* ptr, clang::PreprocessingRecord& PR, unsigned) throw() { PR.Deallocate(ptr); } #endif // LLVM_CLANG_LEX_PREPROCESSINGRECORD_H
0
repos/DirectXShaderCompiler/tools/clang/include/clang
repos/DirectXShaderCompiler/tools/clang/include/clang/Lex/HeaderMap.h
//===--- HeaderMap.h - A file that acts like dir of symlinks ----*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines the HeaderMap interface. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_LEX_HEADERMAP_H #define LLVM_CLANG_LEX_HEADERMAP_H #include "clang/Basic/LLVM.h" #include "llvm/Support/Compiler.h" #include "llvm/Support/MemoryBuffer.h" #include <memory> namespace clang { class FileEntry; class FileManager; struct HMapBucket; struct HMapHeader; /// This class represents an Apple concept known as a 'header map'. To the /// \#include file resolution process, it basically acts like a directory of /// symlinks to files. Its advantages are that it is dense and more efficient /// to create and process than a directory of symlinks. class HeaderMap { HeaderMap(const HeaderMap &) = delete; void operator=(const HeaderMap &) = delete; std::unique_ptr<const llvm::MemoryBuffer> FileBuffer; bool NeedsBSwap; HeaderMap(std::unique_ptr<const llvm::MemoryBuffer> File, bool BSwap) : FileBuffer(std::move(File)), NeedsBSwap(BSwap) {} public: /// HeaderMap::Create - This attempts to load the specified file as a header /// map. If it doesn't look like a HeaderMap, it gives up and returns null. static const HeaderMap *Create(const FileEntry *FE, FileManager &FM); /// LookupFile - Check to see if the specified relative filename is located in /// this HeaderMap. If so, open it and return its FileEntry. /// If RawPath is not NULL and the file is found, RawPath will be set to the /// raw path at which the file was found in the file system. For example, /// for a search path ".." and a filename "../file.h" this would be /// "../../file.h". const FileEntry *LookupFile(StringRef Filename, FileManager &FM) const; /// If the specified relative filename is located in this HeaderMap return /// the filename it is mapped to, otherwise return an empty StringRef. StringRef lookupFilename(StringRef Filename, SmallVectorImpl<char> &DestPath) const; /// getFileName - Return the filename of the headermap. const char *getFileName() const; /// dump - Print the contents of this headermap to stderr. void dump() const; private: unsigned getEndianAdjustedWord(unsigned X) const; const HMapHeader &getHeader() const; HMapBucket getBucket(unsigned BucketNo) const; const char *getString(unsigned StrTabIdx) const; }; } // end namespace clang. #endif
0
repos/DirectXShaderCompiler/tools/clang/include/clang
repos/DirectXShaderCompiler/tools/clang/include/clang/Lex/HLSLMacroExpander.h
//===--- HLSLMacroExpander.h - Standalone Macro expansion ------*- C++ -*-===// /////////////////////////////////////////////////////////////////////////////// // // // HLSLMacroExpander.h // // Copyright (C) Microsoft Corporation. All rights reserved. // // This file is distributed under the University of Illinois Open Source // // License. See LICENSE.TXT for details. // // // // This file defines utilites for expanding macros after lexing has // // completed. Normally, macros are expanded as part of the lexing // // phase and returned in an expanded form directly from the lexer. // // For hlsl we need to be able to expand macros after the fact to // // correctly capture semantic defines and root signature defines. // // // /////////////////////////////////////////////////////////////////////////////// #ifndef LLVM_CLANG_LEX_HLSLMACROEXPANDER_H #define LLVM_CLANG_LEX_HLSLMACROEXPANDER_H #include "clang/Basic/SourceLocation.h" #include <string> #include <utility> namespace clang { class Preprocessor; class Token; class MacroInfo; } // namespace clang namespace llvm { class StringRef; } namespace hlsl { class MacroExpander { public: // Options used during macro expansion. enum Option : unsigned { // Strip quotes from string literals. Enables concatenating adjacent // string literals into a single value. STRIP_QUOTES = 1 << 1, }; // Constructor MacroExpander(clang::Preprocessor &PP, unsigned options = 0); // Expand the given macro into the output string. // Returns true if macro was expanded successfully. bool ExpandMacro(clang::MacroInfo *macro, std::string *out); // Look in the preprocessor for a macro with the provided name. // Return nullptr if the macro could not be found. static clang::MacroInfo *FindMacroInfo(clang::Preprocessor &PP, llvm::StringRef macroName); private: clang::Preprocessor &PP; clang::FileID m_expansionFileId; bool m_stripQuotes; }; } // namespace hlsl #endif // header include guard
0
repos/DirectXShaderCompiler/tools/clang/include/clang
repos/DirectXShaderCompiler/tools/clang/include/clang/Lex/PPCallbacks.h
//===--- PPCallbacks.h - Callbacks for Preprocessor actions -----*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// /// /// \file /// \brief Defines the PPCallbacks interface. /// //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_LEX_PPCALLBACKS_H #define LLVM_CLANG_LEX_PPCALLBACKS_H #include "clang/Basic/DiagnosticIDs.h" #include "clang/Basic/SourceLocation.h" #include "clang/Lex/DirectoryLookup.h" #include "clang/Lex/ModuleLoader.h" #include "clang/Lex/Pragma.h" #include "llvm/ADT/StringRef.h" #include <string> namespace clang { class SourceLocation; class Token; class IdentifierInfo; class MacroDefinition; class MacroDirective; class MacroArgs; /// \brief This interface provides a way to observe the actions of the /// preprocessor as it does its thing. /// /// Clients can define their hooks here to implement preprocessor level tools. class PPCallbacks { public: virtual ~PPCallbacks(); enum FileChangeReason { EnterFile, ExitFile, SystemHeaderPragma, RenameFile }; /// \brief Callback invoked whenever a source file is entered or exited. /// /// \param Loc Indicates the new location. /// \param PrevFID the file that was exited if \p Reason is ExitFile. virtual void FileChanged(SourceLocation Loc, FileChangeReason Reason, SrcMgr::CharacteristicKind FileType, FileID PrevFID = FileID()) { } /// \brief Callback invoked whenever a source file is skipped as the result /// of header guard optimization. /// /// \param SkippedFile The file that is skipped instead of entering \#include /// /// \param FilenameTok The file name token in \#include "FileName" directive /// or macro expanded file name token from \#include MACRO(PARAMS) directive. /// Note that FilenameTok contains corresponding quotes/angles symbols. virtual void FileSkipped(const FileEntry &SkippedFile, const Token &FilenameTok, SrcMgr::CharacteristicKind FileType) { } /// \brief Callback invoked whenever an inclusion directive results in a /// file-not-found error. /// /// \param FileName The name of the file being included, as written in the /// source code. /// /// \param RecoveryPath If this client indicates that it can recover from /// this missing file, the client should set this as an additional header /// search patch. /// /// \returns true to indicate that the preprocessor should attempt to recover /// by adding \p RecoveryPath as a header search path. virtual bool FileNotFound(StringRef FileName, SmallVectorImpl<char> &RecoveryPath) { return false; } /// \brief Callback invoked whenever an inclusion directive of /// any kind (\c \#include, \c \#import, etc.) has been processed, regardless /// of whether the inclusion will actually result in an inclusion. /// /// \param HashLoc The location of the '#' that starts the inclusion /// directive. /// /// \param IncludeTok The token that indicates the kind of inclusion /// directive, e.g., 'include' or 'import'. /// /// \param FileName The name of the file being included, as written in the /// source code. /// /// \param IsAngled Whether the file name was enclosed in angle brackets; /// otherwise, it was enclosed in quotes. /// /// \param FilenameRange The character range of the quotes or angle brackets /// for the written file name. /// /// \param File The actual file that may be included by this inclusion /// directive. /// /// \param SearchPath Contains the search path which was used to find the file /// in the file system. If the file was found via an absolute include path, /// SearchPath will be empty. For framework includes, the SearchPath and /// RelativePath will be split up. For example, if an include of "Some/Some.h" /// is found via the framework path /// "path/to/Frameworks/Some.framework/Headers/Some.h", SearchPath will be /// "path/to/Frameworks/Some.framework/Headers" and RelativePath will be /// "Some.h". /// /// \param RelativePath The path relative to SearchPath, at which the include /// file was found. This is equal to FileName except for framework includes. /// /// \param Imported The module, whenever an inclusion directive was /// automatically turned into a module import or null otherwise. /// virtual void InclusionDirective(SourceLocation HashLoc, const Token &IncludeTok, StringRef FileName, bool IsAngled, CharSourceRange FilenameRange, const FileEntry *File, StringRef SearchPath, StringRef RelativePath, const Module *Imported) { } /// \brief Callback invoked whenever there was an explicit module-import /// syntax. /// /// \param ImportLoc The location of import directive token. /// /// \param Path The identifiers (and their locations) of the module /// "path", e.g., "std.vector" would be split into "std" and "vector". /// /// \param Imported The imported module; can be null if importing failed. /// virtual void moduleImport(SourceLocation ImportLoc, ModuleIdPath Path, const Module *Imported) { } /// \brief Callback invoked when the end of the main file is reached. /// /// No subsequent callbacks will be made. virtual void EndOfMainFile() { } /// \brief Callback invoked when a \#ident or \#sccs directive is read. /// \param Loc The location of the directive. /// \param str The text of the directive. /// virtual void Ident(SourceLocation Loc, StringRef str) { } /// \brief Callback invoked when start reading any pragma directive. virtual void PragmaDirective(SourceLocation Loc, PragmaIntroducerKind Introducer) { } /// \brief Callback invoked when a \#pragma comment directive is read. virtual void PragmaComment(SourceLocation Loc, const IdentifierInfo *Kind, StringRef Str) { } /// \brief Callback invoked when a \#pragma detect_mismatch directive is /// read. virtual void PragmaDetectMismatch(SourceLocation Loc, StringRef Name, StringRef Value) { } /// \brief Callback invoked when a \#pragma clang __debug directive is read. /// \param Loc The location of the debug directive. /// \param DebugType The identifier following __debug. virtual void PragmaDebug(SourceLocation Loc, StringRef DebugType) { } /// \brief Determines the kind of \#pragma invoking a call to PragmaMessage. enum PragmaMessageKind { /// \brief \#pragma message has been invoked. PMK_Message, /// \brief \#pragma GCC warning has been invoked. PMK_Warning, /// \brief \#pragma GCC error has been invoked. PMK_Error }; /// \brief Callback invoked when a \#pragma message directive is read. /// \param Loc The location of the message directive. /// \param Namespace The namespace of the message directive. /// \param Kind The type of the message directive. /// \param Str The text of the message directive. virtual void PragmaMessage(SourceLocation Loc, StringRef Namespace, PragmaMessageKind Kind, StringRef Str) { } /// \brief Callback invoked when a \#pragma gcc dianostic push directive /// is read. virtual void PragmaDiagnosticPush(SourceLocation Loc, StringRef Namespace) { } /// \brief Callback invoked when a \#pragma gcc dianostic pop directive /// is read. virtual void PragmaDiagnosticPop(SourceLocation Loc, StringRef Namespace) { } /// \brief Callback invoked when a \#pragma gcc dianostic directive is read. virtual void PragmaDiagnostic(SourceLocation Loc, StringRef Namespace, diag::Severity mapping, StringRef Str) {} /// \brief Called when an OpenCL extension is either disabled or /// enabled with a pragma. virtual void PragmaOpenCLExtension(SourceLocation NameLoc, const IdentifierInfo *Name, SourceLocation StateLoc, unsigned State) { } /// \brief Callback invoked when a \#pragma warning directive is read. virtual void PragmaWarning(SourceLocation Loc, StringRef WarningSpec, ArrayRef<int> Ids) { } /// \brief Callback invoked when a \#pragma warning(push) directive is read. virtual void PragmaWarningPush(SourceLocation Loc, int Level) { } /// \brief Callback invoked when a \#pragma warning(pop) directive is read. virtual void PragmaWarningPop(SourceLocation Loc) { } /// \brief Called by Preprocessor::HandleMacroExpandedIdentifier when a /// macro invocation is found. virtual void MacroExpands(const Token &MacroNameTok, const MacroDefinition &MD, SourceRange Range, const MacroArgs *Args) {} /// \brief Hook called whenever a macro definition is seen. virtual void MacroDefined(const Token &MacroNameTok, const MacroDirective *MD) { } /// \brief Hook called whenever a macro \#undef is seen. /// /// MD is released immediately following this callback. virtual void MacroUndefined(const Token &MacroNameTok, const MacroDefinition &MD) { } /// \brief Hook called whenever the 'defined' operator is seen. /// \param MD The MacroDirective if the name was a macro, null otherwise. virtual void Defined(const Token &MacroNameTok, const MacroDefinition &MD, SourceRange Range) { } /// \brief Hook called when a source range is skipped. /// \param Range The SourceRange that was skipped. The range begins at the /// \#if/\#else directive and ends after the \#endif/\#else directive. virtual void SourceRangeSkipped(SourceRange Range) { } enum ConditionValueKind { CVK_NotEvaluated, CVK_False, CVK_True }; /// \brief Hook called whenever an \#if is seen. /// \param Loc the source location of the directive. /// \param ConditionRange The SourceRange of the expression being tested. /// \param ConditionValue The evaluated value of the condition. /// // FIXME: better to pass in a list (or tree!) of Tokens. virtual void If(SourceLocation Loc, SourceRange ConditionRange, ConditionValueKind ConditionValue) { } /// \brief Hook called whenever an \#elif is seen. /// \param Loc the source location of the directive. /// \param ConditionRange The SourceRange of the expression being tested. /// \param ConditionValue The evaluated value of the condition. /// \param IfLoc the source location of the \#if/\#ifdef/\#ifndef directive. // FIXME: better to pass in a list (or tree!) of Tokens. virtual void Elif(SourceLocation Loc, SourceRange ConditionRange, ConditionValueKind ConditionValue, SourceLocation IfLoc) { } /// \brief Hook called whenever an \#ifdef is seen. /// \param Loc the source location of the directive. /// \param MacroNameTok Information on the token being tested. /// \param MD The MacroDefinition if the name was a macro, null otherwise. virtual void Ifdef(SourceLocation Loc, const Token &MacroNameTok, const MacroDefinition &MD) { } /// \brief Hook called whenever an \#ifndef is seen. /// \param Loc the source location of the directive. /// \param MacroNameTok Information on the token being tested. /// \param MD The MacroDefiniton if the name was a macro, null otherwise. virtual void Ifndef(SourceLocation Loc, const Token &MacroNameTok, const MacroDefinition &MD) { } /// \brief Hook called whenever an \#else is seen. /// \param Loc the source location of the directive. /// \param IfLoc the source location of the \#if/\#ifdef/\#ifndef directive. virtual void Else(SourceLocation Loc, SourceLocation IfLoc) { } /// \brief Hook called whenever an \#endif is seen. /// \param Loc the source location of the directive. /// \param IfLoc the source location of the \#if/\#ifdef/\#ifndef directive. virtual void Endif(SourceLocation Loc, SourceLocation IfLoc) { } }; /// \brief Simple wrapper class for chaining callbacks. class PPChainedCallbacks : public PPCallbacks { virtual void anchor(); std::unique_ptr<PPCallbacks> First, Second; public: PPChainedCallbacks(std::unique_ptr<PPCallbacks> _First, std::unique_ptr<PPCallbacks> _Second) : First(std::move(_First)), Second(std::move(_Second)) {} void FileChanged(SourceLocation Loc, FileChangeReason Reason, SrcMgr::CharacteristicKind FileType, FileID PrevFID) override { First->FileChanged(Loc, Reason, FileType, PrevFID); Second->FileChanged(Loc, Reason, FileType, PrevFID); } void FileSkipped(const FileEntry &SkippedFile, const Token &FilenameTok, SrcMgr::CharacteristicKind FileType) override { First->FileSkipped(SkippedFile, FilenameTok, FileType); Second->FileSkipped(SkippedFile, FilenameTok, FileType); } bool FileNotFound(StringRef FileName, SmallVectorImpl<char> &RecoveryPath) override { return First->FileNotFound(FileName, RecoveryPath) || Second->FileNotFound(FileName, RecoveryPath); } void InclusionDirective(SourceLocation HashLoc, const Token &IncludeTok, StringRef FileName, bool IsAngled, CharSourceRange FilenameRange, const FileEntry *File, StringRef SearchPath, StringRef RelativePath, const Module *Imported) override { First->InclusionDirective(HashLoc, IncludeTok, FileName, IsAngled, FilenameRange, File, SearchPath, RelativePath, Imported); Second->InclusionDirective(HashLoc, IncludeTok, FileName, IsAngled, FilenameRange, File, SearchPath, RelativePath, Imported); } void moduleImport(SourceLocation ImportLoc, ModuleIdPath Path, const Module *Imported) override { First->moduleImport(ImportLoc, Path, Imported); Second->moduleImport(ImportLoc, Path, Imported); } void EndOfMainFile() override { First->EndOfMainFile(); Second->EndOfMainFile(); } void Ident(SourceLocation Loc, StringRef str) override { First->Ident(Loc, str); Second->Ident(Loc, str); } void PragmaComment(SourceLocation Loc, const IdentifierInfo *Kind, StringRef Str) override { First->PragmaComment(Loc, Kind, Str); Second->PragmaComment(Loc, Kind, Str); } void PragmaDetectMismatch(SourceLocation Loc, StringRef Name, StringRef Value) override { First->PragmaDetectMismatch(Loc, Name, Value); Second->PragmaDetectMismatch(Loc, Name, Value); } void PragmaMessage(SourceLocation Loc, StringRef Namespace, PragmaMessageKind Kind, StringRef Str) override { First->PragmaMessage(Loc, Namespace, Kind, Str); Second->PragmaMessage(Loc, Namespace, Kind, Str); } void PragmaDiagnosticPush(SourceLocation Loc, StringRef Namespace) override { First->PragmaDiagnosticPush(Loc, Namespace); Second->PragmaDiagnosticPush(Loc, Namespace); } void PragmaDiagnosticPop(SourceLocation Loc, StringRef Namespace) override { First->PragmaDiagnosticPop(Loc, Namespace); Second->PragmaDiagnosticPop(Loc, Namespace); } void PragmaDiagnostic(SourceLocation Loc, StringRef Namespace, diag::Severity mapping, StringRef Str) override { First->PragmaDiagnostic(Loc, Namespace, mapping, Str); Second->PragmaDiagnostic(Loc, Namespace, mapping, Str); } void PragmaOpenCLExtension(SourceLocation NameLoc, const IdentifierInfo *Name, SourceLocation StateLoc, unsigned State) override { First->PragmaOpenCLExtension(NameLoc, Name, StateLoc, State); Second->PragmaOpenCLExtension(NameLoc, Name, StateLoc, State); } void PragmaWarning(SourceLocation Loc, StringRef WarningSpec, ArrayRef<int> Ids) override { First->PragmaWarning(Loc, WarningSpec, Ids); Second->PragmaWarning(Loc, WarningSpec, Ids); } void PragmaWarningPush(SourceLocation Loc, int Level) override { First->PragmaWarningPush(Loc, Level); Second->PragmaWarningPush(Loc, Level); } void PragmaWarningPop(SourceLocation Loc) override { First->PragmaWarningPop(Loc); Second->PragmaWarningPop(Loc); } void MacroExpands(const Token &MacroNameTok, const MacroDefinition &MD, SourceRange Range, const MacroArgs *Args) override { First->MacroExpands(MacroNameTok, MD, Range, Args); Second->MacroExpands(MacroNameTok, MD, Range, Args); } void MacroDefined(const Token &MacroNameTok, const MacroDirective *MD) override { First->MacroDefined(MacroNameTok, MD); Second->MacroDefined(MacroNameTok, MD); } void MacroUndefined(const Token &MacroNameTok, const MacroDefinition &MD) override { First->MacroUndefined(MacroNameTok, MD); Second->MacroUndefined(MacroNameTok, MD); } void Defined(const Token &MacroNameTok, const MacroDefinition &MD, SourceRange Range) override { First->Defined(MacroNameTok, MD, Range); Second->Defined(MacroNameTok, MD, Range); } void SourceRangeSkipped(SourceRange Range) override { First->SourceRangeSkipped(Range); Second->SourceRangeSkipped(Range); } /// \brief Hook called whenever an \#if is seen. void If(SourceLocation Loc, SourceRange ConditionRange, ConditionValueKind ConditionValue) override { First->If(Loc, ConditionRange, ConditionValue); Second->If(Loc, ConditionRange, ConditionValue); } /// \brief Hook called whenever an \#elif is seen. void Elif(SourceLocation Loc, SourceRange ConditionRange, ConditionValueKind ConditionValue, SourceLocation IfLoc) override { First->Elif(Loc, ConditionRange, ConditionValue, IfLoc); Second->Elif(Loc, ConditionRange, ConditionValue, IfLoc); } /// \brief Hook called whenever an \#ifdef is seen. void Ifdef(SourceLocation Loc, const Token &MacroNameTok, const MacroDefinition &MD) override { First->Ifdef(Loc, MacroNameTok, MD); Second->Ifdef(Loc, MacroNameTok, MD); } /// \brief Hook called whenever an \#ifndef is seen. void Ifndef(SourceLocation Loc, const Token &MacroNameTok, const MacroDefinition &MD) override { First->Ifndef(Loc, MacroNameTok, MD); Second->Ifndef(Loc, MacroNameTok, MD); } /// \brief Hook called whenever an \#else is seen. void Else(SourceLocation Loc, SourceLocation IfLoc) override { First->Else(Loc, IfLoc); Second->Else(Loc, IfLoc); } /// \brief Hook called whenever an \#endif is seen. void Endif(SourceLocation Loc, SourceLocation IfLoc) override { First->Endif(Loc, IfLoc); Second->Endif(Loc, IfLoc); } }; } // end namespace clang #endif
0
repos/DirectXShaderCompiler/tools/clang/include/clang
repos/DirectXShaderCompiler/tools/clang/include/clang/Lex/PPConditionalDirectiveRecord.h
//===--- PPConditionalDirectiveRecord.h - Preprocessing Directives-*- C++ -*-=// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines the PPConditionalDirectiveRecord class, which maintains // a record of conditional directive regions. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_LEX_PPCONDITIONALDIRECTIVERECORD_H #define LLVM_CLANG_LEX_PPCONDITIONALDIRECTIVERECORD_H #include "clang/Basic/SourceLocation.h" #include "clang/Lex/PPCallbacks.h" #include "llvm/ADT/SmallVector.h" #include <vector> namespace clang { /// \brief Records preprocessor conditional directive regions and allows /// querying in which region source locations belong to. class PPConditionalDirectiveRecord : public PPCallbacks { SourceManager &SourceMgr; SmallVector<SourceLocation, 6> CondDirectiveStack; class CondDirectiveLoc { SourceLocation Loc; SourceLocation RegionLoc; public: CondDirectiveLoc(SourceLocation Loc, SourceLocation RegionLoc) : Loc(Loc), RegionLoc(RegionLoc) {} SourceLocation getLoc() const { return Loc; } SourceLocation getRegionLoc() const { return RegionLoc; } class Comp { SourceManager &SM; public: explicit Comp(SourceManager &SM) : SM(SM) {} bool operator()(const CondDirectiveLoc &LHS, const CondDirectiveLoc &RHS) { return SM.isBeforeInTranslationUnit(LHS.getLoc(), RHS.getLoc()); } bool operator()(const CondDirectiveLoc &LHS, SourceLocation RHS) { return SM.isBeforeInTranslationUnit(LHS.getLoc(), RHS); } bool operator()(SourceLocation LHS, const CondDirectiveLoc &RHS) { return SM.isBeforeInTranslationUnit(LHS, RHS.getLoc()); } }; }; typedef std::vector<CondDirectiveLoc> CondDirectiveLocsTy; /// \brief The locations of conditional directives in source order. CondDirectiveLocsTy CondDirectiveLocs; void addCondDirectiveLoc(CondDirectiveLoc DirLoc); public: /// \brief Construct a new preprocessing record. explicit PPConditionalDirectiveRecord(SourceManager &SM); size_t getTotalMemory() const; SourceManager &getSourceManager() const { return SourceMgr; } /// \brief Returns true if the given range intersects with a conditional /// directive. if a \#if/\#endif block is fully contained within the range, /// this function will return false. bool rangeIntersectsConditionalDirective(SourceRange Range) const; /// \brief Returns true if the given locations are in different regions, /// separated by conditional directive blocks. bool areInDifferentConditionalDirectiveRegion(SourceLocation LHS, SourceLocation RHS) const { return findConditionalDirectiveRegionLoc(LHS) != findConditionalDirectiveRegionLoc(RHS); } SourceLocation findConditionalDirectiveRegionLoc(SourceLocation Loc) const; private: void If(SourceLocation Loc, SourceRange ConditionRange, ConditionValueKind ConditionValue) override; void Elif(SourceLocation Loc, SourceRange ConditionRange, ConditionValueKind ConditionValue, SourceLocation IfLoc) override; void Ifdef(SourceLocation Loc, const Token &MacroNameTok, const MacroDefinition &MD) override; void Ifndef(SourceLocation Loc, const Token &MacroNameTok, const MacroDefinition &MD) override; void Else(SourceLocation Loc, SourceLocation IfLoc) override; void Endif(SourceLocation Loc, SourceLocation IfLoc) override; }; } // end namespace clang #endif // LLVM_CLANG_LEX_PPCONDITIONALDIRECTIVERECORD_H
0
repos/DirectXShaderCompiler/tools/clang/include/clang
repos/DirectXShaderCompiler/tools/clang/include/clang/Lex/HeaderSearch.h
//===--- HeaderSearch.h - Resolve Header File Locations ---------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines the HeaderSearch interface. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_LEX_HEADERSEARCH_H #define LLVM_CLANG_LEX_HEADERSEARCH_H #include "clang/Lex/DirectoryLookup.h" #include "clang/Lex/ModuleMap.h" #include "llvm/ADT/ArrayRef.h" #include "llvm/ADT/IntrusiveRefCntPtr.h" #include "llvm/ADT/StringMap.h" #include "llvm/ADT/StringSet.h" #include "llvm/Support/Allocator.h" #include <memory> #include <vector> namespace clang { class DiagnosticsEngine; class ExternalPreprocessorSource; class FileEntry; class FileManager; class HeaderSearchOptions; class IdentifierInfo; class Preprocessor; /// \brief The preprocessor keeps track of this information for each /// file that is \#included. struct HeaderFileInfo { /// \brief True if this is a \#import'd or \#pragma once file. unsigned isImport : 1; /// \brief True if this is a \#pragma once file. unsigned isPragmaOnce : 1; /// DirInfo - Keep track of whether this is a system header, and if so, /// whether it is C++ clean or not. This can be set by the include paths or /// by \#pragma gcc system_header. This is an instance of /// SrcMgr::CharacteristicKind. unsigned DirInfo : 2; /// \brief Whether this header file info was supplied by an external source. unsigned External : 1; /// \brief Whether this header is part of a module. unsigned isModuleHeader : 1; /// \brief Whether this header is part of the module that we are building. unsigned isCompilingModuleHeader : 1; /// \brief Whether this header is part of the module that we are building. /// This is an instance of ModuleMap::ModuleHeaderRole. unsigned HeaderRole : 2; /// \brief Whether this structure is considered to already have been /// "resolved", meaning that it was loaded from the external source. unsigned Resolved : 1; /// \brief Whether this is a header inside a framework that is currently /// being built. /// /// When a framework is being built, the headers have not yet been placed /// into the appropriate framework subdirectories, and therefore are /// provided via a header map. This bit indicates when this is one of /// those framework headers. unsigned IndexHeaderMapHeader : 1; /// \brief Whether this file had been looked up as a header. unsigned IsValid : 1; /// \brief The number of times the file has been included already. unsigned short NumIncludes; /// \brief The ID number of the controlling macro. /// /// This ID number will be non-zero when there is a controlling /// macro whose IdentifierInfo may not yet have been loaded from /// external storage. unsigned ControllingMacroID; /// If this file has a \#ifndef XXX (or equivalent) guard that /// protects the entire contents of the file, this is the identifier /// for the macro that controls whether or not it has any effect. /// /// Note: Most clients should use getControllingMacro() to access /// the controlling macro of this header, since /// getControllingMacro() is able to load a controlling macro from /// external storage. const IdentifierInfo *ControllingMacro; /// \brief If this header came from a framework include, this is the name /// of the framework. StringRef Framework; HeaderFileInfo() : isImport(false), isPragmaOnce(false), DirInfo(SrcMgr::C_User), External(false), isModuleHeader(false), isCompilingModuleHeader(false), HeaderRole(ModuleMap::NormalHeader), Resolved(false), IndexHeaderMapHeader(false), IsValid(0), NumIncludes(0), ControllingMacroID(0), ControllingMacro(nullptr) {} /// \brief Retrieve the controlling macro for this header file, if /// any. const IdentifierInfo * getControllingMacro(ExternalPreprocessorSource *External); /// \brief Determine whether this is a non-default header file info, e.g., /// it corresponds to an actual header we've included or tried to include. bool isNonDefault() const { return isImport || isPragmaOnce || NumIncludes || ControllingMacro || ControllingMacroID; } /// \brief Get the HeaderRole properly typed. ModuleMap::ModuleHeaderRole getHeaderRole() const { return static_cast<ModuleMap::ModuleHeaderRole>(HeaderRole); } /// \brief Set the HeaderRole properly typed. void setHeaderRole(ModuleMap::ModuleHeaderRole Role) { HeaderRole = Role; } }; /// \brief An external source of header file information, which may supply /// information about header files already included. class ExternalHeaderFileInfoSource { public: virtual ~ExternalHeaderFileInfoSource(); /// \brief Retrieve the header file information for the given file entry. /// /// \returns Header file information for the given file entry, with the /// \c External bit set. If the file entry is not known, return a /// default-constructed \c HeaderFileInfo. virtual HeaderFileInfo GetHeaderFileInfo(const FileEntry *FE) = 0; }; /// \brief Encapsulates the information needed to find the file referenced /// by a \#include or \#include_next, (sub-)framework lookup, etc. class HeaderSearch { /// This structure is used to record entries in our framework cache. struct FrameworkCacheEntry { /// The directory entry which should be used for the cached framework. const DirectoryEntry *Directory; /// Whether this framework has been "user-specified" to be treated as if it /// were a system framework (even if it was found outside a system framework /// directory). bool IsUserSpecifiedSystemFramework; }; /// \brief Header-search options used to initialize this header search. IntrusiveRefCntPtr<HeaderSearchOptions> HSOpts; DiagnosticsEngine &Diags; FileManager &FileMgr; /// \#include search path information. Requests for \#include "x" search the /// directory of the \#including file first, then each directory in SearchDirs /// consecutively. Requests for <x> search the current dir first, then each /// directory in SearchDirs, starting at AngledDirIdx, consecutively. If /// NoCurDirSearch is true, then the check for the file in the current /// directory is suppressed. std::vector<DirectoryLookup> SearchDirs; unsigned AngledDirIdx; unsigned SystemDirIdx; bool NoCurDirSearch; /// \brief \#include prefixes for which the 'system header' property is /// overridden. /// /// For a \#include "x" or \#include \<x> directive, the last string in this /// list which is a prefix of 'x' determines whether the file is treated as /// a system header. std::vector<std::pair<std::string, bool> > SystemHeaderPrefixes; /// \brief The path to the module cache. std::string ModuleCachePath; /// \brief All of the preprocessor-specific data about files that are /// included, indexed by the FileEntry's UID. std::vector<HeaderFileInfo> FileInfo; /// Keeps track of each lookup performed by LookupFile. struct LookupFileCacheInfo { /// Starting index in SearchDirs that the cached search was performed from. /// If there is a hit and this value doesn't match the current query, the /// cache has to be ignored. unsigned StartIdx; /// The entry in SearchDirs that satisfied the query. unsigned HitIdx; /// This is non-null if the original filename was mapped to a framework /// include via a headermap. const char *MappedName; /// Default constructor -- Initialize all members with zero. LookupFileCacheInfo(): StartIdx(0), HitIdx(0), MappedName(nullptr) {} void reset(unsigned StartIdx) { this->StartIdx = StartIdx; this->MappedName = nullptr; } }; llvm::StringMap<LookupFileCacheInfo, llvm::BumpPtrAllocator> LookupFileCache; /// \brief Collection mapping a framework or subframework /// name like "Carbon" to the Carbon.framework directory. llvm::StringMap<FrameworkCacheEntry, llvm::BumpPtrAllocator> FrameworkMap; /// IncludeAliases - maps include file names (including the quotes or /// angle brackets) to other include file names. This is used to support the /// include_alias pragma for Microsoft compatibility. typedef llvm::StringMap<std::string, llvm::BumpPtrAllocator> IncludeAliasMap; std::unique_ptr<IncludeAliasMap> IncludeAliases; /// HeaderMaps - This is a mapping from FileEntry -> HeaderMap, uniquing /// headermaps. This vector owns the headermap. std::vector<std::pair<const FileEntry*, const HeaderMap*> > HeaderMaps; /// \brief The mapping between modules and headers. mutable ModuleMap ModMap; /// \brief Describes whether a given directory has a module map in it. llvm::DenseMap<const DirectoryEntry *, bool> DirectoryHasModuleMap; /// \brief Set of module map files we've already loaded, and a flag indicating /// whether they were valid or not. llvm::DenseMap<const FileEntry *, bool> LoadedModuleMaps; /// \brief Uniqued set of framework names, which is used to track which /// headers were included as framework headers. llvm::StringSet<llvm::BumpPtrAllocator> FrameworkNames; /// \brief Entity used to resolve the identifier IDs of controlling /// macros into IdentifierInfo pointers, and keep the identifire up to date, /// as needed. ExternalPreprocessorSource *ExternalLookup; /// \brief Entity used to look up stored header file information. ExternalHeaderFileInfoSource *ExternalSource; // Various statistics we track for performance analysis. unsigned NumIncluded; unsigned NumMultiIncludeFileOptzn; unsigned NumFrameworkLookups, NumSubFrameworkLookups; const LangOptions &LangOpts; // HeaderSearch doesn't support default or copy construction. HeaderSearch(const HeaderSearch&) = delete; void operator=(const HeaderSearch&) = delete; friend class DirectoryLookup; public: HeaderSearch(IntrusiveRefCntPtr<HeaderSearchOptions> HSOpts, SourceManager &SourceMgr, DiagnosticsEngine &Diags, const LangOptions &LangOpts, const TargetInfo *Target); ~HeaderSearch(); /// \brief Retrieve the header-search options with which this header search /// was initialized. HeaderSearchOptions &getHeaderSearchOpts() const { return *HSOpts; } FileManager &getFileMgr() const { return FileMgr; } /// \brief Interface for setting the file search paths. void SetSearchPaths(const std::vector<DirectoryLookup> &dirs, unsigned angledDirIdx, unsigned systemDirIdx, bool noCurDirSearch) { assert(angledDirIdx <= systemDirIdx && systemDirIdx <= dirs.size() && "Directory indicies are unordered"); SearchDirs = dirs; AngledDirIdx = angledDirIdx; SystemDirIdx = systemDirIdx; NoCurDirSearch = noCurDirSearch; //LookupFileCache.clear(); } /// \brief Add an additional search path. void AddSearchPath(const DirectoryLookup &dir, bool isAngled) { unsigned idx = isAngled ? SystemDirIdx : AngledDirIdx; SearchDirs.insert(SearchDirs.begin() + idx, dir); if (!isAngled) AngledDirIdx++; SystemDirIdx++; } /// \brief Set the list of system header prefixes. void SetSystemHeaderPrefixes(ArrayRef<std::pair<std::string, bool> > P) { SystemHeaderPrefixes.assign(P.begin(), P.end()); } /// \brief Checks whether the map exists or not. bool HasIncludeAliasMap() const { return (bool)IncludeAliases; } /// \brief Map the source include name to the dest include name. /// /// The Source should include the angle brackets or quotes, the dest /// should not. This allows for distinction between <> and "" headers. void AddIncludeAlias(StringRef Source, StringRef Dest) { if (!IncludeAliases) IncludeAliases.reset(new IncludeAliasMap); (*IncludeAliases)[Source] = Dest; } /// MapHeaderToIncludeAlias - Maps one header file name to a different header /// file name, for use with the include_alias pragma. Note that the source /// file name should include the angle brackets or quotes. Returns StringRef /// as null if the header cannot be mapped. StringRef MapHeaderToIncludeAlias(StringRef Source) { assert(IncludeAliases && "Trying to map headers when there's no map"); // Do any filename replacements before anything else IncludeAliasMap::const_iterator Iter = IncludeAliases->find(Source); if (Iter != IncludeAliases->end()) return Iter->second; return StringRef(); } /// \brief Set the path to the module cache. void setModuleCachePath(StringRef CachePath) { ModuleCachePath = CachePath; } /// \brief Retrieve the path to the module cache. StringRef getModuleCachePath() const { return ModuleCachePath; } /// \brief Consider modules when including files from this directory. void setDirectoryHasModuleMap(const DirectoryEntry* Dir) { DirectoryHasModuleMap[Dir] = true; } /// \brief Forget everything we know about headers so far. void ClearFileInfo() { FileInfo.clear(); } void SetExternalLookup(ExternalPreprocessorSource *EPS) { ExternalLookup = EPS; } ExternalPreprocessorSource *getExternalLookup() const { return ExternalLookup; } /// \brief Set the external source of header information. void SetExternalSource(ExternalHeaderFileInfoSource *ES) { ExternalSource = ES; } /// \brief Set the target information for the header search, if not /// already known. void setTarget(const TargetInfo &Target); /// \brief Given a "foo" or \<foo> reference, look up the indicated file, /// return null on failure. /// /// \returns If successful, this returns 'UsedDir', the DirectoryLookup member /// the file was found in, or null if not applicable. /// /// \param IncludeLoc Used for diagnostics if valid. /// /// \param isAngled indicates whether the file reference is a <> reference. /// /// \param CurDir If non-null, the file was found in the specified directory /// search location. This is used to implement \#include_next. /// /// \param Includers Indicates where the \#including file(s) are, in case /// relative searches are needed. In reverse order of inclusion. /// /// \param SearchPath If non-null, will be set to the search path relative /// to which the file was found. If the include path is absolute, SearchPath /// will be set to an empty string. /// /// \param RelativePath If non-null, will be set to the path relative to /// SearchPath at which the file was found. This only differs from the /// Filename for framework includes. /// /// \param SuggestedModule If non-null, and the file found is semantically /// part of a known module, this will be set to the module that should /// be imported instead of preprocessing/parsing the file found. const FileEntry *LookupFile( StringRef Filename, SourceLocation IncludeLoc, bool isAngled, const DirectoryLookup *FromDir, const DirectoryLookup *&CurDir, ArrayRef<std::pair<const FileEntry *, const DirectoryEntry *>> Includers, SmallVectorImpl<char> *SearchPath, SmallVectorImpl<char> *RelativePath, ModuleMap::KnownHeader *SuggestedModule, bool SkipCache = false); /// \brief Look up a subframework for the specified \#include file. /// /// For example, if \#include'ing <HIToolbox/HIToolbox.h> from /// within ".../Carbon.framework/Headers/Carbon.h", check to see if /// HIToolbox is a subframework within Carbon.framework. If so, return /// the FileEntry for the designated file, otherwise return null. const FileEntry *LookupSubframeworkHeader( StringRef Filename, const FileEntry *RelativeFileEnt, SmallVectorImpl<char> *SearchPath, SmallVectorImpl<char> *RelativePath, ModuleMap::KnownHeader *SuggestedModule); /// \brief Look up the specified framework name in our framework cache. /// \returns The DirectoryEntry it is in if we know, null otherwise. FrameworkCacheEntry &LookupFrameworkCache(StringRef FWName) { return FrameworkMap[FWName]; } /// \brief Mark the specified file as a target of of a \#include, /// \#include_next, or \#import directive. /// /// \return false if \#including the file will have no effect or true /// if we should include it. bool ShouldEnterIncludeFile(Preprocessor &PP, const FileEntry *File, bool isImport, Module *CorrespondingModule); /// \brief Return whether the specified file is a normal header, /// a system header, or a C++ friendly system header. SrcMgr::CharacteristicKind getFileDirFlavor(const FileEntry *File) { return (SrcMgr::CharacteristicKind)getFileInfo(File).DirInfo; } /// \brief Mark the specified file as a "once only" file, e.g. due to /// \#pragma once. void MarkFileIncludeOnce(const FileEntry *File) { HeaderFileInfo &FI = getFileInfo(File); FI.isImport = true; FI.isPragmaOnce = true; } /// \brief Mark the specified file as a system header, e.g. due to /// \#pragma GCC system_header. void MarkFileSystemHeader(const FileEntry *File) { getFileInfo(File).DirInfo = SrcMgr::C_System; } /// \brief Mark the specified file as part of a module. void MarkFileModuleHeader(const FileEntry *File, ModuleMap::ModuleHeaderRole Role, bool IsCompiledModuleHeader); /// \brief Increment the count for the number of times the specified /// FileEntry has been entered. void IncrementIncludeCount(const FileEntry *File) { ++getFileInfo(File).NumIncludes; } /// \brief Mark the specified file as having a controlling macro. /// /// This is used by the multiple-include optimization to eliminate /// no-op \#includes. void SetFileControllingMacro(const FileEntry *File, const IdentifierInfo *ControllingMacro) { getFileInfo(File).ControllingMacro = ControllingMacro; } /// \brief Return true if this is the first time encountering this header. bool FirstTimeLexingFile(const FileEntry *File) { return getFileInfo(File).NumIncludes == 1; } /// \brief Determine whether this file is intended to be safe from /// multiple inclusions, e.g., it has \#pragma once or a controlling /// macro. /// /// This routine does not consider the effect of \#import bool isFileMultipleIncludeGuarded(const FileEntry *File); /// CreateHeaderMap - This method returns a HeaderMap for the specified /// FileEntry, uniquing them through the 'HeaderMaps' datastructure. const HeaderMap *CreateHeaderMap(const FileEntry *FE); /// \brief Retrieve the name of the module file that should be used to /// load the given module. /// /// \param Module The module whose module file name will be returned. /// /// \returns The name of the module file that corresponds to this module, /// or an empty string if this module does not correspond to any module file. std::string getModuleFileName(Module *Module); /// \brief Retrieve the name of the module file that should be used to /// load a module with the given name. /// /// \param ModuleName The module whose module file name will be returned. /// /// \param ModuleMapPath A path that when combined with \c ModuleName /// uniquely identifies this module. See Module::ModuleMap. /// /// \returns The name of the module file that corresponds to this module, /// or an empty string if this module does not correspond to any module file. std::string getModuleFileName(StringRef ModuleName, StringRef ModuleMapPath); /// \brief Lookup a module Search for a module with the given name. /// /// \param ModuleName The name of the module we're looking for. /// /// \param AllowSearch Whether we are allowed to search in the various /// search directories to produce a module definition. If not, this lookup /// will only return an already-known module. /// /// \returns The module with the given name. Module *lookupModule(StringRef ModuleName, bool AllowSearch = true); /// \brief Try to find a module map file in the given directory, returning /// \c nullptr if none is found. const FileEntry *lookupModuleMapFile(const DirectoryEntry *Dir, bool IsFramework); void IncrementFrameworkLookupCount() { ++NumFrameworkLookups; } /// \brief Determine whether there is a module map that may map the header /// with the given file name to a (sub)module. /// Always returns false if modules are disabled. /// /// \param Filename The name of the file. /// /// \param Root The "root" directory, at which we should stop looking for /// module maps. /// /// \param IsSystem Whether the directories we're looking at are system /// header directories. bool hasModuleMap(StringRef Filename, const DirectoryEntry *Root, bool IsSystem); /// \brief Retrieve the module that corresponds to the given file, if any. /// /// \param File The header that we wish to map to a module. ModuleMap::KnownHeader findModuleForHeader(const FileEntry *File) const; /// \brief Read the contents of the given module map file. /// /// \param File The module map file. /// \param IsSystem Whether this file is in a system header directory. /// /// \returns true if an error occurred, false otherwise. bool loadModuleMapFile(const FileEntry *File, bool IsSystem); /// \brief Collect the set of all known, top-level modules. /// /// \param Modules Will be filled with the set of known, top-level modules. void collectAllModules(SmallVectorImpl<Module *> &Modules); /// \brief Load all known, top-level system modules. void loadTopLevelSystemModules(); private: /// \brief Retrieve a module with the given name, which may be part of the /// given framework. /// /// \param Name The name of the module to retrieve. /// /// \param Dir The framework directory (e.g., ModuleName.framework). /// /// \param IsSystem Whether the framework directory is part of the system /// frameworks. /// /// \returns The module, if found; otherwise, null. Module *loadFrameworkModule(StringRef Name, const DirectoryEntry *Dir, bool IsSystem); /// \brief Load all of the module maps within the immediate subdirectories /// of the given search directory. void loadSubdirectoryModuleMaps(DirectoryLookup &SearchDir); /// \brief Return the HeaderFileInfo structure for the specified FileEntry. const HeaderFileInfo &getFileInfo(const FileEntry *FE) const { return const_cast<HeaderSearch*>(this)->getFileInfo(FE); } public: /// \brief Retrieve the module map. ModuleMap &getModuleMap() { return ModMap; } unsigned header_file_size() const { return FileInfo.size(); } /// \brief Get a \c HeaderFileInfo structure for the specified \c FileEntry, /// if one exists. bool tryGetFileInfo(const FileEntry *FE, HeaderFileInfo &Result) const; // Used by external tools typedef std::vector<DirectoryLookup>::const_iterator search_dir_iterator; search_dir_iterator search_dir_begin() const { return SearchDirs.begin(); } search_dir_iterator search_dir_end() const { return SearchDirs.end(); } unsigned search_dir_size() const { return SearchDirs.size(); } search_dir_iterator quoted_dir_begin() const { return SearchDirs.begin(); } search_dir_iterator quoted_dir_end() const { return SearchDirs.begin() + AngledDirIdx; } search_dir_iterator angled_dir_begin() const { return SearchDirs.begin() + AngledDirIdx; } search_dir_iterator angled_dir_end() const { return SearchDirs.begin() + SystemDirIdx; } search_dir_iterator system_dir_begin() const { return SearchDirs.begin() + SystemDirIdx; } search_dir_iterator system_dir_end() const { return SearchDirs.end(); } /// \brief Retrieve a uniqued framework name. StringRef getUniqueFrameworkName(StringRef Framework); void PrintStats(); size_t getTotalMemory() const; static std::string NormalizeDashIncludePath(StringRef File, FileManager &FileMgr); private: /// \brief Describes what happened when we tried to load a module map file. enum LoadModuleMapResult { /// \brief The module map file had already been loaded. LMM_AlreadyLoaded, /// \brief The module map file was loaded by this invocation. LMM_NewlyLoaded, /// \brief There is was directory with the given name. LMM_NoDirectory, /// \brief There was either no module map file or the module map file was /// invalid. LMM_InvalidModuleMap }; LoadModuleMapResult loadModuleMapFileImpl(const FileEntry *File, bool IsSystem, const DirectoryEntry *Dir); /// \brief Try to load the module map file in the given directory. /// /// \param DirName The name of the directory where we will look for a module /// map file. /// \param IsSystem Whether this is a system header directory. /// \param IsFramework Whether this is a framework directory. /// /// \returns The result of attempting to load the module map file from the /// named directory. LoadModuleMapResult loadModuleMapFile(StringRef DirName, bool IsSystem, bool IsFramework); /// \brief Try to load the module map file in the given directory. /// /// \param Dir The directory where we will look for a module map file. /// \param IsSystem Whether this is a system header directory. /// \param IsFramework Whether this is a framework directory. /// /// \returns The result of attempting to load the module map file from the /// named directory. LoadModuleMapResult loadModuleMapFile(const DirectoryEntry *Dir, bool IsSystem, bool IsFramework); /// \brief Return the HeaderFileInfo structure for the specified FileEntry. HeaderFileInfo &getFileInfo(const FileEntry *FE); }; } // end namespace clang #endif
0
repos/DirectXShaderCompiler/tools/clang/include/clang
repos/DirectXShaderCompiler/tools/clang/include/clang/Lex/Preprocessor.h
//===--- Preprocessor.h - C Language Family Preprocessor --------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// /// /// \file /// \brief Defines the clang::Preprocessor interface. /// //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_LEX_PREPROCESSOR_H #define LLVM_CLANG_LEX_PREPROCESSOR_H #include "clang/Basic/Builtins.h" #include "clang/Basic/Diagnostic.h" #include "clang/Basic/IdentifierTable.h" #include "clang/Basic/SourceLocation.h" #include "clang/Lex/Lexer.h" #include "clang/Lex/MacroInfo.h" #include "clang/Lex/ModuleMap.h" #include "clang/Lex/PPCallbacks.h" #include "clang/Lex/PTHLexer.h" #include "clang/Lex/PTHManager.h" #include "clang/Lex/TokenLexer.h" #include "llvm/ADT/ArrayRef.h" #include "llvm/ADT/DenseMap.h" #include "llvm/ADT/IntrusiveRefCntPtr.h" #include "llvm/ADT/SmallPtrSet.h" #include "llvm/ADT/SmallVector.h" #include "llvm/ADT/TinyPtrVector.h" #include "llvm/Support/Allocator.h" #include <memory> #include <vector> #include "llvm/Support/OacrIgnoreCond.h" // HLSL Change - options change some lexical rules (tokens, identifier chars, others) namespace llvm { template<unsigned InternalLen> class SmallString; } namespace clang { class SourceManager; class ExternalPreprocessorSource; class FileManager; class FileEntry; class HeaderSearch; class PragmaNamespace; class PragmaHandler; class CommentHandler; class ScratchBuffer; class TargetInfo; class PPCallbacks; class CodeCompletionHandler; class DirectoryLookup; class PreprocessingRecord; class ModuleLoader; class PreprocessorOptions; /// \brief Stores token information for comparing actual tokens with /// predefined values. Only handles simple tokens and identifiers. class TokenValue { tok::TokenKind Kind; IdentifierInfo *II; public: TokenValue(tok::TokenKind Kind) : Kind(Kind), II(nullptr) { assert(Kind != tok::raw_identifier && "Raw identifiers are not supported."); assert(Kind != tok::identifier && "Identifiers should be created by TokenValue(IdentifierInfo *)"); assert(!tok::isLiteral(Kind) && "Literals are not supported."); assert(!tok::isAnnotation(Kind) && "Annotations are not supported."); } TokenValue(IdentifierInfo *II) : Kind(tok::identifier), II(II) {} bool operator==(const Token &Tok) const { return Tok.getKind() == Kind && (!II || II == Tok.getIdentifierInfo()); } }; /// \brief Context in which macro name is used. enum MacroUse { MU_Other = 0, // other than #define or #undef MU_Define = 1, // macro name specified in #define MU_Undef = 2 // macro name specified in #undef }; /// \brief Engages in a tight little dance with the lexer to efficiently /// preprocess tokens. /// /// Lexers know only about tokens within a single source file, and don't /// know anything about preprocessor-level issues like the \#include stack, /// token expansion, etc. class Preprocessor : public RefCountedBase<Preprocessor> { IntrusiveRefCntPtr<PreprocessorOptions> PPOpts; DiagnosticsEngine *Diags; LangOptions &LangOpts; const TargetInfo *Target; FileManager &FileMgr; SourceManager &SourceMgr; std::unique_ptr<ScratchBuffer> ScratchBuf; HeaderSearch &HeaderInfo; ModuleLoader &TheModuleLoader; /// \brief External source of macros. ExternalPreprocessorSource *ExternalSource; /// An optional PTHManager object used for getting tokens from /// a token cache rather than lexing the original source file. std::unique_ptr<PTHManager> PTH; /// A BumpPtrAllocator object used to quickly allocate and release /// objects internal to the Preprocessor. llvm::BumpPtrAllocator BP; /// Identifiers for builtin macros and other builtins. IdentifierInfo *Ident__LINE__, *Ident__FILE__; // __LINE__, __FILE__ IdentifierInfo *Ident__DATE__, *Ident__TIME__; // __DATE__, __TIME__ IdentifierInfo *Ident__INCLUDE_LEVEL__; // __INCLUDE_LEVEL__ IdentifierInfo *Ident__BASE_FILE__; // __BASE_FILE__ IdentifierInfo *Ident__TIMESTAMP__; // __TIMESTAMP__ IdentifierInfo *Ident__COUNTER__; // __COUNTER__ IdentifierInfo *Ident_Pragma, *Ident__pragma; // _Pragma, __pragma IdentifierInfo *Ident__identifier; // __identifier IdentifierInfo *Ident__VA_ARGS__; // __VA_ARGS__ IdentifierInfo *Ident__has_feature; // __has_feature IdentifierInfo *Ident__has_extension; // __has_extension IdentifierInfo *Ident__has_builtin; // __has_builtin IdentifierInfo *Ident__has_attribute; // __has_attribute IdentifierInfo *Ident__has_include; // __has_include IdentifierInfo *Ident__has_include_next; // __has_include_next IdentifierInfo *Ident__has_warning; // __has_warning IdentifierInfo *Ident__is_identifier; // __is_identifier IdentifierInfo *Ident__building_module; // __building_module IdentifierInfo *Ident__MODULE__; // __MODULE__ IdentifierInfo *Ident__has_cpp_attribute; // __has_cpp_attribute IdentifierInfo *Ident__has_declspec; // __has_declspec_attribute SourceLocation DATELoc, TIMELoc; unsigned CounterValue; // Next __COUNTER__ value. enum { /// \brief Maximum depth of \#includes. MaxAllowedIncludeStackDepth = 200 }; // State that is set before the preprocessor begins. bool KeepComments : 1; bool KeepMacroComments : 1; bool SuppressIncludeNotFoundError : 1; // State that changes while the preprocessor runs: bool InMacroArgs : 1; // True if parsing fn macro invocation args. /// Whether the preprocessor owns the header search object. bool OwnsHeaderSearch : 1; /// True if macro expansion is disabled. bool DisableMacroExpansion : 1; /// Temporarily disables DisableMacroExpansion (i.e. enables expansion) /// when parsing preprocessor directives. bool MacroExpansionInDirectivesOverride : 1; class ResetMacroExpansionHelper; /// \brief Whether we have already loaded macros from the external source. mutable bool ReadMacrosFromExternalSource : 1; /// \brief True if pragmas are enabled. bool PragmasEnabled : 1; /// \brief True if the current build action is a preprocessing action. bool PreprocessedOutput : 1; /// \brief True if we are currently preprocessing a #if or #elif directive bool ParsingIfOrElifDirective; /// \brief True if we are pre-expanding macro arguments. bool InMacroArgPreExpansion; /// \brief Mapping/lookup information for all identifiers in /// the program, including program keywords. mutable IdentifierTable Identifiers; /// \brief This table contains all the selectors in the program. /// /// Unlike IdentifierTable above, this table *isn't* populated by the /// preprocessor. It is declared/expanded here because its role/lifetime is /// conceptually similar to the IdentifierTable. In addition, the current /// control flow (in clang::ParseAST()), make it convenient to put here. /// /// FIXME: Make sure the lifetime of Identifiers/Selectors *isn't* tied to /// the lifetime of the preprocessor. SelectorTable Selectors; /// \brief Information about builtins. Builtin::Context BuiltinInfo; /// \brief Tracks all of the pragmas that the client registered /// with this preprocessor. std::unique_ptr<PragmaNamespace> PragmaHandlers; /// \brief Pragma handlers of the original source is stored here during the /// parsing of a model file. std::unique_ptr<PragmaNamespace> PragmaHandlersBackup; /// \brief Tracks all of the comment handlers that the client registered /// with this preprocessor. std::vector<CommentHandler *> CommentHandlers; /// \brief True if we want to ignore EOF token and continue later on (thus /// avoid tearing the Lexer and etc. down). bool IncrementalProcessing; /// The kind of translation unit we are processing. TranslationUnitKind TUKind; /// \brief The code-completion handler. CodeCompletionHandler *CodeComplete; /// \brief The file that we're performing code-completion for, if any. const FileEntry *CodeCompletionFile; /// \brief The offset in file for the code-completion point. unsigned CodeCompletionOffset; /// \brief The location for the code-completion point. This gets instantiated /// when the CodeCompletionFile gets \#include'ed for preprocessing. SourceLocation CodeCompletionLoc; /// \brief The start location for the file of the code-completion point. /// /// This gets instantiated when the CodeCompletionFile gets \#include'ed /// for preprocessing. SourceLocation CodeCompletionFileLoc; /// \brief The source location of the \c import contextual keyword we just /// lexed, if any. SourceLocation ModuleImportLoc; /// \brief The module import path that we're currently processing. SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> ModuleImportPath; /// \brief Whether the last token we lexed was an '@'. bool LastTokenWasAt; /// \brief Whether the module import expects an identifier next. Otherwise, /// it expects a '.' or ';'. bool ModuleImportExpectsIdentifier; /// \brief The source location of the currently-active /// \#pragma clang arc_cf_code_audited begin. SourceLocation PragmaARCCFCodeAuditedLoc; /// \brief The source location of the currently-active /// \#pragma clang assume_nonnull begin. SourceLocation PragmaAssumeNonNullLoc; /// \brief True if we hit the code-completion point. bool CodeCompletionReached; /// \brief The directory that the main file should be considered to occupy, /// if it does not correspond to a real file (as happens when building a /// module). const DirectoryEntry *MainFileDir; /// \brief The number of bytes that we will initially skip when entering the /// main file, along with a flag that indicates whether skipping this number /// of bytes will place the lexer at the start of a line. /// /// This is used when loading a precompiled preamble. std::pair<int, bool> SkipMainFilePreamble; /// \brief The current top of the stack that we're lexing from if /// not expanding a macro and we are lexing directly from source code. /// /// Only one of CurLexer, CurPTHLexer, or CurTokenLexer will be non-null. std::unique_ptr<Lexer> CurLexer; /// \brief The current top of stack that we're lexing from if /// not expanding from a macro and we are lexing from a PTH cache. /// /// Only one of CurLexer, CurPTHLexer, or CurTokenLexer will be non-null. std::unique_ptr<PTHLexer> CurPTHLexer; /// \brief The current top of the stack what we're lexing from /// if not expanding a macro. /// /// This is an alias for either CurLexer or CurPTHLexer. PreprocessorLexer *CurPPLexer; /// \brief Used to find the current FileEntry, if CurLexer is non-null /// and if applicable. /// /// This allows us to implement \#include_next and find directory-specific /// properties. const DirectoryLookup *CurDirLookup; /// \brief The current macro we are expanding, if we are expanding a macro. /// /// One of CurLexer and CurTokenLexer must be null. std::unique_ptr<TokenLexer> CurTokenLexer; /// \brief The kind of lexer we're currently working with. enum CurLexerKind { CLK_Lexer, CLK_PTHLexer, CLK_TokenLexer, CLK_CachingLexer, CLK_LexAfterModuleImport } CurLexerKind; /// \brief If the current lexer is for a submodule that is being built, this /// is that submodule. Module *CurSubmodule; /// \brief Keeps track of the stack of files currently /// \#included, and macros currently being expanded from, not counting /// CurLexer/CurTokenLexer. struct IncludeStackInfo { enum CurLexerKind CurLexerKind; Module *TheSubmodule; std::unique_ptr<Lexer> TheLexer; std::unique_ptr<PTHLexer> ThePTHLexer; PreprocessorLexer *ThePPLexer; std::unique_ptr<TokenLexer> TheTokenLexer; const DirectoryLookup *TheDirLookup; // The following constructors are completely useless copies of the default // versions, only needed to pacify MSVC. IncludeStackInfo(enum CurLexerKind CurLexerKind, Module *TheSubmodule, std::unique_ptr<Lexer> &&TheLexer, std::unique_ptr<PTHLexer> &&ThePTHLexer, PreprocessorLexer *ThePPLexer, std::unique_ptr<TokenLexer> &&TheTokenLexer, const DirectoryLookup *TheDirLookup) : CurLexerKind(std::move(CurLexerKind)), TheSubmodule(std::move(TheSubmodule)), TheLexer(std::move(TheLexer)), ThePTHLexer(std::move(ThePTHLexer)), ThePPLexer(std::move(ThePPLexer)), TheTokenLexer(std::move(TheTokenLexer)), TheDirLookup(std::move(TheDirLookup)) {} IncludeStackInfo(IncludeStackInfo &&RHS) : CurLexerKind(std::move(RHS.CurLexerKind)), TheSubmodule(std::move(RHS.TheSubmodule)), TheLexer(std::move(RHS.TheLexer)), ThePTHLexer(std::move(RHS.ThePTHLexer)), ThePPLexer(std::move(RHS.ThePPLexer)), TheTokenLexer(std::move(RHS.TheTokenLexer)), TheDirLookup(std::move(RHS.TheDirLookup)) {} }; std::vector<IncludeStackInfo> IncludeMacroStack; /// \brief Actions invoked when some preprocessor activity is /// encountered (e.g. a file is \#included, etc). std::unique_ptr<PPCallbacks> Callbacks; struct MacroExpandsInfo { Token Tok; MacroDefinition MD; SourceRange Range; MacroExpandsInfo(Token Tok, MacroDefinition MD, SourceRange Range) : Tok(Tok), MD(MD), Range(Range) { } }; SmallVector<MacroExpandsInfo, 2> DelayedMacroExpandsCallbacks; /// Information about a name that has been used to define a module macro. struct ModuleMacroInfo { ModuleMacroInfo(MacroDirective *MD) : MD(MD), ActiveModuleMacrosGeneration(0), IsAmbiguous(false) {} /// The most recent macro directive for this identifier. MacroDirective *MD; /// The active module macros for this identifier. llvm::TinyPtrVector<ModuleMacro*> ActiveModuleMacros; /// The generation number at which we last updated ActiveModuleMacros. /// \see Preprocessor::VisibleModules. unsigned ActiveModuleMacrosGeneration; /// Whether this macro name is ambiguous. bool IsAmbiguous; /// The module macros that are overridden by this macro. llvm::TinyPtrVector<ModuleMacro*> OverriddenMacros; }; /// The state of a macro for an identifier. class MacroState { mutable llvm::PointerUnion<MacroDirective *, ModuleMacroInfo *> State; ModuleMacroInfo *getModuleInfo(Preprocessor &PP, const IdentifierInfo *II) const { // FIXME: Find a spare bit on IdentifierInfo and store a // HasModuleMacros flag. if (!II->hasMacroDefinition() || (!PP.getLangOpts().Modules && !PP.getLangOpts().ModulesLocalVisibility) || !PP.CurSubmoduleState->VisibleModules.getGeneration()) return nullptr; auto *Info = State.dyn_cast<ModuleMacroInfo*>(); if (!Info) { Info = new (PP.getPreprocessorAllocator()) ModuleMacroInfo(State.get<MacroDirective *>()); State = Info; } if (PP.CurSubmoduleState->VisibleModules.getGeneration() != Info->ActiveModuleMacrosGeneration) PP.updateModuleMacroInfo(II, *Info); return Info; } public: MacroState() : MacroState(nullptr) {} MacroState(MacroDirective *MD) : State(MD) {} MacroState(MacroState &&O) LLVM_NOEXCEPT : State(O.State) { O.State = (MacroDirective *)nullptr; } MacroState &operator=(MacroState &&O) LLVM_NOEXCEPT { auto S = O.State; O.State = (MacroDirective *)nullptr; State = S; return *this; } ~MacroState() { if (auto *Info = State.dyn_cast<ModuleMacroInfo*>()) Info->~ModuleMacroInfo(); } MacroDirective *getLatest() const { if (auto *Info = State.dyn_cast<ModuleMacroInfo*>()) return Info->MD; return State.get<MacroDirective*>(); } void setLatest(MacroDirective *MD) { if (auto *Info = State.dyn_cast<ModuleMacroInfo*>()) Info->MD = MD; else State = MD; } bool isAmbiguous(Preprocessor &PP, const IdentifierInfo *II) const { auto *Info = getModuleInfo(PP, II); return Info ? Info->IsAmbiguous : false; } ArrayRef<ModuleMacro *> getActiveModuleMacros(Preprocessor &PP, const IdentifierInfo *II) const { if (auto *Info = getModuleInfo(PP, II)) return Info->ActiveModuleMacros; return None; } MacroDirective::DefInfo findDirectiveAtLoc(SourceLocation Loc, SourceManager &SourceMgr) const { // FIXME: Incorporate module macros into the result of this. if (auto *Latest = getLatest()) return Latest->findDirectiveAtLoc(Loc, SourceMgr); return MacroDirective::DefInfo(); } void overrideActiveModuleMacros(Preprocessor &PP, IdentifierInfo *II) { if (auto *Info = getModuleInfo(PP, II)) { Info->OverriddenMacros.insert(Info->OverriddenMacros.end(), Info->ActiveModuleMacros.begin(), Info->ActiveModuleMacros.end()); Info->ActiveModuleMacros.clear(); Info->IsAmbiguous = false; } } ArrayRef<ModuleMacro*> getOverriddenMacros() const { if (auto *Info = State.dyn_cast<ModuleMacroInfo*>()) return Info->OverriddenMacros; return None; } void setOverriddenMacros(Preprocessor &PP, ArrayRef<ModuleMacro *> Overrides) { auto *Info = State.dyn_cast<ModuleMacroInfo*>(); if (!Info) { if (Overrides.empty()) return; Info = new (PP.getPreprocessorAllocator()) ModuleMacroInfo(State.get<MacroDirective *>()); State = Info; } Info->OverriddenMacros.clear(); Info->OverriddenMacros.insert(Info->OverriddenMacros.end(), Overrides.begin(), Overrides.end()); Info->ActiveModuleMacrosGeneration = 0; } }; /// For each IdentifierInfo that was associated with a macro, we /// keep a mapping to the history of all macro definitions and #undefs in /// the reverse order (the latest one is in the head of the list). /// /// This mapping lives within the \p CurSubmoduleState. typedef llvm::DenseMap<const IdentifierInfo *, MacroState> MacroMap; friend class ASTReader; struct SubmoduleState; /// \brief Information about a submodule that we're currently building. struct BuildingSubmoduleInfo { BuildingSubmoduleInfo(Module *M, SourceLocation ImportLoc, SubmoduleState *OuterSubmoduleState) : M(M), ImportLoc(ImportLoc), OuterSubmoduleState(OuterSubmoduleState) { } /// The module that we are building. Module *M; /// The location at which the module was included. SourceLocation ImportLoc; /// The previous SubmoduleState. SubmoduleState *OuterSubmoduleState; }; SmallVector<BuildingSubmoduleInfo, 8> BuildingSubmoduleStack; /// \brief Information about a submodule's preprocessor state. struct SubmoduleState { /// The macros for the submodule. MacroMap Macros; /// The set of modules that are visible within the submodule. VisibleModuleSet VisibleModules; // FIXME: CounterValue? // FIXME: PragmaPushMacroInfo? }; std::map<Module*, SubmoduleState> Submodules; /// The preprocessor state for preprocessing outside of any submodule. SubmoduleState NullSubmoduleState; /// The current submodule state. Will be \p NullSubmoduleState if we're not /// in a submodule. SubmoduleState *CurSubmoduleState; /// The set of known macros exported from modules. llvm::FoldingSet<ModuleMacro> ModuleMacros; /// The list of module macros, for each identifier, that are not overridden by /// any other module macro. llvm::DenseMap<const IdentifierInfo *, llvm::TinyPtrVector<ModuleMacro*>> LeafModuleMacros; /// \brief Macros that we want to warn because they are not used at the end /// of the translation unit. /// /// We store just their SourceLocations instead of /// something like MacroInfo*. The benefit of this is that when we are /// deserializing from PCH, we don't need to deserialize identifier & macros /// just so that we can report that they are unused, we just warn using /// the SourceLocations of this set (that will be filled by the ASTReader). /// We are using SmallPtrSet instead of a vector for faster removal. typedef llvm::SmallPtrSet<SourceLocation, 32> WarnUnusedMacroLocsTy; WarnUnusedMacroLocsTy WarnUnusedMacroLocs; /// \brief A "freelist" of MacroArg objects that can be /// reused for quick allocation. MacroArgs *MacroArgCache; friend class MacroArgs; /// For each IdentifierInfo used in a \#pragma push_macro directive, /// we keep a MacroInfo stack used to restore the previous macro value. llvm::DenseMap<IdentifierInfo*, std::vector<MacroInfo*> > PragmaPushMacroInfo; // Various statistics we track for performance analysis. unsigned NumDirectives, NumDefined, NumUndefined, NumPragma; unsigned NumIf, NumElse, NumEndif; unsigned NumEnteredSourceFiles, MaxIncludeStackDepth; unsigned NumMacroExpanded, NumFnMacroExpanded, NumBuiltinMacroExpanded; unsigned NumFastMacroExpanded, NumTokenPaste, NumFastTokenPaste; unsigned NumSkipped; /// \brief The predefined macros that preprocessor should use from the /// command line etc. std::string Predefines; /// \brief The file ID for the preprocessor predefines. FileID PredefinesFileID; /// \{ /// \brief Cache of macro expanders to reduce malloc traffic. enum { TokenLexerCacheSize = 8 }; unsigned NumCachedTokenLexers; std::unique_ptr<TokenLexer> TokenLexerCache[TokenLexerCacheSize]; /// \} /// \brief Keeps macro expanded tokens for TokenLexers. // /// Works like a stack; a TokenLexer adds the macro expanded tokens that is /// going to lex in the cache and when it finishes the tokens are removed /// from the end of the cache. SmallVector<Token, 16> MacroExpandedTokens; std::vector<std::pair<TokenLexer *, size_t> > MacroExpandingLexersStack; /// \brief A record of the macro definitions and expansions that /// occurred during preprocessing. /// /// This is an optional side structure that can be enabled with /// \c createPreprocessingRecord() prior to preprocessing. PreprocessingRecord *Record; /// Cached tokens state. typedef SmallVector<Token, 1> CachedTokensTy; /// \brief Cached tokens are stored here when we do backtracking or /// lookahead. They are "lexed" by the CachingLex() method. CachedTokensTy CachedTokens; /// \brief The position of the cached token that CachingLex() should /// "lex" next. /// /// If it points beyond the CachedTokens vector, it means that a normal /// Lex() should be invoked. CachedTokensTy::size_type CachedLexPos; /// \brief Stack of backtrack positions, allowing nested backtracks. /// /// The EnableBacktrackAtThisPos() method pushes a position to /// indicate where CachedLexPos should be set when the BackTrack() method is /// invoked (at which point the last position is popped). std::vector<CachedTokensTy::size_type> BacktrackPositions; struct MacroInfoChain { MacroInfo MI; MacroInfoChain *Next; }; /// MacroInfos are managed as a chain for easy disposal. This is the head /// of that list. MacroInfoChain *MIChainHead; struct DeserializedMacroInfoChain { MacroInfo MI; unsigned OwningModuleID; // MUST be immediately after the MacroInfo object // so it can be accessed by MacroInfo::getOwningModuleID(). DeserializedMacroInfoChain *Next; }; DeserializedMacroInfoChain *DeserialMIChainHead; public: Preprocessor(IntrusiveRefCntPtr<PreprocessorOptions> PPOpts, DiagnosticsEngine &diags, LangOptions &opts, SourceManager &SM, HeaderSearch &Headers, ModuleLoader &TheModuleLoader, IdentifierInfoLookup *IILookup = nullptr, bool OwnsHeaderSearch = false, TranslationUnitKind TUKind = TU_Complete); ~Preprocessor(); /// \brief Initialize the preprocessor using information about the target. /// /// \param Target is owned by the caller and must remain valid for the /// lifetime of the preprocessor. void Initialize(const TargetInfo &Target); /// \brief Initialize the preprocessor to parse a model file /// /// To parse model files the preprocessor of the original source is reused to /// preserver the identifier table. However to avoid some duplicate /// information in the preprocessor some cleanup is needed before it is used /// to parse model files. This method does that cleanup. void InitializeForModelFile(); /// \brief Cleanup after model file parsing void FinalizeForModelFile(); /// \brief Retrieve the preprocessor options used to initialize this /// preprocessor. PreprocessorOptions &getPreprocessorOpts() const { return *PPOpts; } DiagnosticsEngine &getDiagnostics() const { return *Diags; } void setDiagnostics(DiagnosticsEngine &D) { Diags = &D; } const LangOptions &getLangOpts() const { return LangOpts; } const TargetInfo &getTargetInfo() const { return *Target; } FileManager &getFileManager() const { return FileMgr; } SourceManager &getSourceManager() const { return SourceMgr; } HeaderSearch &getHeaderSearchInfo() const { return HeaderInfo; } IdentifierTable &getIdentifierTable() { return Identifiers; } const IdentifierTable &getIdentifierTable() const { return Identifiers; } SelectorTable &getSelectorTable() { return Selectors; } Builtin::Context &getBuiltinInfo() { return BuiltinInfo; } llvm::BumpPtrAllocator &getPreprocessorAllocator() { return BP; } void setPTHManager(PTHManager* pm); PTHManager *getPTHManager() { return PTH.get(); } void setExternalSource(ExternalPreprocessorSource *Source) { ExternalSource = Source; } ExternalPreprocessorSource *getExternalSource() const { return ExternalSource; } /// \brief Retrieve the module loader associated with this preprocessor. ModuleLoader &getModuleLoader() const { return TheModuleLoader; } bool hadModuleLoaderFatalFailure() const { return TheModuleLoader.HadFatalFailure; } /// \brief True if we are currently preprocessing a #if or #elif directive bool isParsingIfOrElifDirective() const { return ParsingIfOrElifDirective; } /// \brief Control whether the preprocessor retains comments in output. void SetCommentRetentionState(bool KeepComments, bool KeepMacroComments) { this->KeepComments = KeepComments | KeepMacroComments; this->KeepMacroComments = KeepMacroComments; } bool getCommentRetentionState() const { return KeepComments; } void setPragmasEnabled(bool Enabled) { PragmasEnabled = Enabled; } bool getPragmasEnabled() const { return PragmasEnabled; } void SetSuppressIncludeNotFoundError(bool Suppress) { SuppressIncludeNotFoundError = Suppress; } bool GetSuppressIncludeNotFoundError() { return SuppressIncludeNotFoundError; } /// Sets whether the preprocessor is responsible for producing output or if /// it is producing tokens to be consumed by Parse and Sema. void setPreprocessedOutput(bool IsPreprocessedOutput) { PreprocessedOutput = IsPreprocessedOutput; } /// Returns true if the preprocessor is responsible for generating output, /// false if it is producing tokens to be consumed by Parse and Sema. bool isPreprocessedOutput() const { return PreprocessedOutput; } /// \brief Return true if we are lexing directly from the specified lexer. bool isCurrentLexer(const PreprocessorLexer *L) const { return CurPPLexer == L; } /// \brief Return the current lexer being lexed from. /// /// Note that this ignores any potentially active macro expansions and _Pragma /// expansions going on at the time. PreprocessorLexer *getCurrentLexer() const { return CurPPLexer; } /// \brief Return the current file lexer being lexed from. /// /// Note that this ignores any potentially active macro expansions and _Pragma /// expansions going on at the time. PreprocessorLexer *getCurrentFileLexer() const; /// \brief Return the submodule owning the file being lexed. Module *getCurrentSubmodule() const { return CurSubmodule; } /// \brief Returns the FileID for the preprocessor predefines. FileID getPredefinesFileID() const { return PredefinesFileID; } /// \{ /// \brief Accessors for preprocessor callbacks. /// /// Note that this class takes ownership of any PPCallbacks object given to /// it. PPCallbacks *getPPCallbacks() const { return Callbacks.get(); } void addPPCallbacks(std::unique_ptr<PPCallbacks> C) { if (Callbacks) C = llvm::make_unique<PPChainedCallbacks>(std::move(C), std::move(Callbacks)); Callbacks = std::move(C); } /// \} bool isMacroDefined(StringRef Id) { return isMacroDefined(&Identifiers.get(Id)); } bool isMacroDefined(const IdentifierInfo *II) { return II->hasMacroDefinition() && (!getLangOpts().Modules || (bool)getMacroDefinition(II)); } /// \brief Determine whether II is defined as a macro within the module M, /// if that is a module that we've already preprocessed. Does not check for /// macros imported into M. bool isMacroDefinedInLocalModule(const IdentifierInfo *II, Module *M) { if (!II->hasMacroDefinition()) return false; auto I = Submodules.find(M); if (I == Submodules.end()) return false; auto J = I->second.Macros.find(II); if (J == I->second.Macros.end()) return false; auto *MD = J->second.getLatest(); return MD && MD->isDefined(); } MacroDefinition getMacroDefinition(const IdentifierInfo *II) { if (!II->hasMacroDefinition()) return MacroDefinition(); MacroState &S = CurSubmoduleState->Macros[II]; auto *MD = S.getLatest(); while (MD && isa<VisibilityMacroDirective>(MD)) MD = MD->getPrevious(); return MacroDefinition(dyn_cast_or_null<DefMacroDirective>(MD), S.getActiveModuleMacros(*this, II), S.isAmbiguous(*this, II)); } MacroDefinition getMacroDefinitionAtLoc(const IdentifierInfo *II, SourceLocation Loc) { if (!II->hadMacroDefinition()) return MacroDefinition(); MacroState &S = CurSubmoduleState->Macros[II]; MacroDirective::DefInfo DI; if (auto *MD = S.getLatest()) DI = MD->findDirectiveAtLoc(Loc, getSourceManager()); // FIXME: Compute the set of active module macros at the specified location. return MacroDefinition(DI.getDirective(), S.getActiveModuleMacros(*this, II), S.isAmbiguous(*this, II)); } /// \brief Given an identifier, return its latest non-imported MacroDirective /// if it is \#define'd and not \#undef'd, or null if it isn't \#define'd. MacroDirective *getLocalMacroDirective(const IdentifierInfo *II) const { if (!II->hasMacroDefinition()) return nullptr; auto *MD = getLocalMacroDirectiveHistory(II); if (!MD || MD->getDefinition().isUndefined()) return nullptr; return MD; } const MacroInfo *getMacroInfo(const IdentifierInfo *II) const { return const_cast<Preprocessor*>(this)->getMacroInfo(II); } MacroInfo *getMacroInfo(const IdentifierInfo *II) { if (!II->hasMacroDefinition()) return nullptr; if (auto MD = getMacroDefinition(II)) return MD.getMacroInfo(); return nullptr; } /// \brief Given an identifier, return the latest non-imported macro /// directive for that identifier. /// /// One can iterate over all previous macro directives from the most recent /// one. MacroDirective *getLocalMacroDirectiveHistory(const IdentifierInfo *II) const; /// \brief Add a directive to the macro directive history for this identifier. void appendMacroDirective(IdentifierInfo *II, MacroDirective *MD); DefMacroDirective *appendDefMacroDirective(IdentifierInfo *II, MacroInfo *MI, SourceLocation Loc) { DefMacroDirective *MD = AllocateDefMacroDirective(MI, Loc); appendMacroDirective(II, MD); return MD; } DefMacroDirective *appendDefMacroDirective(IdentifierInfo *II, MacroInfo *MI) { return appendDefMacroDirective(II, MI, MI->getDefinitionLoc()); } /// \brief Set a MacroDirective that was loaded from a PCH file. void setLoadedMacroDirective(IdentifierInfo *II, MacroDirective *MD); /// \brief Register an exported macro for a module and identifier. ModuleMacro *addModuleMacro(Module *Mod, IdentifierInfo *II, MacroInfo *Macro, ArrayRef<ModuleMacro *> Overrides, bool &IsNew); ModuleMacro *getModuleMacro(Module *Mod, IdentifierInfo *II); /// \brief Get the list of leaf (non-overridden) module macros for a name. ArrayRef<ModuleMacro*> getLeafModuleMacros(const IdentifierInfo *II) const { auto I = LeafModuleMacros.find(II); if (I != LeafModuleMacros.end()) return I->second; return None; } /// \{ /// Iterators for the macro history table. Currently defined macros have /// IdentifierInfo::hasMacroDefinition() set and an empty /// MacroInfo::getUndefLoc() at the head of the list. typedef MacroMap::const_iterator macro_iterator; macro_iterator macro_begin(bool IncludeExternalMacros = true) const; macro_iterator macro_end(bool IncludeExternalMacros = true) const; llvm::iterator_range<macro_iterator> macros(bool IncludeExternalMacros = true) const { return llvm::make_range(macro_begin(IncludeExternalMacros), macro_end(IncludeExternalMacros)); } /// \} /// \brief Return the name of the macro defined before \p Loc that has /// spelling \p Tokens. If there are multiple macros with same spelling, /// return the last one defined. StringRef getLastMacroWithSpelling(SourceLocation Loc, ArrayRef<TokenValue> Tokens) const; const std::string &getPredefines() const { return Predefines; } /// \brief Set the predefines for this Preprocessor. /// /// These predefines are automatically injected when parsing the main file. void setPredefines(const char *P) { Predefines = P; } void setPredefines(StringRef P) { Predefines = P; } /// Return information about the specified preprocessor /// identifier token. IdentifierInfo *getIdentifierInfo(StringRef Name) const { return &Identifiers.get(Name); } /// \brief Add the specified pragma handler to this preprocessor. /// /// If \p Namespace is non-null, then it is a token required to exist on the /// pragma line before the pragma string starts, e.g. "STDC" or "GCC". void AddPragmaHandler(StringRef Namespace, PragmaHandler *Handler); void AddPragmaHandler(PragmaHandler *Handler) { AddPragmaHandler(StringRef(), Handler); } /// \brief Remove the specific pragma handler from this preprocessor. /// /// If \p Namespace is non-null, then it should be the namespace that /// \p Handler was added to. It is an error to remove a handler that /// has not been registered. void RemovePragmaHandler(StringRef Namespace, PragmaHandler *Handler); void RemovePragmaHandler(PragmaHandler *Handler) { RemovePragmaHandler(StringRef(), Handler); } /// Install empty handlers for all pragmas (making them ignored). void IgnorePragmas(); /// \brief Add the specified comment handler to the preprocessor. void addCommentHandler(CommentHandler *Handler); /// \brief Remove the specified comment handler. /// /// It is an error to remove a handler that has not been registered. void removeCommentHandler(CommentHandler *Handler); /// \brief Set the code completion handler to the given object. void setCodeCompletionHandler(CodeCompletionHandler &Handler) { CodeComplete = &Handler; } /// \brief Retrieve the current code-completion handler. CodeCompletionHandler *getCodeCompletionHandler() const { return CodeComplete; } /// \brief Clear out the code completion handler. void clearCodeCompletionHandler() { CodeComplete = nullptr; } /// \brief Hook used by the lexer to invoke the "natural language" code /// completion point. void CodeCompleteNaturalLanguage(); /// \brief Retrieve the preprocessing record, or NULL if there is no /// preprocessing record. PreprocessingRecord *getPreprocessingRecord() const { return Record; } /// \brief Create a new preprocessing record, which will keep track of /// all macro expansions, macro definitions, etc. void createPreprocessingRecord(); /// \brief Enter the specified FileID as the main source file, /// which implicitly adds the builtin defines etc. void EnterMainSourceFile(); /// \brief Inform the preprocessor callbacks that processing is complete. void EndSourceFile(); /// \brief Add a source file to the top of the include stack and /// start lexing tokens from it instead of the current buffer. /// /// Emits a diagnostic, doesn't enter the file, and returns true on error. bool EnterSourceFile(FileID CurFileID, const DirectoryLookup *Dir, SourceLocation Loc); /// \brief Add a Macro to the top of the include stack and start lexing /// tokens from it instead of the current buffer. /// /// \param Args specifies the tokens input to a function-like macro. /// \param ILEnd specifies the location of the ')' for a function-like macro /// or the identifier for an object-like macro. void EnterMacro(Token &Identifier, SourceLocation ILEnd, MacroInfo *Macro, MacroArgs *Args); /// \brief Add a "macro" context to the top of the include stack, /// which will cause the lexer to start returning the specified tokens. /// /// If \p DisableMacroExpansion is true, tokens lexed from the token stream /// will not be subject to further macro expansion. Otherwise, these tokens /// will be re-macro-expanded when/if expansion is enabled. /// /// If \p OwnsTokens is false, this method assumes that the specified stream /// of tokens has a permanent owner somewhere, so they do not need to be /// copied. If it is true, it assumes the array of tokens is allocated with /// \c new[] and must be freed. void EnterTokenStream(const Token *Toks, unsigned NumToks, bool DisableMacroExpansion, bool OwnsTokens); /// \brief Pop the current lexer/macro exp off the top of the lexer stack. /// /// This should only be used in situations where the current state of the /// top-of-stack lexer is known. void RemoveTopOfLexerStack(); /// From the point that this method is called, and until /// CommitBacktrackedTokens() or Backtrack() is called, the Preprocessor /// keeps track of the lexed tokens so that a subsequent Backtrack() call will /// make the Preprocessor re-lex the same tokens. /// /// Nested backtracks are allowed, meaning that EnableBacktrackAtThisPos can /// be called multiple times and CommitBacktrackedTokens/Backtrack calls will /// be combined with the EnableBacktrackAtThisPos calls in reverse order. /// /// NOTE: *DO NOT* forget to call either CommitBacktrackedTokens or Backtrack /// at some point after EnableBacktrackAtThisPos. If you don't, caching of /// tokens will continue indefinitely. /// void EnableBacktrackAtThisPos(); /// \brief Disable the last EnableBacktrackAtThisPos call. void CommitBacktrackedTokens(); /// \brief Make Preprocessor re-lex the tokens that were lexed since /// EnableBacktrackAtThisPos() was previously called. void Backtrack(); /// \brief True if EnableBacktrackAtThisPos() was called and /// caching of tokens is on. bool isBacktrackEnabled() const { return !BacktrackPositions.empty(); } /// \brief Lex the next token for this preprocessor. void Lex(Token &Result); void LexAfterModuleImport(Token &Result); void makeModuleVisible(Module *M, SourceLocation Loc); SourceLocation getModuleImportLoc(Module *M) const { return CurSubmoduleState->VisibleModules.getImportLoc(M); } /// \brief Lex a string literal, which may be the concatenation of multiple /// string literals and may even come from macro expansion. /// \returns true on success, false if a error diagnostic has been generated. bool LexStringLiteral(Token &Result, std::string &String, const char *DiagnosticTag, bool AllowMacroExpansion) { if (AllowMacroExpansion) Lex(Result); else LexUnexpandedToken(Result); return FinishLexStringLiteral(Result, String, DiagnosticTag, AllowMacroExpansion); } /// \brief Complete the lexing of a string literal where the first token has /// already been lexed (see LexStringLiteral). bool FinishLexStringLiteral(Token &Result, std::string &String, const char *DiagnosticTag, bool AllowMacroExpansion); /// \brief Lex a token. If it's a comment, keep lexing until we get /// something not a comment. /// /// This is useful in -E -C mode where comments would foul up preprocessor /// directive handling. void LexNonComment(Token &Result) { do Lex(Result); while (Result.getKind() == tok::comment); } /// \brief Just like Lex, but disables macro expansion of identifier tokens. void LexUnexpandedToken(Token &Result) { // Disable macro expansion. bool OldVal = DisableMacroExpansion; DisableMacroExpansion = true; // Lex the token. Lex(Result); // Reenable it. DisableMacroExpansion = OldVal; } /// \brief Like LexNonComment, but this disables macro expansion of /// identifier tokens. void LexUnexpandedNonComment(Token &Result) { do LexUnexpandedToken(Result); while (Result.getKind() == tok::comment); } /// \brief Parses a simple integer literal to get its numeric value. Floating /// point literals and user defined literals are rejected. Used primarily to /// handle pragmas that accept integer arguments. bool parseSimpleIntegerLiteral(Token &Tok, uint64_t &Value); /// Disables macro expansion everywhere except for preprocessor directives. void SetMacroExpansionOnlyInDirectives() { DisableMacroExpansion = true; MacroExpansionInDirectivesOverride = true; } /// \brief Peeks ahead N tokens and returns that token without consuming any /// tokens. /// /// LookAhead(0) returns the next token that would be returned by Lex(), /// LookAhead(1) returns the token after it, etc. This returns normal /// tokens after phase 5. As such, it is equivalent to using /// 'Lex', not 'LexUnexpandedToken'. const Token &LookAhead(unsigned N) { if (CachedLexPos + N < CachedTokens.size()) return CachedTokens[CachedLexPos+N]; else return PeekAhead(N+1); } /// \brief When backtracking is enabled and tokens are cached, /// this allows to revert a specific number of tokens. /// /// Note that the number of tokens being reverted should be up to the last /// backtrack position, not more. void RevertCachedTokens(unsigned N) { assert(isBacktrackEnabled() && "Should only be called when tokens are cached for backtracking"); assert(signed(CachedLexPos) - signed(N) >= signed(BacktrackPositions.back()) && "Should revert tokens up to the last backtrack position, not more"); assert(signed(CachedLexPos) - signed(N) >= 0 && "Corrupted backtrack positions ?"); CachedLexPos -= N; } /// \brief Enters a token in the token stream to be lexed next. /// /// If BackTrack() is called afterwards, the token will remain at the /// insertion point. void EnterToken(const Token &Tok) { EnterCachingLexMode(); CachedTokens.insert(CachedTokens.begin()+CachedLexPos, Tok); } /// We notify the Preprocessor that if it is caching tokens (because /// backtrack is enabled) it should replace the most recent cached tokens /// with the given annotation token. This function has no effect if /// backtracking is not enabled. /// /// Note that the use of this function is just for optimization, so that the /// cached tokens doesn't get re-parsed and re-resolved after a backtrack is /// invoked. void AnnotateCachedTokens(const Token &Tok) { assert(Tok.isAnnotation() && "Expected annotation token"); if (CachedLexPos != 0 && isBacktrackEnabled()) AnnotatePreviousCachedTokens(Tok); } /// Get the location of the last cached token, suitable for setting the end /// location of an annotation token. SourceLocation getLastCachedTokenLocation() const { assert(CachedLexPos != 0); return CachedTokens[CachedLexPos-1].getLastLoc(); } /// \brief Replace the last token with an annotation token. /// /// Like AnnotateCachedTokens(), this routine replaces an /// already-parsed (and resolved) token with an annotation /// token. However, this routine only replaces the last token with /// the annotation token; it does not affect any other cached /// tokens. This function has no effect if backtracking is not /// enabled. void ReplaceLastTokenWithAnnotation(const Token &Tok) { assert(Tok.isAnnotation() && "Expected annotation token"); if (CachedLexPos != 0 && isBacktrackEnabled()) CachedTokens[CachedLexPos-1] = Tok; } /// Update the current token to represent the provided /// identifier, in order to cache an action performed by typo correction. void TypoCorrectToken(const Token &Tok) { assert(Tok.getIdentifierInfo() && "Expected identifier token"); if (CachedLexPos != 0 && isBacktrackEnabled()) CachedTokens[CachedLexPos-1] = Tok; } /// \brief Recompute the current lexer kind based on the CurLexer/CurPTHLexer/ /// CurTokenLexer pointers. void recomputeCurLexerKind(); /// \brief Returns true if incremental processing is enabled bool isIncrementalProcessingEnabled() const { return IncrementalProcessing; } /// \brief Enables the incremental processing void enableIncrementalProcessing(bool value = true) { IncrementalProcessing = value; } /// \brief Specify the point at which code-completion will be performed. /// /// \param File the file in which code completion should occur. If /// this file is included multiple times, code-completion will /// perform completion the first time it is included. If NULL, this /// function clears out the code-completion point. /// /// \param Line the line at which code completion should occur /// (1-based). /// /// \param Column the column at which code completion should occur /// (1-based). /// /// \returns true if an error occurred, false otherwise. bool SetCodeCompletionPoint(const FileEntry *File, unsigned Line, unsigned Column); /// \brief Determine if we are performing code completion. bool isCodeCompletionEnabled() const { return CodeCompletionFile != nullptr; } /// \brief Returns the location of the code-completion point. /// /// Returns an invalid location if code-completion is not enabled or the file /// containing the code-completion point has not been lexed yet. SourceLocation getCodeCompletionLoc() const { return CodeCompletionLoc; } /// \brief Returns the start location of the file of code-completion point. /// /// Returns an invalid location if code-completion is not enabled or the file /// containing the code-completion point has not been lexed yet. SourceLocation getCodeCompletionFileLoc() const { return CodeCompletionFileLoc; } /// \brief Returns true if code-completion is enabled and we have hit the /// code-completion point. bool isCodeCompletionReached() const { return CodeCompletionReached; } /// \brief Note that we hit the code-completion point. void setCodeCompletionReached() { assert(isCodeCompletionEnabled() && "Code-completion not enabled!"); CodeCompletionReached = true; // Silence any diagnostics that occur after we hit the code-completion. getDiagnostics().setSuppressAllDiagnostics(true); } /// \brief The location of the currently-active \#pragma clang /// arc_cf_code_audited begin. /// /// Returns an invalid location if there is no such pragma active. SourceLocation getPragmaARCCFCodeAuditedLoc() const { return PragmaARCCFCodeAuditedLoc; } /// \brief Set the location of the currently-active \#pragma clang /// arc_cf_code_audited begin. An invalid location ends the pragma. void setPragmaARCCFCodeAuditedLoc(SourceLocation Loc) { PragmaARCCFCodeAuditedLoc = Loc; } /// \brief The location of the currently-active \#pragma clang /// assume_nonnull begin. /// /// Returns an invalid location if there is no such pragma active. SourceLocation getPragmaAssumeNonNullLoc() const { return PragmaAssumeNonNullLoc; } /// \brief Set the location of the currently-active \#pragma clang /// assume_nonnull begin. An invalid location ends the pragma. void setPragmaAssumeNonNullLoc(SourceLocation Loc) { PragmaAssumeNonNullLoc = Loc; } /// \brief Set the directory in which the main file should be considered /// to have been found, if it is not a real file. void setMainFileDir(const DirectoryEntry *Dir) { MainFileDir = Dir; } /// \brief Instruct the preprocessor to skip part of the main source file. /// /// \param Bytes The number of bytes in the preamble to skip. /// /// \param StartOfLine Whether skipping these bytes puts the lexer at the /// start of a line. void setSkipMainFilePreamble(unsigned Bytes, bool StartOfLine) { SkipMainFilePreamble.first = Bytes; SkipMainFilePreamble.second = StartOfLine; } /// Forwarding function for diagnostics. This emits a diagnostic at /// the specified Token's location, translating the token's start /// position in the current buffer into a SourcePosition object for rendering. DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID) const { return Diags->Report(Loc, DiagID); } DiagnosticBuilder Diag(const Token &Tok, unsigned DiagID) const { return Diags->Report(Tok.getLocation(), DiagID); } /// Return the 'spelling' of the token at the given /// location; does not go up to the spelling location or down to the /// expansion location. /// /// \param buffer A buffer which will be used only if the token requires /// "cleaning", e.g. if it contains trigraphs or escaped newlines /// \param invalid If non-null, will be set \c true if an error occurs. StringRef getSpelling(SourceLocation loc, SmallVectorImpl<char> &buffer, bool *invalid = nullptr) const { return Lexer::getSpelling(loc, buffer, SourceMgr, LangOpts, invalid); } /// \brief Return the 'spelling' of the Tok token. /// /// The spelling of a token is the characters used to represent the token in /// the source file after trigraph expansion and escaped-newline folding. In /// particular, this wants to get the true, uncanonicalized, spelling of /// things like digraphs, UCNs, etc. /// /// \param Invalid If non-null, will be set \c true if an error occurs. std::string getSpelling(const Token &Tok, bool *Invalid = nullptr) const { return Lexer::getSpelling(Tok, SourceMgr, LangOpts, Invalid); } /// \brief Get the spelling of a token into a preallocated buffer, instead /// of as an std::string. /// /// The caller is required to allocate enough space for the token, which is /// guaranteed to be at least Tok.getLength() bytes long. The length of the /// actual result is returned. /// /// Note that this method may do two possible things: it may either fill in /// the buffer specified with characters, or it may *change the input pointer* /// to point to a constant buffer with the data already in it (avoiding a /// copy). The caller is not allowed to modify the returned buffer pointer /// if an internal buffer is returned. unsigned getSpelling(const Token &Tok, const char *&Buffer, bool *Invalid = nullptr) const { return Lexer::getSpelling(Tok, Buffer, SourceMgr, LangOpts, Invalid); } /// \brief Get the spelling of a token into a SmallVector. /// /// Note that the returned StringRef may not point to the /// supplied buffer if a copy can be avoided. StringRef getSpelling(const Token &Tok, SmallVectorImpl<char> &Buffer, bool *Invalid = nullptr) const; /// \brief Relex the token at the specified location. /// \returns true if there was a failure, false on success. bool getRawToken(SourceLocation Loc, Token &Result, bool IgnoreWhiteSpace = false) { return Lexer::getRawToken(Loc, Result, SourceMgr, LangOpts, IgnoreWhiteSpace); } /// \brief Given a Token \p Tok that is a numeric constant with length 1, /// return the character. char getSpellingOfSingleCharacterNumericConstant(const Token &Tok, bool *Invalid = nullptr) const { assert(Tok.is(tok::numeric_constant) && Tok.getLength() == 1 && "Called on unsupported token"); assert(!Tok.needsCleaning() && "Token can't need cleaning with length 1"); // If the token is carrying a literal data pointer, just use it. if (const char *D = Tok.getLiteralData()) return *D; // Otherwise, fall back on getCharacterData, which is slower, but always // works. return *SourceMgr.getCharacterData(Tok.getLocation(), Invalid); } /// \brief Retrieve the name of the immediate macro expansion. /// /// This routine starts from a source location, and finds the name of the /// macro responsible for its immediate expansion. It looks through any /// intervening macro argument expansions to compute this. It returns a /// StringRef that refers to the SourceManager-owned buffer of the source /// where that macro name is spelled. Thus, the result shouldn't out-live /// the SourceManager. StringRef getImmediateMacroName(SourceLocation Loc) { return Lexer::getImmediateMacroName(Loc, SourceMgr, getLangOpts()); } /// \brief Plop the specified string into a scratch buffer and set the /// specified token's location and length to it. /// /// If specified, the source location provides a location of the expansion /// point of the token. void CreateString(StringRef Str, Token &Tok, SourceLocation ExpansionLocStart = SourceLocation(), SourceLocation ExpansionLocEnd = SourceLocation()); /// \brief Computes the source location just past the end of the /// token at this source location. /// /// This routine can be used to produce a source location that /// points just past the end of the token referenced by \p Loc, and /// is generally used when a diagnostic needs to point just after a /// token where it expected something different that it received. If /// the returned source location would not be meaningful (e.g., if /// it points into a macro), this routine returns an invalid /// source location. /// /// \param Offset an offset from the end of the token, where the source /// location should refer to. The default offset (0) produces a source /// location pointing just past the end of the token; an offset of 1 produces /// a source location pointing to the last character in the token, etc. SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset = 0) { return Lexer::getLocForEndOfToken(Loc, Offset, SourceMgr, LangOpts); } /// \brief Returns true if the given MacroID location points at the first /// token of the macro expansion. /// /// \param MacroBegin If non-null and function returns true, it is set to /// begin location of the macro. bool isAtStartOfMacroExpansion(SourceLocation loc, SourceLocation *MacroBegin = nullptr) const { return Lexer::isAtStartOfMacroExpansion(loc, SourceMgr, LangOpts, MacroBegin); } /// \brief Returns true if the given MacroID location points at the last /// token of the macro expansion. /// /// \param MacroEnd If non-null and function returns true, it is set to /// end location of the macro. bool isAtEndOfMacroExpansion(SourceLocation loc, SourceLocation *MacroEnd = nullptr) const { return Lexer::isAtEndOfMacroExpansion(loc, SourceMgr, LangOpts, MacroEnd); } /// \brief Print the token to stderr, used for debugging. void DumpToken(const Token &Tok, bool DumpFlags = false) const; void DumpLocation(SourceLocation Loc) const; void DumpMacro(const MacroInfo &MI) const; void dumpMacroInfo(const IdentifierInfo *II); /// \brief Given a location that specifies the start of a /// token, return a new location that specifies a character within the token. SourceLocation AdvanceToTokenCharacter(SourceLocation TokStart, unsigned Char) const { return Lexer::AdvanceToTokenCharacter(TokStart, Char, SourceMgr, LangOpts); } /// \brief Increment the counters for the number of token paste operations /// performed. /// /// If fast was specified, this is a 'fast paste' case we handled. void IncrementPasteCounter(bool isFast) { if (isFast) ++NumFastTokenPaste; else ++NumTokenPaste; } void PrintStats(); size_t getTotalMemory() const; /// When the macro expander pastes together a comment (/##/) in Microsoft /// mode, this method handles updating the current state, returning the /// token on the next source line. void HandleMicrosoftCommentPaste(Token &Tok); //===--------------------------------------------------------------------===// // Preprocessor callback methods. These are invoked by a lexer as various // directives and events are found. /// Given a tok::raw_identifier token, look up the /// identifier information for the token and install it into the token, /// updating the token kind accordingly. IdentifierInfo *LookUpIdentifierInfo(Token &Identifier) const; private: llvm::DenseMap<IdentifierInfo*,unsigned> PoisonReasons; public: /// \brief Specifies the reason for poisoning an identifier. /// /// If that identifier is accessed while poisoned, then this reason will be /// used instead of the default "poisoned" diagnostic. void SetPoisonReason(IdentifierInfo *II, unsigned DiagID); /// \brief Display reason for poisoned identifier. void HandlePoisonedIdentifier(Token & Tok); void MaybeHandlePoisonedIdentifier(Token & Identifier) { if(IdentifierInfo * II = Identifier.getIdentifierInfo()) { if(II->isPoisoned()) { HandlePoisonedIdentifier(Identifier); } } } private: /// Identifiers used for SEH handling in Borland. These are only /// allowed in particular circumstances // __except block IdentifierInfo *Ident__exception_code, *Ident___exception_code, *Ident_GetExceptionCode; // __except filter expression IdentifierInfo *Ident__exception_info, *Ident___exception_info, *Ident_GetExceptionInfo; // __finally IdentifierInfo *Ident__abnormal_termination, *Ident___abnormal_termination, *Ident_AbnormalTermination; const char *getCurLexerEndPos(); public: void PoisonSEHIdentifiers(bool Poison = true); // Borland /// \brief Callback invoked when the lexer reads an identifier and has /// filled in the tokens IdentifierInfo member. /// /// This callback potentially macro expands it or turns it into a named /// token (like 'for'). /// /// \returns true if we actually computed a token, false if we need to /// lex again. bool HandleIdentifier(Token &Identifier); /// \brief Callback invoked when the lexer hits the end of the current file. /// /// This either returns the EOF token and returns true, or /// pops a level off the include stack and returns false, at which point the /// client should call lex again. bool HandleEndOfFile(Token &Result, bool isEndOfMacro = false); /// \brief Callback invoked when the current TokenLexer hits the end of its /// token stream. bool HandleEndOfTokenLexer(Token &Result); /// \brief Callback invoked when the lexer sees a # token at the start of a /// line. /// /// This consumes the directive, modifies the lexer/preprocessor state, and /// advances the lexer(s) so that the next token read is the correct one. void HandleDirective(Token &Result); /// \brief Ensure that the next token is a tok::eod token. /// /// If not, emit a diagnostic and consume up until the eod. /// If \p EnableMacros is true, then we consider macros that expand to zero /// tokens as being ok. void CheckEndOfDirective(const char *Directive, bool EnableMacros = false); /// \brief Read and discard all tokens remaining on the current line until /// the tok::eod token is found. void DiscardUntilEndOfDirective(); /// \brief Returns true if the preprocessor has seen a use of /// __DATE__ or __TIME__ in the file so far. bool SawDateOrTime() const { return DATELoc != SourceLocation() || TIMELoc != SourceLocation(); } unsigned getCounterValue() const { return CounterValue; } void setCounterValue(unsigned V) { CounterValue = V; } /// \brief Retrieves the module that we're currently building, if any. Module *getCurrentModule(); /// \brief Allocate a new MacroInfo object with the provided SourceLocation. MacroInfo *AllocateMacroInfo(SourceLocation L); /// \brief Allocate a new MacroInfo object loaded from an AST file. MacroInfo *AllocateDeserializedMacroInfo(SourceLocation L, unsigned SubModuleID); /// \brief Turn the specified lexer token into a fully checked and spelled /// filename, e.g. as an operand of \#include. /// /// The caller is expected to provide a buffer that is large enough to hold /// the spelling of the filename, but is also expected to handle the case /// when this method decides to use a different buffer. /// /// \returns true if the input filename was in <>'s or false if it was /// in ""'s. bool GetIncludeFilenameSpelling(SourceLocation Loc,StringRef &Filename); /// \brief Given a "foo" or \<foo> reference, look up the indicated file. /// /// Returns null on failure. \p isAngled indicates whether the file /// reference is for system \#include's or not (i.e. using <> instead of ""). const FileEntry *LookupFile(SourceLocation FilenameLoc, StringRef Filename, bool isAngled, const DirectoryLookup *FromDir, const FileEntry *FromFile, const DirectoryLookup *&CurDir, SmallVectorImpl<char> *SearchPath, SmallVectorImpl<char> *RelativePath, ModuleMap::KnownHeader *SuggestedModule, bool SkipCache = false); /// \brief Get the DirectoryLookup structure used to find the current /// FileEntry, if CurLexer is non-null and if applicable. /// /// This allows us to implement \#include_next and find directory-specific /// properties. const DirectoryLookup *GetCurDirLookup() { return CurDirLookup; } /// \brief Return true if we're in the top-level file, not in a \#include. bool isInPrimaryFile() const; /// \brief Handle cases where the \#include name is expanded /// from a macro as multiple tokens, which need to be glued together. /// /// This occurs for code like: /// \code /// \#define FOO <x/y.h> /// \#include FOO /// \endcode /// because in this case, "<x/y.h>" is returned as 7 tokens, not one. /// /// This code concatenates and consumes tokens up to the '>' token. It /// returns false if the > was found, otherwise it returns true if it finds /// and consumes the EOD marker. bool ConcatenateIncludeName(SmallString<128> &FilenameBuffer, SourceLocation &End); /// \brief Lex an on-off-switch (C99 6.10.6p2) and verify that it is /// followed by EOD. Return true if the token is not a valid on-off-switch. bool LexOnOffSwitch(tok::OnOffSwitch &OOS); bool CheckMacroName(Token &MacroNameTok, MacroUse isDefineUndef, bool *ShadowFlag = nullptr); private: void PushIncludeMacroStack() { assert(CurLexerKind != CLK_CachingLexer && "cannot push a caching lexer"); IncludeMacroStack.emplace_back( CurLexerKind, CurSubmodule, std::move(CurLexer), std::move(CurPTHLexer), CurPPLexer, std::move(CurTokenLexer), CurDirLookup); CurPPLexer = nullptr; } void PopIncludeMacroStack() { CurLexer = std::move(IncludeMacroStack.back().TheLexer); CurPTHLexer = std::move(IncludeMacroStack.back().ThePTHLexer); CurPPLexer = IncludeMacroStack.back().ThePPLexer; CurTokenLexer = std::move(IncludeMacroStack.back().TheTokenLexer); CurDirLookup = IncludeMacroStack.back().TheDirLookup; CurSubmodule = IncludeMacroStack.back().TheSubmodule; CurLexerKind = IncludeMacroStack.back().CurLexerKind; IncludeMacroStack.pop_back(); } void PropagateLineStartLeadingSpaceInfo(Token &Result); void EnterSubmodule(Module *M, SourceLocation ImportLoc); void LeaveSubmodule(); /// Update the set of active module macros and ambiguity flag for a module /// macro name. void updateModuleMacroInfo(const IdentifierInfo *II, ModuleMacroInfo &Info); /// \brief Allocate a new MacroInfo object. MacroInfo *AllocateMacroInfo(); DefMacroDirective *AllocateDefMacroDirective(MacroInfo *MI, SourceLocation Loc); UndefMacroDirective *AllocateUndefMacroDirective(SourceLocation UndefLoc); VisibilityMacroDirective *AllocateVisibilityMacroDirective(SourceLocation Loc, bool isPublic); /// \brief Lex and validate a macro name, which occurs after a /// \#define or \#undef. /// /// \param MacroNameTok Token that represents the name defined or undefined. /// \param IsDefineUndef Kind if preprocessor directive. /// \param ShadowFlag Points to flag that is set if macro name shadows /// a keyword. /// /// This emits a diagnostic, sets the token kind to eod, /// and discards the rest of the macro line if the macro name is invalid. void ReadMacroName(Token &MacroNameTok, MacroUse IsDefineUndef = MU_Other, bool *ShadowFlag = nullptr); /// The ( starting an argument list of a macro definition has just been read. /// Lex the rest of the arguments and the closing ), updating \p MI with /// what we learn and saving in \p LastTok the last token read. /// Return true if an error occurs parsing the arg list. bool ReadMacroDefinitionArgList(MacroInfo *MI, Token& LastTok); /// We just read a \#if or related directive and decided that the /// subsequent tokens are in the \#if'd out portion of the /// file. Lex the rest of the file, until we see an \#endif. If \p /// FoundNonSkipPortion is true, then we have already emitted code for part of /// this \#if directive, so \#else/\#elif blocks should never be entered. If /// \p FoundElse is false, then \#else directives are ok, if not, then we have /// already seen one so a \#else directive is a duplicate. When this returns, /// the caller can lex the first valid token. void SkipExcludedConditionalBlock(SourceLocation IfTokenLoc, bool FoundNonSkipPortion, bool FoundElse, SourceLocation ElseLoc = SourceLocation()); /// \brief A fast PTH version of SkipExcludedConditionalBlock. void PTHSkipExcludedConditionalBlock(); /// \brief Evaluate an integer constant expression that may occur after a /// \#if or \#elif directive and return it as a bool. /// /// If the expression is equivalent to "!defined(X)" return X in IfNDefMacro. bool EvaluateDirectiveExpression(IdentifierInfo *&IfNDefMacro); /// \brief Install the standard preprocessor pragmas: /// \#pragma GCC poison/system_header/dependency and \#pragma once. void RegisterBuiltinPragmas(); /// \brief Register builtin macros such as __LINE__ with the identifier table. void RegisterBuiltinMacros(); /// If an identifier token is read that is to be expanded as a macro, handle /// it and return the next token as 'Tok'. If we lexed a token, return true; /// otherwise the caller should lex again. bool HandleMacroExpandedIdentifier(Token &Tok, const MacroDefinition &MD); /// \brief Cache macro expanded tokens for TokenLexers. // /// Works like a stack; a TokenLexer adds the macro expanded tokens that is /// going to lex in the cache and when it finishes the tokens are removed /// from the end of the cache. Token *cacheMacroExpandedTokens(TokenLexer *tokLexer, ArrayRef<Token> tokens); void removeCachedMacroExpandedTokensOfLastLexer(); friend void TokenLexer::ExpandFunctionArguments(); /// Determine whether the next preprocessor token to be /// lexed is a '('. If so, consume the token and return true, if not, this /// method should have no observable side-effect on the lexed tokens. bool isNextPPTokenLParen(); /// After reading "MACRO(", this method is invoked to read all of the formal /// arguments specified for the macro invocation. Returns null on error. MacroArgs *ReadFunctionLikeMacroArgs(Token &MacroName, MacroInfo *MI, SourceLocation &ExpansionEnd); /// \brief If an identifier token is read that is to be expanded /// as a builtin macro, handle it and return the next token as 'Tok'. void ExpandBuiltinMacro(Token &Tok); /// \brief Read a \c _Pragma directive, slice it up, process it, then /// return the first token after the directive. /// This assumes that the \c _Pragma token has just been read into \p Tok. void Handle_Pragma(Token &Tok); /// \brief Like Handle_Pragma except the pragma text is not enclosed within /// a string literal. void HandleMicrosoft__pragma(Token &Tok); /// \brief Add a lexer to the top of the include stack and /// start lexing tokens from it instead of the current buffer. void EnterSourceFileWithLexer(Lexer *TheLexer, const DirectoryLookup *Dir); /// \brief Add a lexer to the top of the include stack and /// start getting tokens from it using the PTH cache. void EnterSourceFileWithPTH(PTHLexer *PL, const DirectoryLookup *Dir); /// \brief Set the FileID for the preprocessor predefines. void setPredefinesFileID(FileID FID) { assert(PredefinesFileID.isInvalid() && "PredefinesFileID already set!"); PredefinesFileID = FID; } /// \brief Returns true if we are lexing from a file and not a /// pragma or a macro. static bool IsFileLexer(const Lexer* L, const PreprocessorLexer* P) { return L ? !L->isPragmaLexer() : P != nullptr; } static bool IsFileLexer(const IncludeStackInfo& I) { return IsFileLexer(I.TheLexer.get(), I.ThePPLexer); } bool IsFileLexer() const { return IsFileLexer(CurLexer.get(), CurPPLexer); } //===--------------------------------------------------------------------===// // Caching stuff. void CachingLex(Token &Result); bool InCachingLexMode() const { // If the Lexer pointers are 0 and IncludeMacroStack is empty, it means // that we are past EOF, not that we are in CachingLex mode. return !CurPPLexer && !CurTokenLexer && !CurPTHLexer && !IncludeMacroStack.empty(); } void EnterCachingLexMode(); void ExitCachingLexMode() { if (InCachingLexMode()) RemoveTopOfLexerStack(); } const Token &PeekAhead(unsigned N); void AnnotatePreviousCachedTokens(const Token &Tok); //===--------------------------------------------------------------------===// /// Handle*Directive - implement the various preprocessor directives. These /// should side-effect the current preprocessor object so that the next call /// to Lex() will return the appropriate token next. void HandleLineDirective(Token &Tok); void HandleDigitDirective(Token &Tok); void HandleUserDiagnosticDirective(Token &Tok, bool isWarning); void HandleIdentSCCSDirective(Token &Tok); void HandleMacroPublicDirective(Token &Tok); void HandleMacroPrivateDirective(Token &Tok); // File inclusion. void HandleIncludeDirective(SourceLocation HashLoc, Token &Tok, const DirectoryLookup *LookupFrom = nullptr, const FileEntry *LookupFromFile = nullptr, bool isImport = false); void HandleIncludeNextDirective(SourceLocation HashLoc, Token &Tok); void HandleIncludeMacrosDirective(SourceLocation HashLoc, Token &Tok); void HandleImportDirective(SourceLocation HashLoc, Token &Tok); void HandleMicrosoftImportDirective(Token &Tok); public: // Module inclusion testing. /// \brief Find the module that owns the source or header file that /// \p Loc points to. If the location is in a file that was included /// into a module, or is outside any module, returns nullptr. Module *getModuleForLocation(SourceLocation Loc); /// \brief Find the module that contains the specified location, either /// directly or indirectly. Module *getModuleContainingLocation(SourceLocation Loc); private: // Macro handling. void HandleDefineDirective(Token &Tok, bool ImmediatelyAfterTopLevelIfndef); void HandleUndefDirective(Token &Tok); // Conditional Inclusion. void HandleIfdefDirective(Token &Tok, bool isIfndef, bool ReadAnyTokensBeforeDirective); void HandleIfDirective(Token &Tok, bool ReadAnyTokensBeforeDirective); void HandleEndifDirective(Token &Tok); void HandleElseDirective(Token &Tok); void HandleElifDirective(Token &Tok); // Pragmas. void HandlePragmaDirective(SourceLocation IntroducerLoc, PragmaIntroducerKind Introducer); public: void HandlePragmaOnce(Token &OnceTok); void HandlePragmaMark(); void HandlePragmaPoison(Token &PoisonTok); void HandlePragmaSystemHeader(Token &SysHeaderTok); void HandlePragmaDependency(Token &DependencyTok); void HandlePragmaPushMacro(Token &Tok); void HandlePragmaPopMacro(Token &Tok); void HandlePragmaIncludeAlias(Token &Tok); IdentifierInfo *ParsePragmaPushOrPopMacro(Token &Tok); // Return true and store the first token only if any CommentHandler // has inserted some tokens and getCommentRetentionState() is false. bool HandleComment(Token &Token, SourceRange Comment); /// \brief A macro is used, update information about macros that need unused /// warnings. void markMacroAsUsed(MacroInfo *MI); }; /// \brief Abstract base class that describes a handler that will receive /// source ranges for each of the comments encountered in the source file. class CommentHandler { public: virtual ~CommentHandler(); // The handler shall return true if it has pushed any tokens // to be read using e.g. EnterToken or EnterTokenStream. virtual bool HandleComment(Preprocessor &PP, SourceRange Comment) = 0; }; } // end namespace clang #endif
0
repos/DirectXShaderCompiler/tools/clang/include/clang
repos/DirectXShaderCompiler/tools/clang/include/clang/Lex/HeaderSearchOptions.h
//===--- HeaderSearchOptions.h ----------------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_LEX_HEADERSEARCHOPTIONS_H #define LLVM_CLANG_LEX_HEADERSEARCHOPTIONS_H #include "clang/Basic/LLVM.h" #include "llvm/ADT/IntrusiveRefCntPtr.h" #include "llvm/ADT/SetVector.h" #include "llvm/ADT/StringRef.h" #include <string> #include <vector> namespace clang { namespace frontend { /// IncludeDirGroup - Identifiers the group a include entry belongs to, which /// represents its relative positive in the search list. A \#include of a "" /// path starts at the -iquote group, then searches the Angled group, then /// searches the system group, etc. enum IncludeDirGroup { Quoted = 0, ///< '\#include ""' paths, added by 'gcc -iquote'. Angled, ///< Paths for '\#include <>' added by '-I'. IndexHeaderMap, ///< Like Angled, but marks header maps used when /// building frameworks. System, ///< Like Angled, but marks system directories. ExternCSystem, ///< Like System, but headers are implicitly wrapped in /// extern "C". CSystem, ///< Like System, but only used for C. CXXSystem, ///< Like System, but only used for C++. ObjCSystem, ///< Like System, but only used for ObjC. ObjCXXSystem, ///< Like System, but only used for ObjC++. After ///< Like System, but searched after the system directories. }; } /// HeaderSearchOptions - Helper class for storing options related to the /// initialization of the HeaderSearch object. class HeaderSearchOptions : public RefCountedBase<HeaderSearchOptions> { public: struct Entry { std::string Path; frontend::IncludeDirGroup Group; unsigned IsFramework : 1; /// IgnoreSysRoot - This is false if an absolute path should be treated /// relative to the sysroot, or true if it should always be the absolute /// path. unsigned IgnoreSysRoot : 1; Entry(StringRef path, frontend::IncludeDirGroup group, bool isFramework, bool ignoreSysRoot) : Path(path), Group(group), IsFramework(isFramework), IgnoreSysRoot(ignoreSysRoot) {} }; struct SystemHeaderPrefix { /// A prefix to be matched against paths in \#include directives. std::string Prefix; /// True if paths beginning with this prefix should be treated as system /// headers. bool IsSystemHeader; SystemHeaderPrefix(StringRef Prefix, bool IsSystemHeader) : Prefix(Prefix), IsSystemHeader(IsSystemHeader) {} }; /// If non-empty, the directory to use as a "virtual system root" for include /// paths. std::string Sysroot; /// User specified include entries. std::vector<Entry> UserEntries; /// User-specified system header prefixes. std::vector<SystemHeaderPrefix> SystemHeaderPrefixes; /// The directory which holds the compiler resource files (builtin includes, /// etc.). std::string ResourceDir; /// \brief The directory used for the module cache. std::string ModuleCachePath; /// \brief The directory used for a user build. std::string ModuleUserBuildPath; /// The module/pch container format. std::string ModuleFormat; /// \brief Whether we should disable the use of the hash string within the /// module cache. /// /// Note: Only used for testing! unsigned DisableModuleHash : 1; /// \brief Implicit module maps. This option is enabld by default when /// modules is enabled. unsigned ImplicitModuleMaps : 1; /// \brief Set the 'home directory' of a module map file to the current /// working directory (or the home directory of the module map file that /// contained the 'extern module' directive importing this module map file /// if any) rather than the directory containing the module map file. // /// The home directory is where we look for files named in the module map /// file. unsigned ModuleMapFileHomeIsCwd : 1; /// \brief The interval (in seconds) between pruning operations. /// /// This operation is expensive, because it requires Clang to walk through /// the directory structure of the module cache, stat()'ing and removing /// files. /// /// The default value is large, e.g., the operation runs once a week. unsigned ModuleCachePruneInterval; /// \brief The time (in seconds) after which an unused module file will be /// considered unused and will, therefore, be pruned. /// /// When the module cache is pruned, any module file that has not been /// accessed in this many seconds will be removed. The default value is /// large, e.g., a month, to avoid forcing infrequently-used modules to be /// regenerated often. unsigned ModuleCachePruneAfter; /// \brief The time in seconds when the build session started. /// /// This time is used by other optimizations in header search and module /// loading. uint64_t BuildSessionTimestamp; /// \brief The set of macro names that should be ignored for the purposes /// of computing the module hash. llvm::SetVector<std::string> ModulesIgnoreMacros; /// \brief The set of user-provided virtual filesystem overlay files. std::vector<std::string> VFSOverlayFiles; /// Include the compiler builtin includes. unsigned UseBuiltinIncludes : 1; /// Include the system standard include search directories. unsigned UseStandardSystemIncludes : 1; /// Include the system standard C++ library include search directories. unsigned UseStandardCXXIncludes : 1; /// Use libc++ instead of the default libstdc++. unsigned UseLibcxx : 1; /// Whether header search information should be output as for -v. unsigned Verbose : 1; /// \brief If true, skip verifying input files used by modules if the /// module was already verified during this build session (see /// \c BuildSessionTimestamp). unsigned ModulesValidateOncePerBuildSession : 1; /// \brief Whether to validate system input files when a module is loaded. unsigned ModulesValidateSystemHeaders : 1; public: HeaderSearchOptions(StringRef _Sysroot = "/") : Sysroot(_Sysroot), ModuleFormat("raw"), DisableModuleHash(0), ImplicitModuleMaps(0), ModuleMapFileHomeIsCwd(0), ModuleCachePruneInterval(7 * 24 * 60 * 60), ModuleCachePruneAfter(31 * 24 * 60 * 60), BuildSessionTimestamp(0), UseBuiltinIncludes(true), UseStandardSystemIncludes(true), UseStandardCXXIncludes(true), UseLibcxx(false), Verbose(false), ModulesValidateOncePerBuildSession(false), ModulesValidateSystemHeaders(false) {} /// AddPath - Add the \p Path path to the specified \p Group list. void AddPath(StringRef Path, frontend::IncludeDirGroup Group, bool IsFramework, bool IgnoreSysRoot) { UserEntries.emplace_back(Path, Group, IsFramework, IgnoreSysRoot); } /// AddSystemHeaderPrefix - Override whether \#include directives naming a /// path starting with \p Prefix should be considered as naming a system /// header. void AddSystemHeaderPrefix(StringRef Prefix, bool IsSystemHeader) { SystemHeaderPrefixes.emplace_back(Prefix, IsSystemHeader); } void AddVFSOverlayFile(StringRef Name) { VFSOverlayFiles.push_back(Name); } }; } // end namespace clang #endif
0
repos/DirectXShaderCompiler/tools/clang/include/clang
repos/DirectXShaderCompiler/tools/clang/include/clang/Lex/TokenLexer.h
//===--- TokenLexer.h - Lex from a token buffer -----------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines the TokenLexer interface. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_LEX_TOKENLEXER_H #define LLVM_CLANG_LEX_TOKENLEXER_H #include "clang/Basic/SourceLocation.h" namespace clang { class MacroInfo; class Preprocessor; class Token; class MacroArgs; /// TokenLexer - This implements a lexer that returns tokens from a macro body /// or token stream instead of lexing from a character buffer. This is used for /// macro expansion and _Pragma handling, for example. /// class TokenLexer { /// Macro - The macro we are expanding from. This is null if expanding a /// token stream. /// MacroInfo *Macro; /// ActualArgs - The actual arguments specified for a function-like macro, or /// null. The TokenLexer owns the pointed-to object. MacroArgs *ActualArgs; /// PP - The current preprocessor object we are expanding for. /// Preprocessor &PP; /// Tokens - This is the pointer to an array of tokens that the macro is /// defined to, with arguments expanded for function-like macros. If this is /// a token stream, these are the tokens we are returning. This points into /// the macro definition we are lexing from, a cache buffer that is owned by /// the preprocessor, or some other buffer that we may or may not own /// (depending on OwnsTokens). /// Note that if it points into Preprocessor's cache buffer, the Preprocessor /// may update the pointer as needed. const Token *Tokens; friend class Preprocessor; /// NumTokens - This is the length of the Tokens array. /// unsigned NumTokens; /// CurToken - This is the next token that Lex will return. /// unsigned CurToken; /// ExpandLocStart/End - The source location range where this macro was /// expanded. SourceLocation ExpandLocStart, ExpandLocEnd; /// \brief Source location pointing at the source location entry chunk that /// was reserved for the current macro expansion. SourceLocation MacroExpansionStart; /// \brief The offset of the macro expansion in the /// "source location address space". unsigned MacroStartSLocOffset; /// \brief Location of the macro definition. SourceLocation MacroDefStart; /// \brief Length of the macro definition. unsigned MacroDefLength; /// Lexical information about the expansion point of the macro: the identifier /// that the macro expanded from had these properties. bool AtStartOfLine : 1; bool HasLeadingSpace : 1; // NextTokGetsSpace - When this is true, the next token appended to the // output list during function argument expansion will get a leading space, // regardless of whether it had one to begin with or not. This is used for // placemarker support. If still true after function argument expansion, the // leading space will be applied to the first token following the macro // expansion. bool NextTokGetsSpace : 1; /// OwnsTokens - This is true if this TokenLexer allocated the Tokens /// array, and thus needs to free it when destroyed. For simple object-like /// macros (for example) we just point into the token buffer of the macro /// definition, we don't make a copy of it. bool OwnsTokens : 1; /// DisableMacroExpansion - This is true when tokens lexed from the TokenLexer /// should not be subject to further macro expansion. bool DisableMacroExpansion : 1; TokenLexer(const TokenLexer &) = delete; void operator=(const TokenLexer &) = delete; public: /// Create a TokenLexer for the specified macro with the specified actual /// arguments. Note that this ctor takes ownership of the ActualArgs pointer. /// ILEnd specifies the location of the ')' for a function-like macro or the /// identifier for an object-like macro. TokenLexer(Token &Tok, SourceLocation ILEnd, MacroInfo *MI, MacroArgs *ActualArgs, Preprocessor &pp) : Macro(nullptr), ActualArgs(nullptr), PP(pp), OwnsTokens(false) { Init(Tok, ILEnd, MI, ActualArgs); } /// Init - Initialize this TokenLexer to expand from the specified macro /// with the specified argument information. Note that this ctor takes /// ownership of the ActualArgs pointer. ILEnd specifies the location of the /// ')' for a function-like macro or the identifier for an object-like macro. void Init(Token &Tok, SourceLocation ILEnd, MacroInfo *MI, MacroArgs *ActualArgs); /// Create a TokenLexer for the specified token stream. If 'OwnsTokens' is /// specified, this takes ownership of the tokens and delete[]'s them when /// the token lexer is empty. TokenLexer(const Token *TokArray, unsigned NumToks, bool DisableExpansion, bool ownsTokens, Preprocessor &pp) : Macro(nullptr), ActualArgs(nullptr), PP(pp), OwnsTokens(false) { Init(TokArray, NumToks, DisableExpansion, ownsTokens); } /// Init - Initialize this TokenLexer with the specified token stream. /// This does not take ownership of the specified token vector. /// /// DisableExpansion is true when macro expansion of tokens lexed from this /// stream should be disabled. void Init(const Token *TokArray, unsigned NumToks, bool DisableMacroExpansion, bool OwnsTokens); ~TokenLexer() { destroy(); } /// isNextTokenLParen - If the next token lexed will pop this macro off the /// expansion stack, return 2. If the next unexpanded token is a '(', return /// 1, otherwise return 0. unsigned isNextTokenLParen() const; /// Lex - Lex and return a token from this macro stream. bool Lex(Token &Tok); /// isParsingPreprocessorDirective - Return true if we are in the middle of a /// preprocessor directive. bool isParsingPreprocessorDirective() const; private: void destroy(); /// isAtEnd - Return true if the next lex call will pop this macro off the /// include stack. bool isAtEnd() const { return CurToken == NumTokens; } /// PasteTokens - Tok is the LHS of a ## operator, and CurToken is the ## /// operator. Read the ## and RHS, and paste the LHS/RHS together. If there /// are is another ## after it, chomp it iteratively. Return the result as /// Tok. If this returns true, the caller should immediately return the /// token. bool PasteTokens(Token &Tok); /// Expand the arguments of a function-like macro so that we can quickly /// return preexpanded tokens from Tokens. void ExpandFunctionArguments(); /// HandleMicrosoftCommentPaste - In microsoft compatibility mode, /##/ pastes /// together to form a comment that comments out everything in the current /// macro, other active macros, and anything left on the current physical /// source line of the expanded buffer. Handle this by returning the /// first token on the next line. void HandleMicrosoftCommentPaste(Token &Tok); /// \brief If \p loc is a FileID and points inside the current macro /// definition, returns the appropriate source location pointing at the /// macro expansion source location entry. SourceLocation getExpansionLocForMacroDefLoc(SourceLocation loc) const; /// \brief Creates SLocEntries and updates the locations of macro argument /// tokens to their new expanded locations. /// /// \param ArgIdSpellLoc the location of the macro argument id inside the /// macro definition. void updateLocForMacroArgTokens(SourceLocation ArgIdSpellLoc, Token *begin_tokens, Token *end_tokens); /// Remove comma ahead of __VA_ARGS__, if present, according to compiler /// dialect settings. Returns true if the comma is removed. bool MaybeRemoveCommaBeforeVaArgs(SmallVectorImpl<Token> &ResultToks, bool HasPasteOperator, MacroInfo *Macro, unsigned MacroArgNo, Preprocessor &PP); void PropagateLineStartLeadingSpaceInfo(Token &Result); }; } // end namespace clang #endif
0
repos/DirectXShaderCompiler/tools/clang/include/clang
repos/DirectXShaderCompiler/tools/clang/include/clang/Lex/Token.h
//===--- Token.h - Token interface ------------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines the Token interface. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_LEX_TOKEN_H #define LLVM_CLANG_LEX_TOKEN_H #include "clang/Basic/OperatorKinds.h" #include "clang/Basic/SourceLocation.h" #include "clang/Basic/TemplateKinds.h" #include "clang/Basic/TokenKinds.h" #include "llvm/ADT/StringRef.h" #include <cstdlib> namespace clang { class IdentifierInfo; /// Token - This structure provides full information about a lexed token. /// It is not intended to be space efficient, it is intended to return as much /// information as possible about each returned token. This is expected to be /// compressed into a smaller form if memory footprint is important. /// /// The parser can create a special "annotation token" representing a stream of /// tokens that were parsed and semantically resolved, e.g.: "foo::MyClass<int>" /// can be represented by a single typename annotation token that carries /// information about the SourceRange of the tokens and the type object. class Token { /// The location of the token. This is actually a SourceLocation. unsigned Loc; // Conceptually these next two fields could be in a union. However, this // causes gcc 4.2 to pessimize LexTokenInternal, a very performance critical // routine. Keeping as separate members with casts until a more beautiful fix // presents itself. /// UintData - This holds either the length of the token text, when /// a normal token, or the end of the SourceRange when an annotation /// token. unsigned UintData; /// PtrData - This is a union of four different pointer types, which depends /// on what type of token this is: /// Identifiers, keywords, etc: /// This is an IdentifierInfo*, which contains the uniqued identifier /// spelling. /// Literals: isLiteral() returns true. /// This is a pointer to the start of the token in a text buffer, which /// may be dirty (have trigraphs / escaped newlines). /// Annotations (resolved type names, C++ scopes, etc): isAnnotation(). /// This is a pointer to sema-specific data for the annotation token. /// Eof: // This is a pointer to a Decl. /// Other: /// This is null. void *PtrData; /// Kind - The actual flavor of token this is. tok::TokenKind Kind; /// Flags - Bits we track about this token, members of the TokenFlags enum. unsigned short Flags; public: // Various flags set per token: enum TokenFlags { StartOfLine = 0x01, // At start of line or only after whitespace // (considering the line after macro expansion). LeadingSpace = 0x02, // Whitespace exists before this token (considering // whitespace after macro expansion). DisableExpand = 0x04, // This identifier may never be macro expanded. NeedsCleaning = 0x08, // Contained an escaped newline or trigraph. LeadingEmptyMacro = 0x10, // Empty macro exists before this token. HasUDSuffix = 0x20, // This string or character literal has a ud-suffix. HasUCN = 0x40, // This identifier contains a UCN. IgnoredComma = 0x80, // This comma is not a macro argument separator (MS). StringifiedInMacro = 0x100, // This string or character literal is formed by // macro stringizing or charizing operator. }; tok::TokenKind getKind() const { return Kind; } void setKind(tok::TokenKind K) { Kind = K; } /// is/isNot - Predicates to check if this token is a specific kind, as in /// "if (Tok.is(tok::l_brace)) {...}". bool is(tok::TokenKind K) const { return Kind == K; } bool isNot(tok::TokenKind K) const { return Kind != K; } bool isOneOf(tok::TokenKind K1, tok::TokenKind K2) const { return is(K1) || is(K2); } template <typename... Ts> bool isOneOf(tok::TokenKind K1, tok::TokenKind K2, Ts... Ks) const { return is(K1) || isOneOf(K2, Ks...); } /// \brief Return true if this is a raw identifier (when lexing /// in raw mode) or a non-keyword identifier (when lexing in non-raw mode). bool isAnyIdentifier() const { return tok::isAnyIdentifier(getKind()); } /// \brief Return true if this is a "literal", like a numeric /// constant, string, etc. bool isLiteral() const { return tok::isLiteral(getKind()); } /// \brief Return true if this is any of tok::annot_* kind tokens. bool isAnnotation() const { return tok::isAnnotation(getKind()); } /// \brief Return a source location identifier for the specified /// offset in the current file. SourceLocation getLocation() const { return SourceLocation::getFromRawEncoding(Loc); } unsigned getLength() const { assert(!isAnnotation() && "Annotation tokens have no length field"); return UintData; } void setLocation(SourceLocation L) { Loc = L.getRawEncoding(); } void setLength(unsigned Len) { assert(!isAnnotation() && "Annotation tokens have no length field"); UintData = Len; } SourceLocation getAnnotationEndLoc() const { assert(isAnnotation() && "Used AnnotEndLocID on non-annotation token"); return SourceLocation::getFromRawEncoding(UintData ? UintData : Loc); } void setAnnotationEndLoc(SourceLocation L) { assert(isAnnotation() && "Used AnnotEndLocID on non-annotation token"); UintData = L.getRawEncoding(); } SourceLocation getLastLoc() const { return isAnnotation() ? getAnnotationEndLoc() : getLocation(); } SourceLocation getEndLoc() const { return isAnnotation() ? getAnnotationEndLoc() : getLocation().getLocWithOffset(getLength()); } /// \brief SourceRange of the group of tokens that this annotation token /// represents. SourceRange getAnnotationRange() const { return SourceRange(getLocation(), getAnnotationEndLoc()); } void setAnnotationRange(SourceRange R) { setLocation(R.getBegin()); setAnnotationEndLoc(R.getEnd()); } const char *getName() const { return tok::getTokenName(Kind); } /// \brief Reset all flags to cleared. void startToken() { Kind = tok::unknown; Flags = 0; PtrData = nullptr; UintData = 0; Loc = SourceLocation().getRawEncoding(); } IdentifierInfo *getIdentifierInfo() const { assert(isNot(tok::raw_identifier) && "getIdentifierInfo() on a tok::raw_identifier token!"); assert(!isAnnotation() && "getIdentifierInfo() on an annotation token!"); if (isLiteral()) return nullptr; if (is(tok::eof)) return nullptr; return (IdentifierInfo*) PtrData; } void setIdentifierInfo(IdentifierInfo *II) { PtrData = (void*) II; } const void *getEofData() const { assert(is(tok::eof)); return reinterpret_cast<const void *>(PtrData); } void setEofData(const void *D) { assert(is(tok::eof)); assert(!PtrData); PtrData = const_cast<void *>(D); } /// getRawIdentifier - For a raw identifier token (i.e., an identifier /// lexed in raw mode), returns a reference to the text substring in the /// buffer if known. StringRef getRawIdentifier() const { assert(is(tok::raw_identifier)); return StringRef(reinterpret_cast<const char *>(PtrData), getLength()); } void setRawIdentifierData(const char *Ptr) { assert(is(tok::raw_identifier)); PtrData = const_cast<char*>(Ptr); } /// getLiteralData - For a literal token (numeric constant, string, etc), this /// returns a pointer to the start of it in the text buffer if known, null /// otherwise. const char *getLiteralData() const { assert(isLiteral() && "Cannot get literal data of non-literal"); return reinterpret_cast<const char*>(PtrData); } void setLiteralData(const char *Ptr) { assert(isLiteral() && "Cannot set literal data of non-literal"); PtrData = const_cast<char*>(Ptr); } void *getAnnotationValue() const { assert(isAnnotation() && "Used AnnotVal on non-annotation token"); return PtrData; } void setAnnotationValue(void *val) { assert(isAnnotation() && "Used AnnotVal on non-annotation token"); PtrData = val; } /// \brief Set the specified flag. void setFlag(TokenFlags Flag) { Flags |= Flag; } /// \brief Unset the specified flag. void clearFlag(TokenFlags Flag) { Flags &= ~Flag; } /// \brief Return the internal represtation of the flags. /// /// This is only intended for low-level operations such as writing tokens to /// disk. unsigned getFlags() const { return Flags; } /// \brief Set a flag to either true or false. void setFlagValue(TokenFlags Flag, bool Val) { if (Val) setFlag(Flag); else clearFlag(Flag); } /// isAtStartOfLine - Return true if this token is at the start of a line. /// bool isAtStartOfLine() const { return (Flags & StartOfLine) ? true : false; } /// \brief Return true if this token has whitespace before it. /// bool hasLeadingSpace() const { return (Flags & LeadingSpace) ? true : false; } /// \brief Return true if this identifier token should never /// be expanded in the future, due to C99 6.10.3.4p2. bool isExpandDisabled() const { return (Flags & DisableExpand) ? true : false; } /// \brief Return true if we have an ObjC keyword identifier. bool isObjCAtKeyword(tok::ObjCKeywordKind objcKey) const; /// \brief Return the ObjC keyword kind. tok::ObjCKeywordKind getObjCKeywordID() const; /// \brief Return true if this token has trigraphs or escaped newlines in it. bool needsCleaning() const { return (Flags & NeedsCleaning) ? true : false; } /// \brief Return true if this token has an empty macro before it. /// bool hasLeadingEmptyMacro() const { return (Flags & LeadingEmptyMacro) ? true : false; } /// \brief Return true if this token is a string or character literal which /// has a ud-suffix. bool hasUDSuffix() const { return (Flags & HasUDSuffix) ? true : false; } /// Returns true if this token contains a universal character name. bool hasUCN() const { return (Flags & HasUCN) ? true : false; } // HLSL Change Starts bool isHLSLReserved() const { return is(tok::kw___is_signed) || is(tok::kw___declspec) || is(tok::kw___forceinline) || is(tok::kw_auto) || is(tok::kw_catch) || is(tok::kw_const_cast) || is(tok::kw_delete) || is(tok::kw_dynamic_cast) || is(tok::kw_enum) || is(tok::kw_explicit) || is(tok::kw_friend) || is(tok::kw_goto) || is(tok::kw_mutable) || is(tok::kw_new) || is(tok::kw_operator) || is(tok::kw_protected) || is(tok::kw_private) || is(tok::kw_public) || is(tok::kw_reinterpret_cast) || is(tok::kw_signed) || is(tok::kw_sizeof) || is(tok::kw_static_cast) || is(tok::kw_template) || is(tok::kw_throw) || is(tok::kw_try) || is(tok::kw_typename) || is(tok::kw_union) || is(tok::kw_using) || is(tok::kw_virtual); } // HLSL Change Starts /// Returns true if this token is formed by macro by stringizing or charizing /// operator. bool stringifiedInMacro() const { return (Flags & StringifiedInMacro) ? true : false; } }; /// \brief Information about the conditional stack (\#if directives) /// currently active. struct PPConditionalInfo { /// \brief Location where the conditional started. SourceLocation IfLoc; /// \brief True if this was contained in a skipping directive, e.g., /// in a "\#if 0" block. bool WasSkipping; /// \brief True if we have emitted tokens already, and now we're in /// an \#else block or something. Only useful in Skipping blocks. bool FoundNonSkip; /// \brief True if we've seen a \#else in this block. If so, /// \#elif/\#else directives are not allowed. bool FoundElse; }; } // end namespace clang namespace llvm { template <> struct isPodLike<clang::Token> { static const bool value = true; }; } // end namespace llvm #endif
0
repos/DirectXShaderCompiler/tools/clang/include/clang
repos/DirectXShaderCompiler/tools/clang/include/clang/Lex/ModuleMap.h
//===--- ModuleMap.h - Describe the layout of modules -----------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines the ModuleMap interface, which describes the layout of a // module as it relates to headers. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_LEX_MODULEMAP_H #define LLVM_CLANG_LEX_MODULEMAP_H #include "clang/Basic/LangOptions.h" #include "clang/Basic/Module.h" #include "clang/Basic/SourceManager.h" #include "llvm/ADT/DenseMap.h" #include "llvm/ADT/IntrusiveRefCntPtr.h" #include "llvm/ADT/SmallVector.h" #include "llvm/ADT/StringMap.h" #include "llvm/ADT/StringRef.h" #include <string> namespace clang { class DirectoryEntry; class FileEntry; class FileManager; class DiagnosticConsumer; class DiagnosticsEngine; class HeaderSearch; class ModuleMapParser; class ModuleMap { SourceManager &SourceMgr; DiagnosticsEngine &Diags; const LangOptions &LangOpts; const TargetInfo *Target; HeaderSearch &HeaderInfo; /// \brief The directory used for Clang-supplied, builtin include headers, /// such as "stdint.h". const DirectoryEntry *BuiltinIncludeDir; /// \brief Language options used to parse the module map itself. /// /// These are always simple C language options. LangOptions MMapLangOpts; // The module that we are building; related to \c LangOptions::CurrentModule. Module *CompilingModule; public: // The module that the .cc source file is associated with. Module *SourceModule; std::string SourceModuleName; private: /// \brief The top-level modules that are known. llvm::StringMap<Module *> Modules; /// \brief The number of modules we have created in total. unsigned NumCreatedModules; public: /// \brief Flags describing the role of a module header. enum ModuleHeaderRole { /// \brief This header is normally included in the module. NormalHeader = 0x0, /// \brief This header is included but private. PrivateHeader = 0x1, /// \brief This header is part of the module (for layering purposes) but /// should be textually included. TextualHeader = 0x2, // Caution: Adding an enumerator needs other changes. // Adjust the number of bits for KnownHeader::Storage. // Adjust the bitfield HeaderFileInfo::HeaderRole size. // Adjust the HeaderFileInfoTrait::ReadData streaming. // Adjust the HeaderFileInfoTrait::EmitData streaming. // Adjust ModuleMap::addHeader. }; /// \brief A header that is known to reside within a given module, /// whether it was included or excluded. class KnownHeader { llvm::PointerIntPair<Module *, 2, ModuleHeaderRole> Storage; public: KnownHeader() : Storage(nullptr, NormalHeader) { } KnownHeader(Module *M, ModuleHeaderRole Role) : Storage(M, Role) { } /// \brief Retrieve the module the header is stored in. Module *getModule() const { return Storage.getPointer(); } /// \brief The role of this header within the module. ModuleHeaderRole getRole() const { return Storage.getInt(); } /// \brief Whether this header is available in the module. bool isAvailable() const { return getModule()->isAvailable(); } // \brief Whether this known header is valid (i.e., it has an // associated module). explicit operator bool() const { return Storage.getPointer() != nullptr; } }; typedef llvm::SmallPtrSet<const FileEntry *, 1> AdditionalModMapsSet; private: typedef llvm::DenseMap<const FileEntry *, SmallVector<KnownHeader, 1> > HeadersMap; /// \brief Mapping from each header to the module that owns the contents of /// that header. HeadersMap Headers; /// \brief Mapping from directories with umbrella headers to the module /// that is generated from the umbrella header. /// /// This mapping is used to map headers that haven't explicitly been named /// in the module map over to the module that includes them via its umbrella /// header. llvm::DenseMap<const DirectoryEntry *, Module *> UmbrellaDirs; /// \brief The set of attributes that can be attached to a module. struct Attributes { Attributes() : IsSystem(), IsExternC(), IsExhaustive() {} /// \brief Whether this is a system module. unsigned IsSystem : 1; /// \brief Whether this is an extern "C" module. unsigned IsExternC : 1; /// \brief Whether this is an exhaustive set of configuration macros. unsigned IsExhaustive : 1; }; /// \brief A directory for which framework modules can be inferred. struct InferredDirectory { InferredDirectory() : InferModules() {} /// \brief Whether to infer modules from this directory. unsigned InferModules : 1; /// \brief The attributes to use for inferred modules. Attributes Attrs; /// \brief If \c InferModules is non-zero, the module map file that allowed /// inferred modules. Otherwise, nullptr. const FileEntry *ModuleMapFile; /// \brief The names of modules that cannot be inferred within this /// directory. SmallVector<std::string, 2> ExcludedModules; }; /// \brief A mapping from directories to information about inferring /// framework modules from within those directories. llvm::DenseMap<const DirectoryEntry *, InferredDirectory> InferredDirectories; /// A mapping from an inferred module to the module map that allowed the /// inference. llvm::DenseMap<const Module *, const FileEntry *> InferredModuleAllowedBy; llvm::DenseMap<const Module *, AdditionalModMapsSet> AdditionalModMaps; /// \brief Describes whether we haved parsed a particular file as a module /// map. llvm::DenseMap<const FileEntry *, bool> ParsedModuleMap; friend class ModuleMapParser; /// \brief Resolve the given export declaration into an actual export /// declaration. /// /// \param Mod The module in which we're resolving the export declaration. /// /// \param Unresolved The export declaration to resolve. /// /// \param Complain Whether this routine should complain about unresolvable /// exports. /// /// \returns The resolved export declaration, which will have a NULL pointer /// if the export could not be resolved. Module::ExportDecl resolveExport(Module *Mod, const Module::UnresolvedExportDecl &Unresolved, bool Complain) const; /// \brief Resolve the given module id to an actual module. /// /// \param Id The module-id to resolve. /// /// \param Mod The module in which we're resolving the module-id. /// /// \param Complain Whether this routine should complain about unresolvable /// module-ids. /// /// \returns The resolved module, or null if the module-id could not be /// resolved. Module *resolveModuleId(const ModuleId &Id, Module *Mod, bool Complain) const; /// \brief Looks up the modules that \p File corresponds to. /// /// If \p File represents a builtin header within Clang's builtin include /// directory, this also loads all of the module maps to see if it will get /// associated with a specific module (e.g. in /usr/include). HeadersMap::iterator findKnownHeader(const FileEntry *File); /// \brief Searches for a module whose umbrella directory contains \p File. /// /// \param File The header to search for. /// /// \param IntermediateDirs On success, contains the set of directories /// searched before finding \p File. KnownHeader findHeaderInUmbrellaDirs(const FileEntry *File, SmallVectorImpl<const DirectoryEntry *> &IntermediateDirs); /// \brief A convenience method to determine if \p File is (possibly nested) /// in an umbrella directory. bool isHeaderInUmbrellaDirs(const FileEntry *File) { SmallVector<const DirectoryEntry *, 2> IntermediateDirs; return static_cast<bool>(findHeaderInUmbrellaDirs(File, IntermediateDirs)); } Module *inferFrameworkModule(const DirectoryEntry *FrameworkDir, Attributes Attrs, Module *Parent); public: /// \brief Construct a new module map. /// /// \param SourceMgr The source manager used to find module files and headers. /// This source manager should be shared with the header-search mechanism, /// since they will refer to the same headers. /// /// \param Diags A diagnostic engine used for diagnostics. /// /// \param LangOpts Language options for this translation unit. /// /// \param Target The target for this translation unit. ModuleMap(SourceManager &SourceMgr, DiagnosticsEngine &Diags, const LangOptions &LangOpts, const TargetInfo *Target, HeaderSearch &HeaderInfo); /// \brief Destroy the module map. /// ~ModuleMap(); /// \brief Set the target information. void setTarget(const TargetInfo &Target); /// \brief Set the directory that contains Clang-supplied include /// files, such as our stdarg.h or tgmath.h. void setBuiltinIncludeDir(const DirectoryEntry *Dir) { BuiltinIncludeDir = Dir; } /// \brief Retrieve the module that owns the given header file, if any. /// /// \param File The header file that is likely to be included. /// /// \returns The module KnownHeader, which provides the module that owns the /// given header file. The KnownHeader is default constructed to indicate /// that no module owns this header file. KnownHeader findModuleForHeader(const FileEntry *File); /// \brief Reports errors if a module must not include a specific file. /// /// \param RequestingModule The module including a file. /// /// \param FilenameLoc The location of the inclusion's filename. /// /// \param Filename The included filename as written. /// /// \param File The included file. void diagnoseHeaderInclusion(Module *RequestingModule, SourceLocation FilenameLoc, StringRef Filename, const FileEntry *File); /// \brief Determine whether the given header is part of a module /// marked 'unavailable'. bool isHeaderInUnavailableModule(const FileEntry *Header) const; /// \brief Determine whether the given header is unavailable as part /// of the specified module. bool isHeaderUnavailableInModule(const FileEntry *Header, const Module *RequestingModule) const; /// \brief Retrieve a module with the given name. /// /// \param Name The name of the module to look up. /// /// \returns The named module, if known; otherwise, returns null. Module *findModule(StringRef Name) const; /// \brief Retrieve a module with the given name using lexical name lookup, /// starting at the given context. /// /// \param Name The name of the module to look up. /// /// \param Context The module context, from which we will perform lexical /// name lookup. /// /// \returns The named module, if known; otherwise, returns null. Module *lookupModuleUnqualified(StringRef Name, Module *Context) const; /// \brief Retrieve a module with the given name within the given context, /// using direct (qualified) name lookup. /// /// \param Name The name of the module to look up. /// /// \param Context The module for which we will look for a submodule. If /// null, we will look for a top-level module. /// /// \returns The named submodule, if known; otherwose, returns null. Module *lookupModuleQualified(StringRef Name, Module *Context) const; /// \brief Find a new module or submodule, or create it if it does not already /// exist. /// /// \param Name The name of the module to find or create. /// /// \param Parent The module that will act as the parent of this submodule, /// or NULL to indicate that this is a top-level module. /// /// \param IsFramework Whether this is a framework module. /// /// \param IsExplicit Whether this is an explicit submodule. /// /// \returns The found or newly-created module, along with a boolean value /// that will be true if the module is newly-created. std::pair<Module *, bool> findOrCreateModule(StringRef Name, Module *Parent, bool IsFramework, bool IsExplicit); /// \brief Infer the contents of a framework module map from the given /// framework directory. Module *inferFrameworkModule(const DirectoryEntry *FrameworkDir, bool IsSystem, Module *Parent); /// \brief Retrieve the module map file containing the definition of the given /// module. /// /// \param Module The module whose module map file will be returned, if known. /// /// \returns The file entry for the module map file containing the given /// module, or NULL if the module definition was inferred. const FileEntry *getContainingModuleMapFile(const Module *Module) const; /// \brief Get the module map file that (along with the module name) uniquely /// identifies this module. /// /// The particular module that \c Name refers to may depend on how the module /// was found in header search. However, the combination of \c Name and /// this module map will be globally unique for top-level modules. In the case /// of inferred modules, returns the module map that allowed the inference /// (e.g. contained 'module *'). Otherwise, returns /// getContainingModuleMapFile(). const FileEntry *getModuleMapFileForUniquing(const Module *M) const; void setInferredModuleAllowedBy(Module *M, const FileEntry *ModuleMap); /// \brief Get any module map files other than getModuleMapFileForUniquing(M) /// that define submodules of a top-level module \p M. This is cheaper than /// getting the module map file for each submodule individually, since the /// expected number of results is very small. AdditionalModMapsSet *getAdditionalModuleMapFiles(const Module *M) { auto I = AdditionalModMaps.find(M); if (I == AdditionalModMaps.end()) return nullptr; return &I->second; } void addAdditionalModuleMapFile(const Module *M, const FileEntry *ModuleMap) { AdditionalModMaps[M].insert(ModuleMap); } /// \brief Resolve all of the unresolved exports in the given module. /// /// \param Mod The module whose exports should be resolved. /// /// \param Complain Whether to emit diagnostics for failures. /// /// \returns true if any errors were encountered while resolving exports, /// false otherwise. bool resolveExports(Module *Mod, bool Complain); /// \brief Resolve all of the unresolved uses in the given module. /// /// \param Mod The module whose uses should be resolved. /// /// \param Complain Whether to emit diagnostics for failures. /// /// \returns true if any errors were encountered while resolving uses, /// false otherwise. bool resolveUses(Module *Mod, bool Complain); /// \brief Resolve all of the unresolved conflicts in the given module. /// /// \param Mod The module whose conflicts should be resolved. /// /// \param Complain Whether to emit diagnostics for failures. /// /// \returns true if any errors were encountered while resolving conflicts, /// false otherwise. bool resolveConflicts(Module *Mod, bool Complain); /// \brief Infers the (sub)module based on the given source location and /// source manager. /// /// \param Loc The location within the source that we are querying, along /// with its source manager. /// /// \returns The module that owns this source location, or null if no /// module owns this source location. Module *inferModuleFromLocation(FullSourceLoc Loc); /// \brief Sets the umbrella header of the given module to the given /// header. void setUmbrellaHeader(Module *Mod, const FileEntry *UmbrellaHeader, Twine NameAsWritten); /// \brief Sets the umbrella directory of the given module to the given /// directory. void setUmbrellaDir(Module *Mod, const DirectoryEntry *UmbrellaDir, Twine NameAsWritten); /// \brief Adds this header to the given module. /// \param Role The role of the header wrt the module. void addHeader(Module *Mod, Module::Header Header, ModuleHeaderRole Role); /// \brief Marks this header as being excluded from the given module. void excludeHeader(Module *Mod, Module::Header Header); /// \brief Parse the given module map file, and record any modules we /// encounter. /// /// \param File The file to be parsed. /// /// \param IsSystem Whether this module map file is in a system header /// directory, and therefore should be considered a system module. /// /// \param HomeDir The directory in which relative paths within this module /// map file will be resolved. /// /// \param ExternModuleLoc The location of the "extern module" declaration /// that caused us to load this module map file, if any. /// /// \returns true if an error occurred, false otherwise. bool parseModuleMapFile(const FileEntry *File, bool IsSystem, const DirectoryEntry *HomeDir, SourceLocation ExternModuleLoc = SourceLocation()); /// \brief Dump the contents of the module map, for debugging purposes. void dump(); typedef llvm::StringMap<Module *>::const_iterator module_iterator; module_iterator module_begin() const { return Modules.begin(); } module_iterator module_end() const { return Modules.end(); } }; } #endif
0
repos/DirectXShaderCompiler/tools/clang/include/clang
repos/DirectXShaderCompiler/tools/clang/include/clang/Lex/Pragma.h
//===--- Pragma.h - Pragma registration and handling ------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines the PragmaHandler and PragmaTable interfaces. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_LEX_PRAGMA_H #define LLVM_CLANG_LEX_PRAGMA_H #include "clang/Basic/LLVM.h" #include "llvm/ADT/StringMap.h" #include "llvm/ADT/StringRef.h" #include <cassert> namespace clang { class Preprocessor; class Token; class IdentifierInfo; class PragmaNamespace; /** * \brief Describes how the pragma was introduced, e.g., with \#pragma, * _Pragma, or __pragma. */ enum PragmaIntroducerKind { /** * \brief The pragma was introduced via \#pragma. */ PIK_HashPragma, /** * \brief The pragma was introduced via the C99 _Pragma(string-literal). */ PIK__Pragma, /** * \brief The pragma was introduced via the Microsoft * __pragma(token-string). */ PIK___pragma }; /// PragmaHandler - Instances of this interface defined to handle the various /// pragmas that the language front-end uses. Each handler optionally has a /// name (e.g. "pack") and the HandlePragma method is invoked when a pragma with /// that identifier is found. If a handler does not match any of the declared /// pragmas the handler with a null identifier is invoked, if it exists. /// /// Note that the PragmaNamespace class can be used to subdivide pragmas, e.g. /// we treat "\#pragma STDC" and "\#pragma GCC" as namespaces that contain other /// pragmas. class PragmaHandler { std::string Name; public: explicit PragmaHandler(StringRef name) : Name(name) {} PragmaHandler() {} virtual ~PragmaHandler(); StringRef getName() const { return Name; } virtual void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, Token &FirstToken) = 0; /// getIfNamespace - If this is a namespace, return it. This is equivalent to /// using a dynamic_cast, but doesn't require RTTI. virtual PragmaNamespace *getIfNamespace() { return nullptr; } }; /// EmptyPragmaHandler - A pragma handler which takes no action, which can be /// used to ignore particular pragmas. class EmptyPragmaHandler : public PragmaHandler { public: EmptyPragmaHandler(); void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, Token &FirstToken) override; }; /// PragmaNamespace - This PragmaHandler subdivides the namespace of pragmas, /// allowing hierarchical pragmas to be defined. Common examples of namespaces /// are "\#pragma GCC", "\#pragma STDC", and "\#pragma omp", but any namespaces /// may be (potentially recursively) defined. class PragmaNamespace : public PragmaHandler { /// Handlers - This is a map of the handlers in this namespace with their name /// as key. /// llvm::StringMap<PragmaHandler*> Handlers; public: explicit PragmaNamespace(StringRef Name) : PragmaHandler(Name) {} ~PragmaNamespace() override; /// FindHandler - Check to see if there is already a handler for the /// specified name. If not, return the handler for the null name if it /// exists, otherwise return null. If IgnoreNull is true (the default) then /// the null handler isn't returned on failure to match. PragmaHandler *FindHandler(StringRef Name, bool IgnoreNull = true) const; /// AddPragma - Add a pragma to this namespace. /// void AddPragma(PragmaHandler *Handler); /// RemovePragmaHandler - Remove the given handler from the /// namespace. void RemovePragmaHandler(PragmaHandler *Handler); bool IsEmpty() { return Handlers.empty(); } void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, Token &FirstToken) override; PragmaNamespace *getIfNamespace() override { return this; } }; } // end namespace clang #endif
0
repos/DirectXShaderCompiler/tools/clang/include/clang
repos/DirectXShaderCompiler/tools/clang/include/clang/Lex/PTHLexer.h
//===--- PTHLexer.h - Lexer based on Pre-tokenized input --------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines the PTHLexer interface. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_LEX_PTHLEXER_H #define LLVM_CLANG_LEX_PTHLEXER_H #include "clang/Lex/PreprocessorLexer.h" namespace clang { class PTHManager; class PTHSpellingSearch; class PTHLexer : public PreprocessorLexer { SourceLocation FileStartLoc; /// TokBuf - Buffer from PTH file containing raw token data. const unsigned char* TokBuf; /// CurPtr - Pointer into current offset of the token buffer where /// the next token will be read. const unsigned char* CurPtr; /// LastHashTokPtr - Pointer into TokBuf of the last processed '#' /// token that appears at the start of a line. const unsigned char* LastHashTokPtr; /// PPCond - Pointer to a side table in the PTH file that provides a /// a consise summary of the preproccessor conditional block structure. /// This is used to perform quick skipping of conditional blocks. const unsigned char* PPCond; /// CurPPCondPtr - Pointer inside PPCond that refers to the next entry /// to process when doing quick skipping of preprocessor blocks. const unsigned char* CurPPCondPtr; PTHLexer(const PTHLexer &) = delete; void operator=(const PTHLexer &) = delete; /// ReadToken - Used by PTHLexer to read tokens TokBuf. void ReadToken(Token& T); bool LexEndOfFile(Token &Result); /// PTHMgr - The PTHManager object that created this PTHLexer. PTHManager& PTHMgr; Token EofToken; protected: friend class PTHManager; /// Create a PTHLexer for the specified token stream. PTHLexer(Preprocessor& pp, FileID FID, const unsigned char *D, const unsigned char* ppcond, PTHManager &PM); public: ~PTHLexer() override {} /// Lex - Return the next token. bool Lex(Token &Tok); void getEOF(Token &Tok); /// DiscardToEndOfLine - Read the rest of the current preprocessor line as an /// uninterpreted string. This switches the lexer out of directive mode. void DiscardToEndOfLine(); /// isNextPPTokenLParen - Return 1 if the next unexpanded token will return a /// tok::l_paren token, 0 if it is something else and 2 if there are no more /// tokens controlled by this lexer. unsigned isNextPPTokenLParen() { // isNextPPTokenLParen is not on the hot path, and all we care about is // whether or not we are at a token with kind tok::eof or tok::l_paren. // Just read the first byte from the current token pointer to determine // its kind. tok::TokenKind x = (tok::TokenKind)*CurPtr; return x == tok::eof ? 2 : x == tok::l_paren; } /// IndirectLex - An indirect call to 'Lex' that can be invoked via /// the PreprocessorLexer interface. void IndirectLex(Token &Result) override { Lex(Result); } /// getSourceLocation - Return a source location for the token in /// the current file. SourceLocation getSourceLocation() override; /// SkipBlock - Used by Preprocessor to skip the current conditional block. bool SkipBlock(); }; } // end namespace clang #endif
0
repos/DirectXShaderCompiler/tools/clang/include/clang
repos/DirectXShaderCompiler/tools/clang/include/clang/Lex/TokenConcatenation.h
//===--- TokenConcatenation.h - Token Concatenation Avoidance ---*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines the TokenConcatenation class. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_LEX_TOKENCONCATENATION_H #define LLVM_CLANG_LEX_TOKENCONCATENATION_H #include "clang/Basic/TokenKinds.h" namespace clang { class Preprocessor; class Token; /// TokenConcatenation class, which answers the question of /// "Is it safe to emit two tokens without a whitespace between them, or /// would that cause implicit concatenation of the tokens?" /// /// For example, it emitting two identifiers "foo" and "bar" next to each /// other would cause the lexer to produce one "foobar" token. Emitting "1" /// and ")" next to each other is safe. /// class TokenConcatenation { Preprocessor &PP; enum AvoidConcatInfo { /// By default, a token never needs to avoid concatenation. Most tokens /// (e.g. ',', ')', etc) don't cause a problem when concatenated. aci_never_avoid_concat = 0, /// aci_custom_firstchar - AvoidConcat contains custom code to handle this /// token's requirements, and it needs to know the first character of the /// token. aci_custom_firstchar = 1, /// aci_custom - AvoidConcat contains custom code to handle this token's /// requirements, but it doesn't need to know the first character of the /// token. aci_custom = 2, /// aci_avoid_equal - Many tokens cannot be safely followed by an '=' /// character. For example, "<<" turns into "<<=" when followed by an =. aci_avoid_equal = 4 }; /// TokenInfo - This array contains information for each token on what /// action to take when avoiding concatenation of tokens in the AvoidConcat /// method. char TokenInfo[tok::NUM_TOKENS]; public: TokenConcatenation(Preprocessor &PP); bool AvoidConcat(const Token &PrevPrevTok, const Token &PrevTok, const Token &Tok) const; private: /// IsIdentifierStringPrefix - Return true if the spelling of the token /// is literally 'L', 'u', 'U', or 'u8'. bool IsIdentifierStringPrefix(const Token &Tok) const; }; } // end clang namespace #endif
0
repos/DirectXShaderCompiler/tools/clang/include/clang
repos/DirectXShaderCompiler/tools/clang/include/clang/Lex/MacroInfo.h
//===--- MacroInfo.h - Information about #defined identifiers ---*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// /// /// \file /// \brief Defines the clang::MacroInfo and clang::MacroDirective classes. /// //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_LEX_MACROINFO_H #define LLVM_CLANG_LEX_MACROINFO_H #include "clang/Lex/Token.h" #include "llvm/ADT/ArrayRef.h" #include "llvm/ADT/FoldingSet.h" #include "llvm/ADT/PointerIntPair.h" #include "llvm/ADT/SmallVector.h" #include "llvm/Support/Allocator.h" #include <cassert> namespace clang { class Module; class ModuleMacro; class Preprocessor; /// \brief Encapsulates the data about a macro definition (e.g. its tokens). /// /// There's an instance of this class for every #define. class MacroInfo { //===--------------------------------------------------------------------===// // State set when the macro is defined. /// \brief The location the macro is defined. SourceLocation Location; /// \brief The location of the last token in the macro. SourceLocation EndLocation; /// \brief The list of arguments for a function-like macro. /// /// ArgumentList points to the first of NumArguments pointers. /// /// This can be empty, for, e.g. "#define X()". In a C99-style variadic /// macro, this includes the \c __VA_ARGS__ identifier on the list. IdentifierInfo **ArgumentList; /// \see ArgumentList unsigned NumArguments; /// \brief This is the list of tokens that the macro is defined to. SmallVector<Token, 8> ReplacementTokens; /// \brief Length in characters of the macro definition. mutable unsigned DefinitionLength; mutable bool IsDefinitionLengthCached : 1; /// \brief True if this macro is function-like, false if it is object-like. bool IsFunctionLike : 1; /// \brief True if this macro is of the form "#define X(...)" or /// "#define X(Y,Z,...)". /// /// The __VA_ARGS__ token should be replaced with the contents of "..." in an /// invocation. bool IsC99Varargs : 1; /// \brief True if this macro is of the form "#define X(a...)". /// /// The "a" identifier in the replacement list will be replaced with all /// arguments of the macro starting with the specified one. bool IsGNUVarargs : 1; /// \brief True if this macro requires processing before expansion. /// /// This is the case for builtin macros such as __LINE__, so long as they have /// not been redefined, but not for regular predefined macros from the /// "<built-in>" memory buffer (see Preprocessing::getPredefinesFileID). bool IsBuiltinMacro : 1; /// \brief Whether this macro contains the sequence ", ## __VA_ARGS__" bool HasCommaPasting : 1; //===--------------------------------------------------------------------===// // State that changes as the macro is used. /// \brief True if we have started an expansion of this macro already. /// /// This disables recursive expansion, which would be quite bad for things /// like \#define A A. bool IsDisabled : 1; /// \brief True if this macro is either defined in the main file and has /// been used, or if it is not defined in the main file. /// /// This is used to emit -Wunused-macros diagnostics. bool IsUsed : 1; /// \brief True if this macro can be redefined without emitting a warning. bool IsAllowRedefinitionsWithoutWarning : 1; /// \brief Must warn if the macro is unused at the end of translation unit. bool IsWarnIfUnused : 1; /// \brief Whether this macro info was loaded from an AST file. unsigned FromASTFile : 1; /// \brief Whether this macro was used as header guard. bool UsedForHeaderGuard : 1; // Only the Preprocessor gets to create and destroy these. MacroInfo(SourceLocation DefLoc); ~MacroInfo() = default; public: /// \brief Return the location that the macro was defined at. SourceLocation getDefinitionLoc() const { return Location; } /// \brief Set the location of the last token in the macro. void setDefinitionEndLoc(SourceLocation EndLoc) { EndLocation = EndLoc; } /// \brief Return the location of the last token in the macro. SourceLocation getDefinitionEndLoc() const { return EndLocation; } /// \brief Get length in characters of the macro definition. unsigned getDefinitionLength(SourceManager &SM) const { if (IsDefinitionLengthCached) return DefinitionLength; return getDefinitionLengthSlow(SM); } /// \brief Return true if the specified macro definition is equal to /// this macro in spelling, arguments, and whitespace. /// /// \param Syntactically if true, the macro definitions can be identical even /// if they use different identifiers for the function macro parameters. /// Otherwise the comparison is lexical and this implements the rules in /// C99 6.10.3. bool isIdenticalTo(const MacroInfo &Other, Preprocessor &PP, bool Syntactically) const; /// \brief Set or clear the isBuiltinMacro flag. void setIsBuiltinMacro(bool Val = true) { IsBuiltinMacro = Val; } /// \brief Set the value of the IsUsed flag. void setIsUsed(bool Val) { IsUsed = Val; } /// \brief Set the value of the IsAllowRedefinitionsWithoutWarning flag. void setIsAllowRedefinitionsWithoutWarning(bool Val) { IsAllowRedefinitionsWithoutWarning = Val; } /// \brief Set the value of the IsWarnIfUnused flag. void setIsWarnIfUnused(bool val) { IsWarnIfUnused = val; } /// \brief Set the specified list of identifiers as the argument list for /// this macro. void setArgumentList(IdentifierInfo *const *List, unsigned NumArgs, llvm::BumpPtrAllocator &PPAllocator) { assert(ArgumentList == nullptr && NumArguments == 0 && "Argument list already set!"); if (NumArgs == 0) return; NumArguments = NumArgs; ArgumentList = PPAllocator.Allocate<IdentifierInfo *>(NumArgs); for (unsigned i = 0; i != NumArgs; ++i) ArgumentList[i] = List[i]; } /// Arguments - The list of arguments for a function-like macro. This can be /// empty, for, e.g. "#define X()". typedef IdentifierInfo *const *arg_iterator; bool arg_empty() const { return NumArguments == 0; } arg_iterator arg_begin() const { return ArgumentList; } arg_iterator arg_end() const { return ArgumentList + NumArguments; } unsigned getNumArgs() const { return NumArguments; } ArrayRef<const IdentifierInfo *> args() const { return ArrayRef<const IdentifierInfo *>(ArgumentList, NumArguments); } /// \brief Return the argument number of the specified identifier, /// or -1 if the identifier is not a formal argument identifier. int getArgumentNum(const IdentifierInfo *Arg) const { for (arg_iterator I = arg_begin(), E = arg_end(); I != E; ++I) if (*I == Arg) return I - arg_begin(); return -1; } /// Function/Object-likeness. Keep track of whether this macro has formal /// parameters. void setIsFunctionLike() { IsFunctionLike = true; } bool isFunctionLike() const { return IsFunctionLike; } bool isObjectLike() const { return !IsFunctionLike; } /// Varargs querying methods. This can only be set for function-like macros. void setIsC99Varargs() { IsC99Varargs = true; } void setIsGNUVarargs() { IsGNUVarargs = true; } bool isC99Varargs() const { return IsC99Varargs; } bool isGNUVarargs() const { return IsGNUVarargs; } bool isVariadic() const { return IsC99Varargs | IsGNUVarargs; } /// \brief Return true if this macro requires processing before expansion. /// /// This is true only for builtin macro, such as \__LINE__, whose values /// are not given by fixed textual expansions. Regular predefined macros /// from the "<built-in>" buffer are not reported as builtins by this /// function. bool isBuiltinMacro() const { return IsBuiltinMacro; } bool hasCommaPasting() const { return HasCommaPasting; } void setHasCommaPasting() { HasCommaPasting = true; } /// \brief Return false if this macro is defined in the main file and has /// not yet been used. bool isUsed() const { return IsUsed; } /// \brief Return true if this macro can be redefined without warning. bool isAllowRedefinitionsWithoutWarning() const { return IsAllowRedefinitionsWithoutWarning; } /// \brief Return true if we should emit a warning if the macro is unused. bool isWarnIfUnused() const { return IsWarnIfUnused; } /// \brief Return the number of tokens that this macro expands to. /// unsigned getNumTokens() const { return ReplacementTokens.size(); } const Token &getReplacementToken(unsigned Tok) const { assert(Tok < ReplacementTokens.size() && "Invalid token #"); return ReplacementTokens[Tok]; } typedef SmallVectorImpl<Token>::const_iterator tokens_iterator; tokens_iterator tokens_begin() const { return ReplacementTokens.begin(); } tokens_iterator tokens_end() const { return ReplacementTokens.end(); } bool tokens_empty() const { return ReplacementTokens.empty(); } ArrayRef<Token> tokens() const { return ReplacementTokens; } /// \brief Add the specified token to the replacement text for the macro. void AddTokenToBody(const Token &Tok) { assert( !IsDefinitionLengthCached && "Changing replacement tokens after definition length got calculated"); ReplacementTokens.push_back(Tok); } /// \brief Return true if this macro is enabled. /// /// In other words, that we are not currently in an expansion of this macro. bool isEnabled() const { return !IsDisabled; } void EnableMacro() { assert(IsDisabled && "Cannot enable an already-enabled macro!"); IsDisabled = false; } void DisableMacro() { assert(!IsDisabled && "Cannot disable an already-disabled macro!"); IsDisabled = true; } /// \brief Determine whether this macro info came from an AST file (such as /// a precompiled header or module) rather than having been parsed. bool isFromASTFile() const { return FromASTFile; } /// \brief Determine whether this macro was used for a header guard. bool isUsedForHeaderGuard() const { return UsedForHeaderGuard; } void setUsedForHeaderGuard(bool Val) { UsedForHeaderGuard = Val; } /// \brief Retrieve the global ID of the module that owns this particular /// macro info. unsigned getOwningModuleID() const { if (isFromASTFile()) return *(const unsigned *)(this + 1); return 0; } void dump() const; private: unsigned getDefinitionLengthSlow(SourceManager &SM) const; void setOwningModuleID(unsigned ID) { assert(isFromASTFile()); *(unsigned *)(this + 1) = ID; } friend class Preprocessor; }; class DefMacroDirective; /// \brief Encapsulates changes to the "macros namespace" (the location where /// the macro name became active, the location where it was undefined, etc.). /// /// MacroDirectives, associated with an identifier, are used to model the macro /// history. Usually a macro definition (MacroInfo) is where a macro name /// becomes active (MacroDirective) but #pragma push_macro / pop_macro can /// create additional DefMacroDirectives for the same MacroInfo. class MacroDirective { public: enum Kind { MD_Define, MD_Undefine, MD_Visibility }; protected: /// \brief Previous macro directive for the same identifier, or NULL. MacroDirective *Previous; SourceLocation Loc; /// \brief MacroDirective kind. unsigned MDKind : 2; /// \brief True if the macro directive was loaded from a PCH file. bool IsFromPCH : 1; // Used by VisibilityMacroDirective ----------------------------------------// /// \brief Whether the macro has public visibility (when described in a /// module). bool IsPublic : 1; MacroDirective(Kind K, SourceLocation Loc) : Previous(nullptr), Loc(Loc), MDKind(K), IsFromPCH(false), IsPublic(true) {} public: Kind getKind() const { return Kind(MDKind); } SourceLocation getLocation() const { return Loc; } /// \brief Set previous definition of the macro with the same name. void setPrevious(MacroDirective *Prev) { Previous = Prev; } /// \brief Get previous definition of the macro with the same name. const MacroDirective *getPrevious() const { return Previous; } /// \brief Get previous definition of the macro with the same name. MacroDirective *getPrevious() { return Previous; } /// \brief Return true if the macro directive was loaded from a PCH file. bool isFromPCH() const { return IsFromPCH; } void setIsFromPCH() { IsFromPCH = true; } class DefInfo { DefMacroDirective *DefDirective; SourceLocation UndefLoc; bool IsPublic; public: DefInfo() : DefDirective(nullptr), IsPublic(true) {} DefInfo(DefMacroDirective *DefDirective, SourceLocation UndefLoc, bool isPublic) : DefDirective(DefDirective), UndefLoc(UndefLoc), IsPublic(isPublic) {} const DefMacroDirective *getDirective() const { return DefDirective; } DefMacroDirective *getDirective() { return DefDirective; } inline SourceLocation getLocation() const; inline MacroInfo *getMacroInfo(); const MacroInfo *getMacroInfo() const { return const_cast<DefInfo *>(this)->getMacroInfo(); } SourceLocation getUndefLocation() const { return UndefLoc; } bool isUndefined() const { return UndefLoc.isValid(); } bool isPublic() const { return IsPublic; } bool isValid() const { return DefDirective != nullptr; } bool isInvalid() const { return !isValid(); } explicit operator bool() const { return isValid(); } inline DefInfo getPreviousDefinition(); const DefInfo getPreviousDefinition() const { return const_cast<DefInfo *>(this)->getPreviousDefinition(); } }; /// \brief Traverses the macro directives history and returns the next /// macro definition directive along with info about its undefined location /// (if there is one) and if it is public or private. DefInfo getDefinition(); const DefInfo getDefinition() const { return const_cast<MacroDirective *>(this)->getDefinition(); } bool isDefined() const { if (const DefInfo Def = getDefinition()) return !Def.isUndefined(); return false; } const MacroInfo *getMacroInfo() const { return getDefinition().getMacroInfo(); } MacroInfo *getMacroInfo() { return getDefinition().getMacroInfo(); } /// \brief Find macro definition active in the specified source location. If /// this macro was not defined there, return NULL. const DefInfo findDirectiveAtLoc(SourceLocation L, SourceManager &SM) const; void dump() const; static bool classof(const MacroDirective *) { return true; } }; /// \brief A directive for a defined macro or a macro imported from a module. class DefMacroDirective : public MacroDirective { MacroInfo *Info; public: DefMacroDirective(MacroInfo *MI, SourceLocation Loc) : MacroDirective(MD_Define, Loc), Info(MI) { assert(MI && "MacroInfo is null"); } explicit DefMacroDirective(MacroInfo *MI) : DefMacroDirective(MI, MI->getDefinitionLoc()) {} /// \brief The data for the macro definition. const MacroInfo *getInfo() const { return Info; } MacroInfo *getInfo() { return Info; } static bool classof(const MacroDirective *MD) { return MD->getKind() == MD_Define; } static bool classof(const DefMacroDirective *) { return true; } }; /// \brief A directive for an undefined macro. class UndefMacroDirective : public MacroDirective { public: explicit UndefMacroDirective(SourceLocation UndefLoc) : MacroDirective(MD_Undefine, UndefLoc) { assert(UndefLoc.isValid() && "Invalid UndefLoc!"); } static bool classof(const MacroDirective *MD) { return MD->getKind() == MD_Undefine; } static bool classof(const UndefMacroDirective *) { return true; } }; /// \brief A directive for setting the module visibility of a macro. class VisibilityMacroDirective : public MacroDirective { public: explicit VisibilityMacroDirective(SourceLocation Loc, bool Public) : MacroDirective(MD_Visibility, Loc) { IsPublic = Public; } /// \brief Determine whether this macro is part of the public API of its /// module. bool isPublic() const { return IsPublic; } static bool classof(const MacroDirective *MD) { return MD->getKind() == MD_Visibility; } static bool classof(const VisibilityMacroDirective *) { return true; } }; inline SourceLocation MacroDirective::DefInfo::getLocation() const { if (isInvalid()) return SourceLocation(); return DefDirective->getLocation(); } inline MacroInfo *MacroDirective::DefInfo::getMacroInfo() { if (isInvalid()) return nullptr; return DefDirective->getInfo(); } inline MacroDirective::DefInfo MacroDirective::DefInfo::getPreviousDefinition() { if (isInvalid() || DefDirective->getPrevious() == nullptr) return DefInfo(); return DefDirective->getPrevious()->getDefinition(); } /// \brief Represents a macro directive exported by a module. /// /// There's an instance of this class for every macro #define or #undef that is /// the final directive for a macro name within a module. These entities also /// represent the macro override graph. /// /// These are stored in a FoldingSet in the preprocessor. class ModuleMacro : public llvm::FoldingSetNode { /// The name defined by the macro. IdentifierInfo *II; /// The body of the #define, or nullptr if this is a #undef. MacroInfo *Macro; /// The module that exports this macro. Module *OwningModule; /// The number of module macros that override this one. unsigned NumOverriddenBy; /// The number of modules whose macros are directly overridden by this one. unsigned NumOverrides; // ModuleMacro *OverriddenMacros[NumOverrides]; friend class Preprocessor; ModuleMacro(Module *OwningModule, IdentifierInfo *II, MacroInfo *Macro, ArrayRef<ModuleMacro *> Overrides) : II(II), Macro(Macro), OwningModule(OwningModule), NumOverriddenBy(0), NumOverrides(Overrides.size()) { std::copy(Overrides.begin(), Overrides.end(), reinterpret_cast<ModuleMacro **>(this + 1)); } public: static ModuleMacro *create(Preprocessor &PP, Module *OwningModule, IdentifierInfo *II, MacroInfo *Macro, ArrayRef<ModuleMacro *> Overrides); void Profile(llvm::FoldingSetNodeID &ID) const { return Profile(ID, OwningModule, II); } static void Profile(llvm::FoldingSetNodeID &ID, Module *OwningModule, IdentifierInfo *II) { ID.AddPointer(OwningModule); ID.AddPointer(II); } /// Get the ID of the module that exports this macro. Module *getOwningModule() const { return OwningModule; } /// Get definition for this exported #define, or nullptr if this /// represents a #undef. MacroInfo *getMacroInfo() const { return Macro; } /// Iterators over the overridden module IDs. /// \{ typedef ModuleMacro *const *overrides_iterator; overrides_iterator overrides_begin() const { return reinterpret_cast<overrides_iterator>(this + 1); } overrides_iterator overrides_end() const { return overrides_begin() + NumOverrides; } ArrayRef<ModuleMacro *> overrides() const { return llvm::makeArrayRef(overrides_begin(), overrides_end()); } /// \} /// Get the number of macros that override this one. unsigned getNumOverridingMacros() const { return NumOverriddenBy; } }; /// \brief A description of the current definition of a macro. /// /// The definition of a macro comprises a set of (at least one) defining /// entities, which are either local MacroDirectives or imported ModuleMacros. class MacroDefinition { llvm::PointerIntPair<DefMacroDirective *, 1, bool> LatestLocalAndAmbiguous; ArrayRef<ModuleMacro *> ModuleMacros; public: MacroDefinition() : LatestLocalAndAmbiguous(), ModuleMacros() {} MacroDefinition(DefMacroDirective *MD, ArrayRef<ModuleMacro *> MMs, bool IsAmbiguous) : LatestLocalAndAmbiguous(MD, IsAmbiguous), ModuleMacros(MMs) {} /// \brief Determine whether there is a definition of this macro. explicit operator bool() const { return getLocalDirective() || !ModuleMacros.empty(); } /// \brief Get the MacroInfo that should be used for this definition. MacroInfo *getMacroInfo() const { if (!ModuleMacros.empty()) return ModuleMacros.back()->getMacroInfo(); if (auto *MD = getLocalDirective()) return MD->getMacroInfo(); return nullptr; } /// \brief \c true if the definition is ambiguous, \c false otherwise. bool isAmbiguous() const { return LatestLocalAndAmbiguous.getInt(); } /// \brief Get the latest non-imported, non-\#undef'd macro definition /// for this macro. DefMacroDirective *getLocalDirective() const { return LatestLocalAndAmbiguous.getPointer(); } /// \brief Get the active module macros for this macro. ArrayRef<ModuleMacro *> getModuleMacros() const { return ModuleMacros; } template <typename Fn> void forAllDefinitions(Fn F) const { if (auto *MD = getLocalDirective()) F(MD->getMacroInfo()); for (auto *MM : getModuleMacros()) F(MM->getMacroInfo()); } }; } // end namespace clang #endif
0
repos/DirectXShaderCompiler/tools/clang/include/clang
repos/DirectXShaderCompiler/tools/clang/include/clang/Lex/Lexer.h
//===--- Lexer.h - C Language Family Lexer ----------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines the Lexer interface. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_LEX_LEXER_H #define LLVM_CLANG_LEX_LEXER_H #include "clang/Basic/LangOptions.h" #include "clang/Lex/PreprocessorLexer.h" #include "llvm/ADT/SmallVector.h" #include <cassert> #include <string> namespace clang { class DiagnosticsEngine; class SourceManager; class Preprocessor; class DiagnosticBuilder; /// ConflictMarkerKind - Kinds of conflict marker which the lexer might be /// recovering from. enum ConflictMarkerKind { /// Not within a conflict marker. CMK_None, /// A normal or diff3 conflict marker, initiated by at least 7 "<"s, /// separated by at least 7 "="s or "|"s, and terminated by at least 7 ">"s. CMK_Normal, /// A Perforce-style conflict marker, initiated by 4 ">"s, /// separated by 4 "="s, and terminated by 4 "<"s. CMK_Perforce }; /// Lexer - This provides a simple interface that turns a text buffer into a /// stream of tokens. This provides no support for file reading or buffering, /// or buffering/seeking of tokens, only forward lexing is supported. It relies /// on the specified Preprocessor object to handle preprocessor directives, etc. class Lexer : public PreprocessorLexer { void anchor() override; //===--------------------------------------------------------------------===// // Constant configuration values for this lexer. const char *BufferStart; // Start of the buffer. const char *BufferEnd; // End of the buffer. SourceLocation FileLoc; // Location for start of file. LangOptions LangOpts; // LangOpts enabled by this language (cache). bool Is_PragmaLexer; // True if lexer for _Pragma handling. //===--------------------------------------------------------------------===// // Context-specific lexing flags set by the preprocessor. // /// ExtendedTokenMode - The lexer can optionally keep comments and whitespace /// and return them as tokens. This is used for -C and -CC modes, and /// whitespace preservation can be useful for some clients that want to lex /// the file in raw mode and get every character from the file. /// /// When this is set to 2 it returns comments and whitespace. When set to 1 /// it returns comments, when it is set to 0 it returns normal tokens only. unsigned char ExtendedTokenMode; //===--------------------------------------------------------------------===// // Context that changes as the file is lexed. // NOTE: any state that mutates when in raw mode must have save/restore code // in Lexer::isNextPPTokenLParen. // BufferPtr - Current pointer into the buffer. This is the next character // to be lexed. const char *BufferPtr; // IsAtStartOfLine - True if the next lexed token should get the "start of // line" flag set on it. bool IsAtStartOfLine; bool IsAtPhysicalStartOfLine; bool HasLeadingSpace; bool HasLeadingEmptyMacro; // CurrentConflictMarkerState - The kind of conflict marker we are handling. ConflictMarkerKind CurrentConflictMarkerState; Lexer(const Lexer &) = delete; void operator=(const Lexer &) = delete; friend class Preprocessor; void InitLexer(const char *BufStart, const char *BufPtr, const char *BufEnd); public: /// Lexer constructor - Create a new lexer object for the specified buffer /// with the specified preprocessor managing the lexing process. This lexer /// assumes that the associated file buffer and Preprocessor objects will /// outlive it, so it doesn't take ownership of either of them. Lexer(FileID FID, const llvm::MemoryBuffer *InputBuffer, Preprocessor &PP); /// Lexer constructor - Create a new raw lexer object. This object is only /// suitable for calls to 'LexFromRawLexer'. This lexer assumes that the /// text range will outlive it, so it doesn't take ownership of it. Lexer(SourceLocation FileLoc, const LangOptions &LangOpts, const char *BufStart, const char *BufPtr, const char *BufEnd); /// Lexer constructor - Create a new raw lexer object. This object is only /// suitable for calls to 'LexFromRawLexer'. This lexer assumes that the /// text range will outlive it, so it doesn't take ownership of it. Lexer(FileID FID, const llvm::MemoryBuffer *InputBuffer, const SourceManager &SM, const LangOptions &LangOpts); /// Create_PragmaLexer: Lexer constructor - Create a new lexer object for /// _Pragma expansion. This has a variety of magic semantics that this method /// sets up. It returns a new'd Lexer that must be delete'd when done. static Lexer *Create_PragmaLexer(SourceLocation SpellingLoc, SourceLocation ExpansionLocStart, SourceLocation ExpansionLocEnd, unsigned TokLen, Preprocessor &PP); /// getLangOpts - Return the language features currently enabled. /// NOTE: this lexer modifies features as a file is parsed! const LangOptions &getLangOpts() const { return LangOpts; } /// getFileLoc - Return the File Location for the file we are lexing out of. /// The physical location encodes the location where the characters come from, /// the virtual location encodes where we should *claim* the characters came /// from. Currently this is only used by _Pragma handling. SourceLocation getFileLoc() const { return FileLoc; } private: /// Lex - Return the next token in the file. If this is the end of file, it /// return the tok::eof token. This implicitly involves the preprocessor. bool Lex(Token &Result); public: /// isPragmaLexer - Returns true if this Lexer is being used to lex a pragma. bool isPragmaLexer() const { return Is_PragmaLexer; } private: /// IndirectLex - An indirect call to 'Lex' that can be invoked via /// the PreprocessorLexer interface. void IndirectLex(Token &Result) override { Lex(Result); } public: /// LexFromRawLexer - Lex a token from a designated raw lexer (one with no /// associated preprocessor object. Return true if the 'next character to /// read' pointer points at the end of the lexer buffer, false otherwise. bool LexFromRawLexer(Token &Result) { assert(LexingRawMode && "Not already in raw mode!"); Lex(Result); // Note that lexing to the end of the buffer doesn't implicitly delete the // lexer when in raw mode. return BufferPtr == BufferEnd; } /// isKeepWhitespaceMode - Return true if the lexer should return tokens for /// every character in the file, including whitespace and comments. This /// should only be used in raw mode, as the preprocessor is not prepared to /// deal with the excess tokens. bool isKeepWhitespaceMode() const { return ExtendedTokenMode > 1; } /// SetKeepWhitespaceMode - This method lets clients enable or disable /// whitespace retention mode. void SetKeepWhitespaceMode(bool Val) { assert((!Val || LexingRawMode || LangOpts.TraditionalCPP) && "Can only retain whitespace in raw mode or -traditional-cpp"); ExtendedTokenMode = Val ? 2 : 0; } /// inKeepCommentMode - Return true if the lexer should return comments as /// tokens. bool inKeepCommentMode() const { return ExtendedTokenMode > 0; } /// SetCommentRetentionMode - Change the comment retention mode of the lexer /// to the specified mode. This is really only useful when lexing in raw /// mode, because otherwise the lexer needs to manage this. void SetCommentRetentionState(bool Mode) { assert(!isKeepWhitespaceMode() && "Can't play with comment retention state when retaining whitespace"); ExtendedTokenMode = Mode ? 1 : 0; } /// Sets the extended token mode back to its initial value, according to the /// language options and preprocessor. This controls whether the lexer /// produces comment and whitespace tokens. /// /// This requires the lexer to have an associated preprocessor. A standalone /// lexer has nothing to reset to. void resetExtendedTokenMode(); /// Gets source code buffer. StringRef getBuffer() const { return StringRef(BufferStart, BufferEnd - BufferStart); } /// ReadToEndOfLine - Read the rest of the current preprocessor line as an /// uninterpreted string. This switches the lexer out of directive mode. void ReadToEndOfLine(SmallVectorImpl<char> *Result = nullptr); /// Diag - Forwarding function for diagnostics. This translate a source /// position in the current buffer into a SourceLocation object for rendering. DiagnosticBuilder Diag(const char *Loc, unsigned DiagID) const; /// getSourceLocation - Return a source location identifier for the specified /// offset in the current file. SourceLocation getSourceLocation(const char *Loc, unsigned TokLen = 1) const; /// getSourceLocation - Return a source location for the next character in /// the current file. SourceLocation getSourceLocation() override { return getSourceLocation(BufferPtr); } /// \brief Return the current location in the buffer. const char *getBufferLocation() const { return BufferPtr; } /// Stringify - Convert the specified string into a C string by escaping '\' /// and " characters. This does not add surrounding ""'s to the string. /// If Charify is true, this escapes the ' character instead of ". static std::string Stringify(StringRef Str, bool Charify = false); /// Stringify - Convert the specified string into a C string by escaping '\' /// and " characters. This does not add surrounding ""'s to the string. static void Stringify(SmallVectorImpl<char> &Str); /// getSpelling - This method is used to get the spelling of a token into a /// preallocated buffer, instead of as an std::string. The caller is required /// to allocate enough space for the token, which is guaranteed to be at least /// Tok.getLength() bytes long. The length of the actual result is returned. /// /// Note that this method may do two possible things: it may either fill in /// the buffer specified with characters, or it may *change the input pointer* /// to point to a constant buffer with the data already in it (avoiding a /// copy). The caller is not allowed to modify the returned buffer pointer /// if an internal buffer is returned. static unsigned getSpelling(const Token &Tok, const char *&Buffer, const SourceManager &SourceMgr, const LangOptions &LangOpts, bool *Invalid = nullptr); /// getSpelling() - Return the 'spelling' of the Tok token. The spelling of a /// token is the characters used to represent the token in the source file /// after trigraph expansion and escaped-newline folding. In particular, this /// wants to get the true, uncanonicalized, spelling of things like digraphs /// UCNs, etc. static std::string getSpelling(const Token &Tok, const SourceManager &SourceMgr, const LangOptions &LangOpts, bool *Invalid = nullptr); /// getSpelling - This method is used to get the spelling of the /// token at the given source location. If, as is usually true, it /// is not necessary to copy any data, then the returned string may /// not point into the provided buffer. /// /// This method lexes at the expansion depth of the given /// location and does not jump to the expansion or spelling /// location. static StringRef getSpelling(SourceLocation loc, SmallVectorImpl<char> &buffer, const SourceManager &SourceMgr, const LangOptions &LangOpts, bool *invalid = nullptr); /// MeasureTokenLength - Relex the token at the specified location and return /// its length in bytes in the input file. If the token needs cleaning (e.g. /// includes a trigraph or an escaped newline) then this count includes bytes /// that are part of that. static unsigned MeasureTokenLength(SourceLocation Loc, const SourceManager &SM, const LangOptions &LangOpts); /// \brief Relex the token at the specified location. /// \returns true if there was a failure, false on success. static bool getRawToken(SourceLocation Loc, Token &Result, const SourceManager &SM, const LangOptions &LangOpts, bool IgnoreWhiteSpace = false); /// \brief Given a location any where in a source buffer, find the location /// that corresponds to the beginning of the token in which the original /// source location lands. static SourceLocation GetBeginningOfToken(SourceLocation Loc, const SourceManager &SM, const LangOptions &LangOpts); /// AdvanceToTokenCharacter - If the current SourceLocation specifies a /// location at the start of a token, return a new location that specifies a /// character within the token. This handles trigraphs and escaped newlines. static SourceLocation AdvanceToTokenCharacter(SourceLocation TokStart, unsigned Character, const SourceManager &SM, const LangOptions &LangOpts); /// \brief Computes the source location just past the end of the /// token at this source location. /// /// This routine can be used to produce a source location that /// points just past the end of the token referenced by \p Loc, and /// is generally used when a diagnostic needs to point just after a /// token where it expected something different that it received. If /// the returned source location would not be meaningful (e.g., if /// it points into a macro), this routine returns an invalid /// source location. /// /// \param Offset an offset from the end of the token, where the source /// location should refer to. The default offset (0) produces a source /// location pointing just past the end of the token; an offset of 1 produces /// a source location pointing to the last character in the token, etc. static SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset, const SourceManager &SM, const LangOptions &LangOpts); /// \brief Given a token range, produce a corresponding CharSourceRange that /// is not a token range. This allows the source range to be used by /// components that don't have access to the lexer and thus can't find the /// end of the range for themselves. static CharSourceRange getAsCharRange(SourceRange Range, const SourceManager &SM, const LangOptions &LangOpts) { SourceLocation End = getLocForEndOfToken(Range.getEnd(), 0, SM, LangOpts); return End.isInvalid() ? CharSourceRange() : CharSourceRange::getCharRange( Range.getBegin(), End.getLocWithOffset(-1)); } static CharSourceRange getAsCharRange(CharSourceRange Range, const SourceManager &SM, const LangOptions &LangOpts) { return Range.isTokenRange() ? getAsCharRange(Range.getAsRange(), SM, LangOpts) : Range; } /// \brief Returns true if the given MacroID location points at the first /// token of the macro expansion. /// /// \param MacroBegin If non-null and function returns true, it is set to /// begin location of the macro. static bool isAtStartOfMacroExpansion(SourceLocation loc, const SourceManager &SM, const LangOptions &LangOpts, SourceLocation *MacroBegin = nullptr); /// \brief Returns true if the given MacroID location points at the last /// token of the macro expansion. /// /// \param MacroEnd If non-null and function returns true, it is set to /// end location of the macro. static bool isAtEndOfMacroExpansion(SourceLocation loc, const SourceManager &SM, const LangOptions &LangOpts, SourceLocation *MacroEnd = nullptr); /// \brief Accepts a range and returns a character range with file locations. /// /// Returns a null range if a part of the range resides inside a macro /// expansion or the range does not reside on the same FileID. /// /// This function is trying to deal with macros and return a range based on /// file locations. The cases where it can successfully handle macros are: /// /// -begin or end range lies at the start or end of a macro expansion, in /// which case the location will be set to the expansion point, e.g: /// \#define M 1 2 /// a M /// If you have a range [a, 2] (where 2 came from the macro), the function /// will return a range for "a M" /// if you have range [a, 1], the function will fail because the range /// overlaps with only a part of the macro /// /// -The macro is a function macro and the range can be mapped to the macro /// arguments, e.g: /// \#define M 1 2 /// \#define FM(x) x /// FM(a b M) /// if you have range [b, 2], the function will return the file range "b M" /// inside the macro arguments. /// if you have range [a, 2], the function will return the file range /// "FM(a b M)" since the range includes all of the macro expansion. static CharSourceRange makeFileCharRange(CharSourceRange Range, const SourceManager &SM, const LangOptions &LangOpts); /// \brief Returns a string for the source that the range encompasses. static StringRef getSourceText(CharSourceRange Range, const SourceManager &SM, const LangOptions &LangOpts, bool *Invalid = nullptr); /// \brief Retrieve the name of the immediate macro expansion. /// /// This routine starts from a source location, and finds the name of the macro /// responsible for its immediate expansion. It looks through any intervening /// macro argument expansions to compute this. It returns a StringRef which /// refers to the SourceManager-owned buffer of the source where that macro /// name is spelled. Thus, the result shouldn't out-live that SourceManager. static StringRef getImmediateMacroName(SourceLocation Loc, const SourceManager &SM, const LangOptions &LangOpts); /// \brief Compute the preamble of the given file. /// /// The preamble of a file contains the initial comments, include directives, /// and other preprocessor directives that occur before the code in this /// particular file actually begins. The preamble of the main source file is /// a potential prefix header. /// /// \param Buffer The memory buffer containing the file's contents. /// /// \param MaxLines If non-zero, restrict the length of the preamble /// to fewer than this number of lines. /// /// \returns The offset into the file where the preamble ends and the rest /// of the file begins along with a boolean value indicating whether /// the preamble ends at the beginning of a new line. static std::pair<unsigned, bool> ComputePreamble(StringRef Buffer, const LangOptions &LangOpts, unsigned MaxLines = 0); /// \brief Checks that the given token is the first token that occurs after /// the given location (this excludes comments and whitespace). Returns the /// location immediately after the specified token. If the token is not found /// or the location is inside a macro, the returned source location will be /// invalid. static SourceLocation findLocationAfterToken(SourceLocation loc, tok::TokenKind TKind, const SourceManager &SM, const LangOptions &LangOpts, bool SkipTrailingWhitespaceAndNewLine); /// \brief Returns true if the given character could appear in an identifier. static bool isIdentifierBodyChar(char c, const LangOptions &LangOpts); /// getCharAndSizeNoWarn - Like the getCharAndSize method, but does not ever /// emit a warning. static inline char getCharAndSizeNoWarn(const char *Ptr, unsigned &Size, const LangOptions &LangOpts) { // If this is not a trigraph and not a UCN or escaped newline, return // quickly. if (isObviouslySimpleCharacter(Ptr[0])) { Size = 1; return *Ptr; } Size = 0; return getCharAndSizeSlowNoWarn(Ptr, Size, LangOpts); } //===--------------------------------------------------------------------===// // Internal implementation interfaces. private: /// LexTokenInternal - Internal interface to lex a preprocessing token. Called /// by Lex. /// bool LexTokenInternal(Token &Result, bool TokAtPhysicalStartOfLine); bool CheckUnicodeWhitespace(Token &Result, uint32_t C, const char *CurPtr); /// Given that a token begins with the Unicode character \p C, figure out /// what kind of token it is and dispatch to the appropriate lexing helper /// function. bool LexUnicode(Token &Result, uint32_t C, const char *CurPtr); /// FormTokenWithChars - When we lex a token, we have identified a span /// starting at BufferPtr, going to TokEnd that forms the token. This method /// takes that range and assigns it to the token as its location and size. In /// addition, since tokens cannot overlap, this also updates BufferPtr to be /// TokEnd. void FormTokenWithChars(Token &Result, const char *TokEnd, tok::TokenKind Kind) { unsigned TokLen = TokEnd-BufferPtr; Result.setLength(TokLen); Result.setLocation(getSourceLocation(BufferPtr, TokLen)); Result.setKind(Kind); BufferPtr = TokEnd; } /// isNextPPTokenLParen - Return 1 if the next unexpanded token will return a /// tok::l_paren token, 0 if it is something else and 2 if there are no more /// tokens in the buffer controlled by this lexer. unsigned isNextPPTokenLParen(); //===--------------------------------------------------------------------===// // Lexer character reading interfaces. // This lexer is built on two interfaces for reading characters, both of which // automatically provide phase 1/2 translation. getAndAdvanceChar is used // when we know that we will be reading a character from the input buffer and // that this character will be part of the result token. This occurs in (f.e.) // string processing, because we know we need to read until we find the // closing '"' character. // // The second interface is the combination of getCharAndSize with // ConsumeChar. getCharAndSize reads a phase 1/2 translated character, // returning it and its size. If the lexer decides that this character is // part of the current token, it calls ConsumeChar on it. This two stage // approach allows us to emit diagnostics for characters (e.g. warnings about // trigraphs), knowing that they only are emitted if the character is // consumed. /// isObviouslySimpleCharacter - Return true if the specified character is /// obviously the same in translation phase 1 and translation phase 3. This /// can return false for characters that end up being the same, but it will /// never return true for something that needs to be mapped. static bool isObviouslySimpleCharacter(char C) { return C != '?' && C != '\\'; } /// getAndAdvanceChar - Read a single 'character' from the specified buffer, /// advance over it, and return it. This is tricky in several cases. Here we /// just handle the trivial case and fall-back to the non-inlined /// getCharAndSizeSlow method to handle the hard case. inline char getAndAdvanceChar(const char *&Ptr, Token &Tok) { // If this is not a trigraph and not a UCN or escaped newline, return // quickly. if (isObviouslySimpleCharacter(Ptr[0])) return *Ptr++; unsigned Size = 0; char C = getCharAndSizeSlow(Ptr, Size, &Tok); Ptr += Size; return C; } /// ConsumeChar - When a character (identified by getCharAndSize) is consumed /// and added to a given token, check to see if there are diagnostics that /// need to be emitted or flags that need to be set on the token. If so, do /// it. const char *ConsumeChar(const char *Ptr, unsigned Size, Token &Tok) { // Normal case, we consumed exactly one token. Just return it. if (Size == 1) return Ptr+Size; // Otherwise, re-lex the character with a current token, allowing // diagnostics to be emitted and flags to be set. Size = 0; getCharAndSizeSlow(Ptr, Size, &Tok); return Ptr+Size; } /// getCharAndSize - Peek a single 'character' from the specified buffer, /// get its size, and return it. This is tricky in several cases. Here we /// just handle the trivial case and fall-back to the non-inlined /// getCharAndSizeSlow method to handle the hard case. inline char getCharAndSize(const char *Ptr, unsigned &Size) { // If this is not a trigraph and not a UCN or escaped newline, return // quickly. if (isObviouslySimpleCharacter(Ptr[0])) { Size = 1; return *Ptr; } Size = 0; return getCharAndSizeSlow(Ptr, Size); } /// getCharAndSizeSlow - Handle the slow/uncommon case of the getCharAndSize /// method. char getCharAndSizeSlow(const char *Ptr, unsigned &Size, Token *Tok = nullptr); /// getEscapedNewLineSize - Return the size of the specified escaped newline, /// or 0 if it is not an escaped newline. P[-1] is known to be a "\" on entry /// to this function. static unsigned getEscapedNewLineSize(const char *P); /// SkipEscapedNewLines - If P points to an escaped newline (or a series of /// them), skip over them and return the first non-escaped-newline found, /// otherwise return P. static const char *SkipEscapedNewLines(const char *P); /// getCharAndSizeSlowNoWarn - Same as getCharAndSizeSlow, but never emits a /// diagnostic. static char getCharAndSizeSlowNoWarn(const char *Ptr, unsigned &Size, const LangOptions &LangOpts); //===--------------------------------------------------------------------===// // Other lexer functions. void SkipBytes(unsigned Bytes, bool StartOfLine); void PropagateLineStartLeadingSpaceInfo(Token &Result); const char *LexUDSuffix(Token &Result, const char *CurPtr, bool IsStringLiteral); // Helper functions to lex the remainder of a token of the specific type. bool LexIdentifier (Token &Result, const char *CurPtr); bool LexNumericConstant (Token &Result, const char *CurPtr); bool LexNumericConstant (Token &Result, const char *CurPtr, unsigned Periods); // HLSL Change bool LexStringLiteral (Token &Result, const char *CurPtr, tok::TokenKind Kind); bool LexRawStringLiteral (Token &Result, const char *CurPtr, tok::TokenKind Kind); bool LexAngledStringLiteral(Token &Result, const char *CurPtr); bool LexCharConstant (Token &Result, const char *CurPtr, tok::TokenKind Kind); bool LexEndOfFile (Token &Result, const char *CurPtr); bool SkipWhitespace (Token &Result, const char *CurPtr, bool &TokAtPhysicalStartOfLine); bool SkipLineComment (Token &Result, const char *CurPtr, bool &TokAtPhysicalStartOfLine); bool SkipBlockComment (Token &Result, const char *CurPtr, bool &TokAtPhysicalStartOfLine); bool SaveLineComment (Token &Result, const char *CurPtr); bool IsStartOfConflictMarker(const char *CurPtr); bool HandleEndOfConflictMarker(const char *CurPtr); bool isCodeCompletionPoint(const char *CurPtr) const; void cutOffLexing() { BufferPtr = BufferEnd; } bool isHexaLiteral(const char *Start, const LangOptions &LangOpts); /// Read a universal character name. /// /// \param CurPtr The position in the source buffer after the initial '\'. /// If the UCN is syntactically well-formed (but not necessarily /// valid), this parameter will be updated to point to the /// character after the UCN. /// \param SlashLoc The position in the source buffer of the '\'. /// \param Tok The token being formed. Pass \c NULL to suppress diagnostics /// and handle token formation in the caller. /// /// \return The Unicode codepoint specified by the UCN, or 0 if the UCN is /// invalid. uint32_t tryReadUCN(const char *&CurPtr, const char *SlashLoc, Token *Tok); /// \brief Try to consume a UCN as part of an identifier at the current /// location. /// \param CurPtr Initially points to the range of characters in the source /// buffer containing the '\'. Updated to point past the end of /// the UCN on success. /// \param Size The number of characters occupied by the '\' (including /// trigraphs and escaped newlines). /// \param Result The token being produced. Marked as containing a UCN on /// success. /// \return \c true if a UCN was lexed and it produced an acceptable /// identifier character, \c false otherwise. bool tryConsumeIdentifierUCN(const char *&CurPtr, unsigned Size, Token &Result); /// \brief Try to consume an identifier character encoded in UTF-8. /// \param CurPtr Points to the start of the (potential) UTF-8 code unit /// sequence. On success, updated to point past the end of it. /// \return \c true if a UTF-8 sequence mapping to an acceptable identifier /// character was lexed, \c false otherwise. bool tryConsumeIdentifierUTF8Char(const char *&CurPtr); }; } // end namespace clang #endif
0
repos/DirectXShaderCompiler/tools/clang/include/clang
repos/DirectXShaderCompiler/tools/clang/include/clang/Lex/CodeCompletionHandler.h
//===--- CodeCompletionHandler.h - Preprocessor code completion -*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines the CodeCompletionHandler interface, which provides // code-completion callbacks for the preprocessor. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_LEX_CODECOMPLETIONHANDLER_H #define LLVM_CLANG_LEX_CODECOMPLETIONHANDLER_H namespace clang { class IdentifierInfo; class MacroInfo; /// \brief Callback handler that receives notifications when performing code /// completion within the preprocessor. class CodeCompletionHandler { public: virtual ~CodeCompletionHandler(); /// \brief Callback invoked when performing code completion for a preprocessor /// directive. /// /// This callback will be invoked when the preprocessor processes a '#' at the /// start of a line, followed by the code-completion token. /// /// \param InConditional Whether we're inside a preprocessor conditional /// already. virtual void CodeCompleteDirective(bool InConditional) { } /// \brief Callback invoked when performing code completion within a block of /// code that was excluded due to preprocessor conditionals. virtual void CodeCompleteInConditionalExclusion() { } /// \brief Callback invoked when performing code completion in a context /// where the name of a macro is expected. /// /// \param IsDefinition Whether this is the definition of a macro, e.g., /// in a \#define. virtual void CodeCompleteMacroName(bool IsDefinition) { } /// \brief Callback invoked when performing code completion in a preprocessor /// expression, such as the condition of an \#if or \#elif directive. virtual void CodeCompletePreprocessorExpression() { } /// \brief Callback invoked when performing code completion inside a /// function-like macro argument. /// /// There will be another callback invocation after the macro arguments are /// parsed, so this callback should generally be used to note that the next /// callback is invoked inside a macro argument. virtual void CodeCompleteMacroArgument(IdentifierInfo *Macro, MacroInfo *MacroInfo, unsigned ArgumentIndex) { } /// \brief Callback invoked when performing code completion in a part of the /// file where we expect natural language, e.g., a comment, string, or /// \#error directive. virtual void CodeCompleteNaturalLanguage() { } }; } #endif // LLVM_CLANG_LEX_CODECOMPLETIONHANDLER_H
0
repos/DirectXShaderCompiler/tools/clang/include/clang
repos/DirectXShaderCompiler/tools/clang/include/clang/Lex/DirectoryLookup.h
//===--- DirectoryLookup.h - Info for searching for headers -----*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines the DirectoryLookup interface. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_LEX_DIRECTORYLOOKUP_H #define LLVM_CLANG_LEX_DIRECTORYLOOKUP_H #include "clang/Basic/LLVM.h" #include "clang/Basic/SourceManager.h" #include "clang/Lex/ModuleMap.h" namespace clang { class HeaderMap; class DirectoryEntry; class FileEntry; class HeaderSearch; class Module; /// DirectoryLookup - This class represents one entry in the search list that /// specifies the search order for directories in \#include directives. It /// represents either a directory, a framework, or a headermap. /// class DirectoryLookup { public: enum LookupType_t { LT_NormalDir, LT_Framework, LT_HeaderMap }; private: union { // This union is discriminated by isHeaderMap. /// Dir - This is the actual directory that we're referring to for a normal /// directory or a framework. const DirectoryEntry *Dir; /// Map - This is the HeaderMap if this is a headermap lookup. /// const HeaderMap *Map; } u; /// DirCharacteristic - The type of directory this is: this is an instance of /// SrcMgr::CharacteristicKind. unsigned DirCharacteristic : 2; /// LookupType - This indicates whether this DirectoryLookup object is a /// normal directory, a framework, or a headermap. unsigned LookupType : 2; /// \brief Whether this is a header map used when building a framework. unsigned IsIndexHeaderMap : 1; /// \brief Whether we've performed an exhaustive search for module maps /// within the subdirectories of this directory. unsigned SearchedAllModuleMaps : 1; public: /// DirectoryLookup ctor - Note that this ctor *does not take ownership* of /// 'dir'. DirectoryLookup(const DirectoryEntry *dir, SrcMgr::CharacteristicKind DT, bool isFramework) : DirCharacteristic(DT), LookupType(isFramework ? LT_Framework : LT_NormalDir), IsIndexHeaderMap(false), SearchedAllModuleMaps(false) { u.Dir = dir; } /// DirectoryLookup ctor - Note that this ctor *does not take ownership* of /// 'map'. DirectoryLookup(const HeaderMap *map, SrcMgr::CharacteristicKind DT, bool isIndexHeaderMap) : DirCharacteristic(DT), LookupType(LT_HeaderMap), IsIndexHeaderMap(isIndexHeaderMap), SearchedAllModuleMaps(false) { u.Map = map; } /// getLookupType - Return the kind of directory lookup that this is: either a /// normal directory, a framework path, or a HeaderMap. LookupType_t getLookupType() const { return (LookupType_t)LookupType; } /// getName - Return the directory or filename corresponding to this lookup /// object. const char *getName() const; /// getDir - Return the directory that this entry refers to. /// const DirectoryEntry *getDir() const { return isNormalDir() ? u.Dir : nullptr; } /// getFrameworkDir - Return the directory that this framework refers to. /// const DirectoryEntry *getFrameworkDir() const { return isFramework() ? u.Dir : nullptr; } /// getHeaderMap - Return the directory that this entry refers to. /// const HeaderMap *getHeaderMap() const { return isHeaderMap() ? u.Map : nullptr; } /// isNormalDir - Return true if this is a normal directory, not a header map. bool isNormalDir() const { return getLookupType() == LT_NormalDir; } /// isFramework - True if this is a framework directory. /// bool isFramework() const { return getLookupType() == LT_Framework; } /// isHeaderMap - Return true if this is a header map, not a normal directory. bool isHeaderMap() const { return getLookupType() == LT_HeaderMap; } /// \brief Determine whether we have already searched this entire /// directory for module maps. bool haveSearchedAllModuleMaps() const { return SearchedAllModuleMaps; } /// \brief Specify whether we have already searched all of the subdirectories /// for module maps. void setSearchedAllModuleMaps(bool SAMM) { SearchedAllModuleMaps = SAMM; } /// DirCharacteristic - The type of directory this is, one of the DirType enum /// values. SrcMgr::CharacteristicKind getDirCharacteristic() const { return (SrcMgr::CharacteristicKind)DirCharacteristic; } /// \brief Whether this describes a system header directory. bool isSystemHeaderDirectory() const { return getDirCharacteristic() != SrcMgr::C_User; } /// \brief Whether this header map is building a framework or not. bool isIndexHeaderMap() const { return isHeaderMap() && IsIndexHeaderMap; } /// LookupFile - Lookup the specified file in this search path, returning it /// if it exists or returning null if not. /// /// \param Filename The file to look up relative to the search paths. /// /// \param HS The header search instance to search with. /// /// \param SearchPath If not NULL, will be set to the search path relative /// to which the file was found. /// /// \param RelativePath If not NULL, will be set to the path relative to /// SearchPath at which the file was found. This only differs from the /// Filename for framework includes. /// /// \param SuggestedModule If non-null, and the file found is semantically /// part of a known module, this will be set to the module that should /// be imported instead of preprocessing/parsing the file found. /// /// \param [out] InUserSpecifiedSystemFramework If the file is found, /// set to true if the file is located in a framework that has been /// user-specified to be treated as a system framework. /// /// \param [out] MappedName if this is a headermap which maps the filename to /// a framework include ("Foo.h" -> "Foo/Foo.h"), set the new name to this /// vector and point Filename to it. const FileEntry *LookupFile(StringRef &Filename, HeaderSearch &HS, SmallVectorImpl<char> *SearchPath, SmallVectorImpl<char> *RelativePath, ModuleMap::KnownHeader *SuggestedModule, bool &InUserSpecifiedSystemFramework, bool &HasBeenMapped, SmallVectorImpl<char> &MappedName) const; private: const FileEntry *DoFrameworkLookup( StringRef Filename, HeaderSearch &HS, SmallVectorImpl<char> *SearchPath, SmallVectorImpl<char> *RelativePath, ModuleMap::KnownHeader *SuggestedModule, bool &InUserSpecifiedSystemHeader) const; }; } // end namespace clang #endif
0
repos/DirectXShaderCompiler/tools/clang/include/clang
repos/DirectXShaderCompiler/tools/clang/include/clang/Lex/ModuleLoader.h
//===--- ModuleLoader.h - Module Loader Interface ---------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines the ModuleLoader interface, which is responsible for // loading named modules. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_LEX_MODULELOADER_H #define LLVM_CLANG_LEX_MODULELOADER_H #include "clang/Basic/Module.h" #include "clang/Basic/SourceLocation.h" #include "llvm/ADT/ArrayRef.h" #include "llvm/ADT/PointerIntPair.h" namespace clang { class GlobalModuleIndex; class IdentifierInfo; class Module; /// \brief A sequence of identifier/location pairs used to describe a particular /// module or submodule, e.g., std.vector. typedef ArrayRef<std::pair<IdentifierInfo *, SourceLocation> > ModuleIdPath; /// \brief Describes the result of attempting to load a module. class ModuleLoadResult { llvm::PointerIntPair<Module *, 1, bool> Storage; public: ModuleLoadResult() : Storage() { } ModuleLoadResult(Module *mod, bool missingExpected) : Storage(mod, missingExpected) { } operator Module *() const { return Storage.getPointer(); } /// \brief Determines whether the module, which failed to load, was /// actually a submodule that we expected to see (based on implying the /// submodule from header structure), but didn't materialize in the actual /// module. bool isMissingExpected() const { return Storage.getInt(); } }; /// \brief Abstract interface for a module loader. /// /// This abstract interface describes a module loader, which is responsible /// for resolving a module name (e.g., "std") to an actual module file, and /// then loading that module. class ModuleLoader { // Building a module if true. bool BuildingModule; public: explicit ModuleLoader(bool BuildingModule = false) : BuildingModule(BuildingModule), HadFatalFailure(false) {} virtual ~ModuleLoader(); /// \brief Returns true if this instance is building a module. bool buildingModule() const { return BuildingModule; } /// \brief Flag indicating whether this instance is building a module. void setBuildingModule(bool BuildingModuleFlag) { BuildingModule = BuildingModuleFlag; } /// \brief Attempt to load the given module. /// /// This routine attempts to load the module described by the given /// parameters. /// /// \param ImportLoc The location of the 'import' keyword. /// /// \param Path The identifiers (and their locations) of the module /// "path", e.g., "std.vector" would be split into "std" and "vector". /// /// \param Visibility The visibility provided for the names in the loaded /// module. /// /// \param IsInclusionDirective Indicates that this module is being loaded /// implicitly, due to the presence of an inclusion directive. Otherwise, /// it is being loaded due to an import declaration. /// /// \returns If successful, returns the loaded module. Otherwise, returns /// NULL to indicate that the module could not be loaded. virtual ModuleLoadResult loadModule(SourceLocation ImportLoc, ModuleIdPath Path, Module::NameVisibilityKind Visibility, bool IsInclusionDirective) = 0; /// \brief Make the given module visible. virtual void makeModuleVisible(Module *Mod, Module::NameVisibilityKind Visibility, SourceLocation ImportLoc) = 0; /// \brief Load, create, or return global module. /// This function returns an existing global module index, if one /// had already been loaded or created, or loads one if it /// exists, or creates one if it doesn't exist. /// Also, importantly, if the index doesn't cover all the modules /// in the module map, it will be update to do so here, because /// of its use in searching for needed module imports and /// associated fixit messages. /// \param TriggerLoc The location for what triggered the load. /// \returns Returns null if load failed. virtual GlobalModuleIndex *loadGlobalModuleIndex( SourceLocation TriggerLoc) = 0; /// Check global module index for missing imports. /// \param Name The symbol name to look for. /// \param TriggerLoc The location for what triggered the load. /// \returns Returns true if any modules with that symbol found. virtual bool lookupMissingImports(StringRef Name, SourceLocation TriggerLoc) = 0; bool HadFatalFailure; }; } #endif
0
repos/DirectXShaderCompiler/tools/clang/include/clang
repos/DirectXShaderCompiler/tools/clang/include/clang/Lex/PreprocessorLexer.h
//===--- PreprocessorLexer.h - C Language Family Lexer ----------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// /// /// \file /// \brief Defines the PreprocessorLexer interface. /// //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_LEX_PREPROCESSORLEXER_H #define LLVM_CLANG_LEX_PREPROCESSORLEXER_H #include "clang/Lex/MultipleIncludeOpt.h" #include "clang/Lex/Token.h" #include "llvm/ADT/SmallVector.h" namespace clang { class FileEntry; class Preprocessor; class PreprocessorLexer { virtual void anchor(); protected: Preprocessor *PP; // Preprocessor object controlling lexing. /// The SourceManager FileID corresponding to the file being lexed. const FileID FID; /// \brief Number of SLocEntries before lexing the file. unsigned InitialNumSLocEntries; //===--------------------------------------------------------------------===// // Context-specific lexing flags set by the preprocessor. //===--------------------------------------------------------------------===// /// \brief True when parsing \#XXX; turns '\\n' into a tok::eod token. bool ParsingPreprocessorDirective; /// \brief True after \#include; turns \<xx> into a tok::angle_string_literal /// token. bool ParsingFilename; /// \brief True if in raw mode. /// /// Raw mode disables interpretation of tokens and is a far faster mode to /// lex in than non-raw-mode. This flag: /// 1. If EOF of the current lexer is found, the include stack isn't popped. /// 2. Identifier information is not looked up for identifier tokens. As an /// effect of this, implicit macro expansion is naturally disabled. /// 3. "#" tokens at the start of a line are treated as normal tokens, not /// implicitly transformed by the lexer. /// 4. All diagnostic messages are disabled. /// 5. No callbacks are made into the preprocessor. /// /// Note that in raw mode that the PP pointer may be null. bool LexingRawMode; /// \brief A state machine that detects the \#ifndef-wrapping a file /// idiom for the multiple-include optimization. MultipleIncludeOpt MIOpt; /// \brief Information about the set of \#if/\#ifdef/\#ifndef blocks /// we are currently in. SmallVector<PPConditionalInfo, 4> ConditionalStack; PreprocessorLexer(const PreprocessorLexer &) = delete; void operator=(const PreprocessorLexer &) = delete; friend class Preprocessor; PreprocessorLexer(Preprocessor *pp, FileID fid); PreprocessorLexer() : PP(nullptr), InitialNumSLocEntries(0), ParsingPreprocessorDirective(false), ParsingFilename(false), LexingRawMode(false) {} virtual ~PreprocessorLexer() {} virtual void IndirectLex(Token& Result) = 0; /// \brief Return the source location for the next observable location. virtual SourceLocation getSourceLocation() = 0; //===--------------------------------------------------------------------===// // #if directive handling. /// pushConditionalLevel - When we enter a \#if directive, this keeps track of /// what we are currently in for diagnostic emission (e.g. \#if with missing /// \#endif). void pushConditionalLevel(SourceLocation DirectiveStart, bool WasSkipping, bool FoundNonSkip, bool FoundElse) { PPConditionalInfo CI; CI.IfLoc = DirectiveStart; CI.WasSkipping = WasSkipping; CI.FoundNonSkip = FoundNonSkip; CI.FoundElse = FoundElse; ConditionalStack.push_back(CI); } void pushConditionalLevel(const PPConditionalInfo &CI) { ConditionalStack.push_back(CI); } /// popConditionalLevel - Remove an entry off the top of the conditional /// stack, returning information about it. If the conditional stack is empty, /// this returns true and does not fill in the arguments. bool popConditionalLevel(PPConditionalInfo &CI) { if (ConditionalStack.empty()) return true; CI = ConditionalStack.pop_back_val(); return false; } /// \brief Return the top of the conditional stack. /// \pre This requires that there be a conditional active. PPConditionalInfo &peekConditionalLevel() { assert(!ConditionalStack.empty() && "No conditionals active!"); return ConditionalStack.back(); } unsigned getConditionalStackDepth() const { return ConditionalStack.size(); } public: //===--------------------------------------------------------------------===// // Misc. lexing methods. /// \brief After the preprocessor has parsed a \#include, lex and /// (potentially) macro expand the filename. /// /// If the sequence parsed is not lexically legal, emit a diagnostic and /// return a result EOD token. void LexIncludeFilename(Token &Result); /// \brief Inform the lexer whether or not we are currently lexing a /// preprocessor directive. void setParsingPreprocessorDirective(bool f) { ParsingPreprocessorDirective = f; } /// \brief Return true if this lexer is in raw mode or not. bool isLexingRawMode() const { return LexingRawMode; } /// \brief Return the preprocessor object for this lexer. Preprocessor *getPP() const { return PP; } FileID getFileID() const { assert(PP && "PreprocessorLexer::getFileID() should only be used with a Preprocessor"); return FID; } /// \brief Number of SLocEntries before lexing the file. unsigned getInitialNumSLocEntries() const { return InitialNumSLocEntries; } /// getFileEntry - Return the FileEntry corresponding to this FileID. Like /// getFileID(), this only works for lexers with attached preprocessors. const FileEntry *getFileEntry() const; /// \brief Iterator that traverses the current stack of preprocessor /// conditional directives (\#if/\#ifdef/\#ifndef). typedef SmallVectorImpl<PPConditionalInfo>::const_iterator conditional_iterator; conditional_iterator conditional_begin() const { return ConditionalStack.begin(); } conditional_iterator conditional_end() const { return ConditionalStack.end(); } }; } // end namespace clang #endif
0
repos/DirectXShaderCompiler/tools/clang/include/clang
repos/DirectXShaderCompiler/tools/clang/include/clang/Lex/ExternalPreprocessorSource.h
//===- ExternalPreprocessorSource.h - Abstract Macro Interface --*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines the ExternalPreprocessorSource interface, which enables // construction of macro definitions from some external source. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_LEX_EXTERNALPREPROCESSORSOURCE_H #define LLVM_CLANG_LEX_EXTERNALPREPROCESSORSOURCE_H namespace clang { class IdentifierInfo; class Module; /// \brief Abstract interface for external sources of preprocessor /// information. /// /// This abstract class allows an external sources (such as the \c ASTReader) /// to provide additional preprocessing information. class ExternalPreprocessorSource { public: virtual ~ExternalPreprocessorSource(); /// \brief Read the set of macros defined by this external macro source. virtual void ReadDefinedMacros() = 0; /// \brief Update an out-of-date identifier. virtual void updateOutOfDateIdentifier(IdentifierInfo &II) = 0; /// \brief Return the identifier associated with the given ID number. /// /// The ID 0 is associated with the NULL identifier. virtual IdentifierInfo *GetIdentifier(unsigned ID) = 0; /// \brief Map a module ID to a module. virtual Module *getModule(unsigned ModuleID) = 0; }; } #endif