clang 22.0.0git
Frontend.cpp
Go to the documentation of this file.
1//===- Frontend.cpp ---------------------------------------------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
12#include "llvm/ADT/StringRef.h"
13
14using namespace llvm;
15using namespace llvm::MachO;
16
17namespace clang::installapi {
18std::pair<GlobalRecord *, FrontendAttrs *> FrontendRecordsSlice::addGlobal(
19 StringRef Name, RecordLinkage Linkage, GlobalRecord::Kind GV,
20 const clang::AvailabilityInfo Avail, const Decl *D, const HeaderType Access,
21 SymbolFlags Flags, bool Inlined) {
22
23 GlobalRecord *GR =
24 llvm::MachO::RecordsSlice::addGlobal(Name, Linkage, GV, Flags, Inlined);
25 auto Result = FrontendRecords.insert(
26 {GR, FrontendAttrs{Avail, D, D->getLocation(), Access}});
27 return {GR, &(Result.first->second)};
28}
29
30std::pair<ObjCInterfaceRecord *, FrontendAttrs *>
32 const clang::AvailabilityInfo Avail,
33 const Decl *D, HeaderType Access,
34 bool IsEHType) {
35 ObjCIFSymbolKind SymType =
36 ObjCIFSymbolKind::Class | ObjCIFSymbolKind::MetaClass;
37 if (IsEHType)
38 SymType |= ObjCIFSymbolKind::EHType;
39
40 ObjCInterfaceRecord *ObjCR =
41 llvm::MachO::RecordsSlice::addObjCInterface(Name, Linkage, SymType);
42 auto Result = FrontendRecords.insert(
43 {ObjCR, FrontendAttrs{Avail, D, D->getLocation(), Access}});
44 return {ObjCR, &(Result.first->second)};
45}
46
47std::pair<ObjCCategoryRecord *, FrontendAttrs *>
49 StringRef CategoryName,
50 const clang::AvailabilityInfo Avail,
51 const Decl *D, HeaderType Access) {
52 ObjCCategoryRecord *ObjCR =
53 llvm::MachO::RecordsSlice::addObjCCategory(ClassToExtend, CategoryName);
54 auto Result = FrontendRecords.insert(
55 {ObjCR, FrontendAttrs{Avail, D, D->getLocation(), Access}});
56 return {ObjCR, &(Result.first->second)};
57}
58
59std::pair<ObjCIVarRecord *, FrontendAttrs *> FrontendRecordsSlice::addObjCIVar(
60 ObjCContainerRecord *Container, StringRef IvarName, RecordLinkage Linkage,
61 const clang::AvailabilityInfo Avail, const Decl *D, HeaderType Access,
63 // If the decl otherwise would have been exported, check their access control.
64 // Ivar's linkage is also determined by this.
65 if ((Linkage == RecordLinkage::Exported) &&
67 Linkage = RecordLinkage::Internal;
68 ObjCIVarRecord *ObjCR =
69 llvm::MachO::RecordsSlice::addObjCIVar(Container, IvarName, Linkage);
70 auto Result = FrontendRecords.insert(
71 {ObjCR, FrontendAttrs{Avail, D, D->getLocation(), Access}});
72
73 return {ObjCR, &(Result.first->second)};
74}
75
76std::optional<HeaderType>
78 const Preprocessor &PP) {
79 if (!FE)
80 return std::nullopt;
81
82 // Check if header has been looked up already and whether it is something
83 // installapi should use.
84 auto It = KnownFiles.find(FE);
85 if (It != KnownFiles.end()) {
86 if (It->second != HeaderType::Unknown)
87 return It->second;
88 else
89 return std::nullopt;
90 }
91
92 // If file was not found, search by how the header was
93 // included. This is primarily to resolve headers found
94 // in a different location than what passed directly as input.
95 StringRef IncludeName = PP.getHeaderSearchInfo().getIncludeNameForHeader(FE);
96 auto BackupIt = KnownIncludes.find(IncludeName);
97 if (BackupIt != KnownIncludes.end()) {
98 KnownFiles[FE] = BackupIt->second;
99 return BackupIt->second;
100 }
101
102 // Record that the file was found to avoid future string searches for the
103 // same file.
104 KnownFiles.insert({FE, HeaderType::Unknown});
105 return std::nullopt;
106}
107
109 auto FE = FM->getOptionalFileRef(H.getPath());
110 if (!FE)
111 return; // File does not exist.
112 KnownFiles[*FE] = H.getType();
113
114 if (!H.useIncludeName())
115 return;
116
117 KnownIncludes[H.getIncludeName()] = H.getType();
118}
119
120static StringRef getFileExtension(clang::Language Lang) {
121 switch (Lang) {
122 default:
123 llvm_unreachable("Unexpected language option.");
125 return ".c";
127 return ".cpp";
129 return ".m";
131 return ".mm";
132 }
133}
134
135std::unique_ptr<MemoryBuffer> createInputBuffer(InstallAPIContext &Ctx) {
136 assert(Ctx.Type != HeaderType::Unknown &&
137 "unexpected access level for parsing");
138 SmallString<4096> Contents;
139 raw_svector_ostream OS(Contents);
140 for (const HeaderFile &H : Ctx.InputHeaders) {
141 if (H.isExcluded())
142 continue;
143 if (H.getType() != Ctx.Type)
144 continue;
145 if (Ctx.LangMode == Language::C || Ctx.LangMode == Language::CXX)
146 OS << "#include ";
147 else
148 OS << "#import ";
149 if (H.useIncludeName())
150 OS << "<" << H.getIncludeName() << ">\n";
151 else
152 OS << "\"" << H.getPath() << "\"\n";
153
154 Ctx.addKnownHeader(H);
155 }
156 if (Contents.empty())
157 return nullptr;
158
159 SmallString<64> BufferName(
160 {"installapi-includes-", Ctx.Slice->getTriple().str(), "-",
161 getName(Ctx.Type), getFileExtension(Ctx.LangMode)});
162 return llvm::MemoryBuffer::getMemBufferCopy(Contents, BufferName);
163}
164
165std::string findLibrary(StringRef InstallName, FileManager &FM,
166 ArrayRef<std::string> FrameworkSearchPaths,
167 ArrayRef<std::string> LibrarySearchPaths,
168 ArrayRef<std::string> SearchPaths) {
169 auto getLibrary =
170 [&](const StringRef FullPath) -> std::optional<std::string> {
171 // Prefer TextAPI files when possible.
172 SmallString<PATH_MAX> TextAPIFilePath = FullPath;
173 replace_extension(TextAPIFilePath, ".tbd");
174
175 if (FM.getOptionalFileRef(TextAPIFilePath))
176 return std::string(TextAPIFilePath);
177
178 if (FM.getOptionalFileRef(FullPath))
179 return std::string(FullPath);
180
181 return std::nullopt;
182 };
183
184 const StringRef Filename = sys::path::filename(InstallName);
185 const bool IsFramework = sys::path::parent_path(InstallName)
186 .ends_with((Filename + ".framework").str());
187 if (IsFramework) {
188 for (const StringRef Path : FrameworkSearchPaths) {
189 SmallString<PATH_MAX> FullPath(Path);
190 sys::path::append(FullPath, Filename + StringRef(".framework"), Filename);
191 if (auto LibOrNull = getLibrary(FullPath))
192 return *LibOrNull;
193 }
194 } else {
195 // Copy Apple's linker behavior: If this is a .dylib inside a framework, do
196 // not search -L paths.
197 bool IsEmbeddedDylib = (sys::path::extension(InstallName) == ".dylib") &&
198 InstallName.contains(".framework/");
199 if (!IsEmbeddedDylib) {
200 for (const StringRef Path : LibrarySearchPaths) {
201 SmallString<PATH_MAX> FullPath(Path);
202 sys::path::append(FullPath, Filename);
203 if (auto LibOrNull = getLibrary(FullPath))
204 return *LibOrNull;
205 }
206 }
207 }
208
209 for (const StringRef Path : SearchPaths) {
210 SmallString<PATH_MAX> FullPath(Path);
211 sys::path::append(FullPath, InstallName);
212 if (auto LibOrNull = getLibrary(FullPath))
213 return *LibOrNull;
214 }
215
216 return {};
217}
218
219} // namespace clang::installapi
const Decl * D
IndirectLocalPath & Path
StringRef Filename
Definition: Format.cpp:3177
llvm::MachO::ObjCIVarRecord ObjCIVarRecord
Definition: MachO.h:38
llvm::MachO::SymbolFlags SymbolFlags
Definition: MachO.h:29
llvm::MachO::ObjCCategoryRecord ObjCCategoryRecord
Definition: MachO.h:37
llvm::MachO::GlobalRecord GlobalRecord
Definition: MachO.h:33
llvm::MachO::ObjCInterfaceRecord ObjCInterfaceRecord
Definition: MachO.h:36
llvm::MachO::ObjCIFSymbolKind ObjCIFSymbolKind
Definition: MachO.h:39
llvm::MachO::RecordLinkage RecordLinkage
Definition: MachO.h:30
llvm::MachO::ObjCContainerRecord ObjCContainerRecord
Definition: MachO.h:35
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:86
Cached information about one file (either on disk or in the virtual file system).
Definition: FileEntry.h:306
Implements support for file system lookup, file system caching, and directory search management.
Definition: FileManager.h:53
OptionalFileEntryRef getOptionalFileRef(StringRef Filename, bool OpenFile=false, bool CacheFailure=true)
Get a FileEntryRef if it exists, without doing anything on error.
Definition: FileManager.h:208
StringRef getIncludeNameForHeader(const FileEntry *File) const
Retrieve the include name for the header.
Engages in a tight little dance with the lexer to efficiently preprocess tokens.
Definition: Preprocessor.h:145
HeaderSearch & getHeaderSearchInfo() const
std::pair< ObjCIVarRecord *, FrontendAttrs * > addObjCIVar(ObjCContainerRecord *Container, StringRef IvarName, RecordLinkage Linkage, const clang::AvailabilityInfo Avail, const Decl *D, HeaderType Access, const clang::ObjCIvarDecl::AccessControl AC)
Add ObjC IVar record with attributes from AST.
Definition: Frontend.cpp:59
std::pair< GlobalRecord *, FrontendAttrs * > addGlobal(StringRef Name, RecordLinkage Linkage, GlobalRecord::Kind GV, const clang::AvailabilityInfo Avail, const Decl *D, const HeaderType Access, SymbolFlags Flags=SymbolFlags::None, bool Inlined=false)
Add non-ObjC global record with attributes from AST.
Definition: Frontend.cpp:18
std::pair< ObjCInterfaceRecord *, FrontendAttrs * > addObjCInterface(StringRef Name, RecordLinkage Linkage, const clang::AvailabilityInfo Avail, const Decl *D, HeaderType Access, bool IsEHType)
Add ObjC Class record with attributes from AST.
Definition: Frontend.cpp:31
std::pair< ObjCCategoryRecord *, FrontendAttrs * > addObjCCategory(StringRef ClassToExtend, StringRef CategoryName, const clang::AvailabilityInfo Avail, const Decl *D, HeaderType Access)
Add ObjC Category record with attributes from AST.
Definition: Frontend.cpp:48
HeaderType getType() const
Definition: HeaderFile.h:78
StringRef getIncludeName() const
Definition: HeaderFile.h:79
StringRef getPath() const
Definition: HeaderFile.h:80
The DirectoryScanner for collecting library files on the file system.
Definition: Context.h:20
@ Unknown
Unset or unknown type.
std::unique_ptr< llvm::MemoryBuffer > createInputBuffer(InstallAPIContext &Ctx)
Create a buffer that contains all headers to scan for global symbols with.
Definition: Frontend.cpp:135
StringRef getName(const HeaderType T)
Definition: HeaderFile.h:38
static StringRef getFileExtension(clang::Language Lang)
Definition: Frontend.cpp:120
std::string findLibrary(StringRef InstallName, FileManager &FM, ArrayRef< std::string > FrameworkSearchPaths, ArrayRef< std::string > LibrarySearchPaths, ArrayRef< std::string > SearchPaths)
Lookup the dylib or TextAPI file location for a system library or framework.
Definition: Frontend.cpp:165
Linkage
Describes the different kinds of linkage (C++ [basic.link], C99 6.2.2) that an entity may have.
Definition: Linkage.h:24
Language
The language for the input, used to select and validate the language standard and possible actions.
Definition: LangStandard.h:23
@ C
Languages that the frontend can parse and compile.
@ Result
The result type of a method or function.
Diagnostic wrappers for TextAPI types for error reporting.
Definition: Dominators.h:30
Storage of availability attributes for a declaration.
Definition: Availability.h:64
Frontend information captured about records.
Struct used for generating validating InstallAPI.
Definition: Context.h:26
std::optional< HeaderType > findAndRecordFile(const FileEntry *FE, const Preprocessor &PP)
Record visited files during frontend actions to determine whether to include their declarations for T...
Definition: Frontend.cpp:77
void addKnownHeader(const HeaderFile &H)
Populate entries of headers that should be included for TextAPI generation.
Definition: Frontend.cpp:108
FileManager * FM
FileManager for all I/O operations.
Definition: Context.h:47