Movatterモバイル変換


[0]ホーム

URL:


LLVM 20.0.0git
CodeGenData.h
Go to the documentation of this file.
1//===- CodeGenData.h --------------------------------------------*- 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//
9// This file contains support for codegen data that has stable summary which
10// can be used to optimize the code in the subsequent codegen.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_CGDATA_CODEGENDATA_H
15#define LLVM_CGDATA_CODEGENDATA_H
16
17#include "llvm/ADT/BitmaskEnum.h"
18#include "llvm/ADT/StableHashing.h"
19#include "llvm/Bitcode/BitcodeReader.h"
20#include "llvm/CGData/OutlinedHashTree.h"
21#include "llvm/CGData/OutlinedHashTreeRecord.h"
22#include "llvm/CGData/StableFunctionMapRecord.h"
23#include "llvm/IR/Module.h"
24#include "llvm/Object/ObjectFile.h"
25#include "llvm/Support/Caching.h"
26#include "llvm/Support/ErrorHandling.h"
27#include "llvm/TargetParser/Triple.h"
28#include <mutex>
29
30namespacellvm {
31
32enumCGDataSectKind {
33#define CG_DATA_SECT_ENTRY(Kind, SectNameCommon, SectNameCoff, Prefix) Kind,
34#include "llvm/CGData/CodeGenData.inc"
35};
36
37std::stringgetCodeGenDataSectionName(CGDataSectKind CGSK,
38Triple::ObjectFormatType OF,
39bool AddSegmentInfo =true);
40
41enum classCGDataKind {
42Unknown = 0x0,
43// A function outlining info.
44FunctionOutlinedHashTree = 0x1,
45// A function merging info.
46StableFunctionMergingMap = 0x2,
47LLVM_MARK_AS_BITMASK_ENUM(/*LargestValue=*/StableFunctionMergingMap)
48};
49
50const std::error_category &cgdata_category();
51
52enum classcgdata_error {
53success = 0,
54eof,
55bad_magic,
56bad_header,
57empty_cgdata,
58malformed,
59unsupported_version,
60};
61
62inline std::error_codemake_error_code(cgdata_errorE) {
63return std::error_code(static_cast<int>(E),cgdata_category());
64}
65
66classCGDataError :publicErrorInfo<CGDataError> {
67public:
68CGDataError(cgdata_error Err,constTwine &ErrStr =Twine())
69 : Err(Err), Msg(ErrStr.str()) {
70assert(Err !=cgdata_error::success &&"Not an error");
71 }
72
73 std::stringmessage()const override;
74
75voidlog(raw_ostream &OS) const override{OS <<message(); }
76
77 std::error_codeconvertToErrorCode() const override{
78returnmake_error_code(Err);
79 }
80
81cgdata_errorget() const{return Err; }
82const std::string &getMessage() const{return Msg; }
83
84 /// Consume an Error and return the raw enum value contained within it, and
85 /// the optional error message. The Error must either be a success value, or
86 /// contain a single CGDataError.
87static std::pair<cgdata_error, std::string>take(ErrorE) {
88auto Err =cgdata_error::success;
89 std::string Msg;
90handleAllErrors(std::move(E), [&Err, &Msg](constCGDataError &IPE) {
91assert(Err ==cgdata_error::success &&"Multiple errors encountered");
92 Err = IPE.get();
93 Msg = IPE.getMessage();
94 });
95return {Err, Msg};
96 }
97
98staticcharID;
99
100private:
101cgdata_error Err;
102 std::string Msg;
103};
104
105enumCGDataMode {
106None,
107Read,
108Write,
109};
110
111classCodeGenData {
112 /// Global outlined hash tree that has oulined hash sequences across modules.
113 std::unique_ptr<OutlinedHashTree> PublishedHashTree;
114 /// Global stable function map that has stable function info across modules.
115 std::unique_ptr<StableFunctionMap> PublishedStableFunctionMap;
116
117 /// This flag is set when -fcodegen-data-generate is passed.
118 /// Or, it can be mutated with -fcodegen-data-thinlto-two-rounds.
119bool EmitCGData;
120
121 /// This is a singleton instance which is thread-safe. Unlike profile data
122 /// which is largely function-based, codegen data describes the whole module.
123 /// Therefore, this can be initialized once, and can be used across modules
124 /// instead of constructing the same one for each codegen backend.
125static std::unique_ptr<CodeGenData> Instance;
126static std::once_flag OnceFlag;
127
128CodeGenData() =default;
129
130public:
131~CodeGenData() =default;
132
133staticCodeGenData &getInstance();
134
135 /// Returns true if we have a valid outlined hash tree.
136boolhasOutlinedHashTree() {
137return PublishedHashTree && !PublishedHashTree->empty();
138 }
139boolhasStableFunctionMap() {
140return PublishedStableFunctionMap && !PublishedStableFunctionMap->empty();
141 }
142
143 /// Returns the outlined hash tree. This can be globally used in a read-only
144 /// manner.
145constOutlinedHashTree *getOutlinedHashTree() {
146return PublishedHashTree.get();
147 }
148constStableFunctionMap *getStableFunctionMap() {
149return PublishedStableFunctionMap.get();
150 }
151
152 /// Returns true if we should write codegen data.
153boolemitCGData() {return EmitCGData; }
154
155 /// Publish the (globally) merged or read outlined hash tree.
156voidpublishOutlinedHashTree(std::unique_ptr<OutlinedHashTree> HashTree) {
157 PublishedHashTree = std::move(HashTree);
158// Ensure we disable emitCGData as we do not want to read and write both.
159 EmitCGData =false;
160 }
161void
162publishStableFunctionMap(std::unique_ptr<StableFunctionMap> FunctionMap) {
163 PublishedStableFunctionMap = std::move(FunctionMap);
164// Ensure we disable emitCGData as we do not want to read and write both.
165 EmitCGData =false;
166 }
167};
168
169namespacecgdata {
170
171inlineboolhasOutlinedHashTree() {
172returnCodeGenData::getInstance().hasOutlinedHashTree();
173}
174
175inlineboolhasStableFunctionMap() {
176returnCodeGenData::getInstance().hasStableFunctionMap();
177}
178
179inlineconstOutlinedHashTree *getOutlinedHashTree() {
180returnCodeGenData::getInstance().getOutlinedHashTree();
181}
182
183inlineconstStableFunctionMap *getStableFunctionMap() {
184returnCodeGenData::getInstance().getStableFunctionMap();
185}
186
187inlineboolemitCGData() {returnCodeGenData::getInstance().emitCGData(); }
188
189inlinevoid
190publishOutlinedHashTree(std::unique_ptr<OutlinedHashTree> HashTree) {
191CodeGenData::getInstance().publishOutlinedHashTree(std::move(HashTree));
192}
193
194inlinevoid
195publishStableFunctionMap(std::unique_ptr<StableFunctionMap> FunctionMap) {
196CodeGenData::getInstance().publishStableFunctionMap(std::move(FunctionMap));
197}
198
199structStreamCacheData {
200 /// Backing buffer for serialized data stream.
201SmallVector<SmallString<0>>Outputs;
202 /// Callback function to add serialized data to the stream.
203AddStreamFnAddStream;
204 /// Backing buffer for cached data.
205SmallVector<std::unique_ptr<MemoryBuffer>>Files;
206 /// Cache mechanism for storing data.
207FileCacheCache;
208
209StreamCacheData(unsignedSize,constFileCache &OrigCache,
210constTwine &CachePrefix)
211 :Outputs(Size),Files(Size) {
212AddStream = [&](size_t Task,constTwine &ModuleName) {
213return std::make_unique<CachedFileStream>(
214 std::make_unique<raw_svector_ostream>(Outputs[Task]));
215 };
216
217if (OrigCache.isValid()) {
218auto CGCacheOrErr =
219localCache("ThinLTO", CachePrefix, OrigCache.getCacheDirectoryPath(),
220 [&](size_t Task,constTwine &ModuleName,
221 std::unique_ptr<MemoryBuffer> MB) {
222 Files[Task] = std::move(MB);
223 });
224if (Error Err = CGCacheOrErr.takeError())
225report_fatal_error(std::move(Err));
226Cache = std::move(*CGCacheOrErr);
227 }
228 }
229StreamCacheData() =delete;
230
231 /// Retrieve results from either the cache or the stream.
232 std::unique_ptr<SmallVector<StringRef>>getResult() {
233unsigned NumOutputs =Outputs.size();
234auto Result = std::make_unique<SmallVector<StringRef>>(NumOutputs);
235for (unsignedI = 0;I < NumOutputs; ++I)
236if (Files[I])
237 (*Result)[I] =Files[I]->getBuffer();
238else
239 (*Result)[I] =Outputs[I];
240return Result;
241 }
242};
243
244/// Save \p TheModule before the first codegen round.
245/// \p Task represents the partition number in the parallel code generation
246/// process. \p AddStream is the callback used to add the serialized module to
247/// the stream.
248voidsaveModuleForTwoRounds(constModule &TheModule,unsigned Task,
249AddStreamFn AddStream);
250
251/// Load the optimized bitcode module for the second codegen round.
252/// \p OrigModule is the original bitcode module.
253/// \p Task identifies the partition number in the parallel code generation
254/// process. \p Context provides the environment settings for module operations.
255/// \p IRFiles contains optimized bitcode module files needed for loading.
256/// \return A unique_ptr to the loaded Module, or nullptr if loading fails.
257std::unique_ptr<Module>loadModuleForTwoRounds(BitcodeModule &OrigModule,
258unsigned Task,
259LLVMContext &Context,
260ArrayRef<StringRef> IRFiles);
261
262/// Merge the codegen data from the scratch objects \p ObjectFiles from the
263/// first codegen round.
264/// \return the combined hash of the merged codegen data.
265Expected<stable_hash>mergeCodeGenData(ArrayRef<StringRef> ObjectFiles);
266
267voidwarn(ErrorE,StringRef Whence ="");
268voidwarn(Twine Message, std::string Whence ="", std::string Hint ="");
269
270}// end namespace cgdata
271
272namespaceIndexedCGData {
273
274// A signature for data validation, representing "\xffcgdata\x81" in
275// little-endian order
276constuint64_tMagic = 0x81617461646763ff;
277
278enumCGDataVersion {
279// Version 1 is the first version. This version supports the outlined
280// hash tree.
281Version1 = 1,
282// Version 2 supports the stable function merging map.
283Version2 = 2,
284CurrentVersion = CG_DATA_INDEX_VERSION
285};
286constuint64_tVersion =CGDataVersion::CurrentVersion;
287
288structHeader {
289uint64_tMagic;
290uint32_tVersion;
291uint32_tDataKind;
292uint64_tOutlinedHashTreeOffset;
293uint64_tStableFunctionMapOffset;
294
295// New fields should only be added at the end to ensure that the size
296// computation is correct. The methods below need to be updated to ensure that
297// the new field is read correctly.
298
299// Reads a header struct from the buffer.
300staticExpected<Header>readFromBuffer(constunsignedchar *Curr);
301};
302
303}// end namespace IndexedCGData
304
305}// end namespace llvm
306
307#endif// LLVM_CODEGEN_PREPARE_H
BitcodeReader.h
BitmaskEnum.h
E
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
Caching.h
CodeGenData.inc
Size
uint64_t Size
Definition:ELFObjHandler.cpp:81
Module.h
Module.h This file contains the declarations for the Module class.
I
#define I(x, y, z)
Definition:MD5.cpp:58
ObjectFile.h
OutlinedHashTreeRecord.h
OutlinedHashTree.h
assert
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
OS
raw_pwrite_stream & OS
Definition:SampleProfWriter.cpp:51
StableFunctionMapRecord.h
StableHashing.h
Triple.h
llvm::ArrayRef
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition:ArrayRef.h:41
llvm::BitcodeModule
Represents a module in a bitcode file.
Definition:BitcodeReader.h:101
llvm::CGDataError
Definition:CodeGenData.h:66
llvm::CGDataError::getMessage
const std::string & getMessage() const
Definition:CodeGenData.h:82
llvm::CGDataError::convertToErrorCode
std::error_code convertToErrorCode() const override
Convert this error to a std::error_code.
Definition:CodeGenData.h:77
llvm::CGDataError::take
static std::pair< cgdata_error, std::string > take(Error E)
Consume an Error and return the raw enum value contained within it, and the optional error message.
Definition:CodeGenData.h:87
llvm::CGDataError::ID
static char ID
Definition:CodeGenData.h:98
llvm::CGDataError::message
std::string message() const override
Return the error message as a string.
Definition:CodeGenData.cpp:98
llvm::CGDataError::log
void log(raw_ostream &OS) const override
Print an error message to an output stream.
Definition:CodeGenData.h:75
llvm::CGDataError::CGDataError
CGDataError(cgdata_error Err, const Twine &ErrStr=Twine())
Definition:CodeGenData.h:68
llvm::CGDataError::get
cgdata_error get() const
Definition:CodeGenData.h:81
llvm::CodeGenData
Definition:CodeGenData.h:111
llvm::CodeGenData::hasStableFunctionMap
bool hasStableFunctionMap()
Definition:CodeGenData.h:139
llvm::CodeGenData::getStableFunctionMap
const StableFunctionMap * getStableFunctionMap()
Definition:CodeGenData.h:148
llvm::CodeGenData::emitCGData
bool emitCGData()
Returns true if we should write codegen data.
Definition:CodeGenData.h:153
llvm::CodeGenData::publishOutlinedHashTree
void publishOutlinedHashTree(std::unique_ptr< OutlinedHashTree > HashTree)
Publish the (globally) merged or read outlined hash tree.
Definition:CodeGenData.h:156
llvm::CodeGenData::hasOutlinedHashTree
bool hasOutlinedHashTree()
Returns true if we have a valid outlined hash tree.
Definition:CodeGenData.h:136
llvm::CodeGenData::getOutlinedHashTree
const OutlinedHashTree * getOutlinedHashTree()
Returns the outlined hash tree.
Definition:CodeGenData.h:145
llvm::CodeGenData::~CodeGenData
~CodeGenData()=default
llvm::CodeGenData::publishStableFunctionMap
void publishStableFunctionMap(std::unique_ptr< StableFunctionMap > FunctionMap)
Definition:CodeGenData.h:162
llvm::CodeGenData::getInstance
static CodeGenData & getInstance()
Definition:CodeGenData.cpp:146
llvm::ErrorInfo
Base class for user error types.
Definition:Error.h:355
llvm::Error
Lightweight error class with error context and mandatory checking.
Definition:Error.h:160
llvm::Expected
Tagged union holding either a T or a Error.
Definition:Error.h:481
llvm::LLVMContext
This is an important class for using LLVM in a threaded context.
Definition:LLVMContext.h:67
llvm::Module
A Module instance is used to store all the information related to an LLVM module.
Definition:Module.h:65
llvm::OutlinedHashTree
Definition:OutlinedHashTree.h:42
llvm::SmallVector
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition:SmallVector.h:1196
llvm::StringRef
StringRef - Represent a constant reference to a string, i.e.
Definition:StringRef.h:51
llvm::Triple::ObjectFormatType
ObjectFormatType
Definition:Triple.h:307
llvm::Twine
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition:Twine.h:81
llvm::raw_ostream
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition:raw_ostream.h:52
uint32_t
uint64_t
ErrorHandling.h
llvm::IndexedCGData::Version
const uint64_t Version
Definition:CodeGenData.h:286
llvm::IndexedCGData::CGDataVersion
CGDataVersion
Definition:CodeGenData.h:278
llvm::IndexedCGData::Version2
@ Version2
Definition:CodeGenData.h:283
llvm::IndexedCGData::CurrentVersion
@ CurrentVersion
Definition:CodeGenData.h:284
llvm::IndexedCGData::Version1
@ Version1
Definition:CodeGenData.h:281
llvm::IndexedCGData::Magic
const uint64_t Magic
Definition:CodeGenData.h:276
llvm::cgdata::mergeCodeGenData
Expected< stable_hash > mergeCodeGenData(ArrayRef< StringRef > ObjectFiles)
Merge the codegen data from the scratch objects ObjectFiles from the first codegen round.
Definition:CodeGenData.cpp:257
llvm::cgdata::publishOutlinedHashTree
void publishOutlinedHashTree(std::unique_ptr< OutlinedHashTree > HashTree)
Definition:CodeGenData.h:190
llvm::cgdata::hasOutlinedHashTree
bool hasOutlinedHashTree()
Definition:CodeGenData.h:171
llvm::cgdata::hasStableFunctionMap
bool hasStableFunctionMap()
Definition:CodeGenData.h:175
llvm::cgdata::warn
void warn(Error E, StringRef Whence="")
Definition:CodeGenData.cpp:216
llvm::cgdata::getOutlinedHashTree
const OutlinedHashTree * getOutlinedHashTree()
Definition:CodeGenData.h:179
llvm::cgdata::publishStableFunctionMap
void publishStableFunctionMap(std::unique_ptr< StableFunctionMap > FunctionMap)
Definition:CodeGenData.h:195
llvm::cgdata::saveModuleForTwoRounds
void saveModuleForTwoRounds(const Module &TheModule, unsigned Task, AddStreamFn AddStream)
Save TheModule before the first codegen round.
Definition:CodeGenData.cpp:224
llvm::cgdata::emitCGData
bool emitCGData()
Definition:CodeGenData.h:187
llvm::cgdata::getStableFunctionMap
const StableFunctionMap * getStableFunctionMap()
Definition:CodeGenData.h:183
llvm::cgdata::loadModuleForTwoRounds
std::unique_ptr< Module > loadModuleForTwoRounds(BitcodeModule &OrigModule, unsigned Task, LLVMContext &Context, ArrayRef< StringRef > IRFiles)
Load the optimized bitcode module for the second codegen round.
Definition:CodeGenData.cpp:238
llvm
This is an optimization pass for GlobalISel generic memory operations.
Definition:AddressRanges.h:18
llvm::CGDataKind
CGDataKind
Definition:CodeGenData.h:41
llvm::CGDataKind::StableFunctionMergingMap
@ StableFunctionMergingMap
llvm::CGDataKind::Unknown
@ Unknown
llvm::CGDataKind::FunctionOutlinedHashTree
@ FunctionOutlinedHashTree
llvm::CGDataMode
CGDataMode
Definition:CodeGenData.h:105
llvm::Read
@ Read
Definition:CodeGenData.h:107
llvm::Write
@ Write
Definition:CodeGenData.h:108
llvm::make_error_code
std::error_code make_error_code(BitcodeError E)
Definition:BitcodeReader.h:310
llvm::handleAllErrors
void handleAllErrors(Error E, HandlerTs &&... Handlers)
Behaves the same as handleErrors, except that by contract all errors must be handled by the given han...
Definition:Error.h:977
llvm::AddStreamFn
std::function< Expected< std::unique_ptr< CachedFileStream > >(unsigned Task, const Twine &ModuleName)> AddStreamFn
This type defines the callback to add a file that is generated on the fly.
Definition:Caching.h:42
llvm::cgdata_error
cgdata_error
Definition:CodeGenData.h:52
llvm::cgdata_error::success
@ success
llvm::cgdata_error::unsupported_version
@ unsupported_version
llvm::cgdata_error::eof
@ eof
llvm::cgdata_error::bad_magic
@ bad_magic
llvm::cgdata_error::malformed
@ malformed
llvm::cgdata_error::empty_cgdata
@ empty_cgdata
llvm::cgdata_error::bad_header
@ bad_header
llvm::None
@ None
Definition:CodeGenData.h:106
llvm::report_fatal_error
void report_fatal_error(Error Err, bool gen_crash_diag=true)
Report a serious error, calling any installed error handler.
Definition:Error.cpp:167
llvm::cgdata_category
const std::error_category & cgdata_category()
Definition:CodeGenData.cpp:93
llvm::ModRefInfo::LLVM_MARK_AS_BITMASK_ENUM
@ LLVM_MARK_AS_BITMASK_ENUM
llvm::CGDataSectKind
CGDataSectKind
Definition:CodeGenData.h:32
llvm::localCache
Expected< FileCache > localCache(const Twine &CacheNameRef, const Twine &TempFilePrefixRef, const Twine &CacheDirectoryPathRef, AddBufferFn AddBuffer=[](size_t Task, const Twine &ModuleName, std::unique_ptr< MemoryBuffer > MB) {})
Create a local file system cache which uses the given cache name, temporary file prefix,...
Definition:Caching.cpp:29
llvm::getCodeGenDataSectionName
std::string getCodeGenDataSectionName(CGDataSectKind CGSK, Triple::ObjectFormatType OF, bool AddSegmentInfo=true)
Definition:CodeGenData.cpp:127
ModuleName
Definition:ItaniumDemangle.h:1097
llvm::FileCache
This type represents a file cache system that manages caching of files.
Definition:Caching.h:67
llvm::FileCache::getCacheDirectoryPath
const std::string & getCacheDirectoryPath() const
Definition:Caching.h:77
llvm::FileCache::isValid
bool isValid() const
Definition:Caching.h:80
llvm::IndexedCGData::Header
Definition:CodeGenData.h:288
llvm::IndexedCGData::Header::StableFunctionMapOffset
uint64_t StableFunctionMapOffset
Definition:CodeGenData.h:293
llvm::IndexedCGData::Header::Version
uint32_t Version
Definition:CodeGenData.h:290
llvm::IndexedCGData::Header::DataKind
uint32_t DataKind
Definition:CodeGenData.h:291
llvm::IndexedCGData::Header::readFromBuffer
static Expected< Header > readFromBuffer(const unsigned char *Curr)
Definition:CodeGenData.cpp:176
llvm::IndexedCGData::Header::OutlinedHashTreeOffset
uint64_t OutlinedHashTreeOffset
Definition:CodeGenData.h:292
llvm::IndexedCGData::Header::Magic
uint64_t Magic
Definition:CodeGenData.h:289
llvm::StableFunctionMap
Definition:StableFunctionMap.h:51
llvm::cgdata::StreamCacheData
Definition:CodeGenData.h:199
llvm::cgdata::StreamCacheData::StreamCacheData
StreamCacheData()=delete
llvm::cgdata::StreamCacheData::Outputs
SmallVector< SmallString< 0 > > Outputs
Backing buffer for serialized data stream.
Definition:CodeGenData.h:201
llvm::cgdata::StreamCacheData::Cache
FileCache Cache
Cache mechanism for storing data.
Definition:CodeGenData.h:207
llvm::cgdata::StreamCacheData::Files
SmallVector< std::unique_ptr< MemoryBuffer > > Files
Backing buffer for cached data.
Definition:CodeGenData.h:205
llvm::cgdata::StreamCacheData::getResult
std::unique_ptr< SmallVector< StringRef > > getResult()
Retrieve results from either the cache or the stream.
Definition:CodeGenData.h:232
llvm::cgdata::StreamCacheData::AddStream
AddStreamFn AddStream
Callback function to add serialized data to the stream.
Definition:CodeGenData.h:203
llvm::cgdata::StreamCacheData::StreamCacheData
StreamCacheData(unsigned Size, const FileCache &OrigCache, const Twine &CachePrefix)
Definition:CodeGenData.h:209

Generated on Thu Jul 17 2025 09:39:33 for LLVM by doxygen 1.9.6
[8]ページ先頭

©2009-2025 Movatter.jp