LLVM 24.0.0git
ThinLTOBitcodeWriter.cpp
Go to the documentation of this file.
1//===- ThinLTOBitcodeWriter.cpp - Bitcode writing pass for ThinLTO --------===//
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
15#include "llvm/IR/Constants.h"
16#include "llvm/IR/DebugInfo.h"
18#include "llvm/IR/Intrinsics.h"
19#include "llvm/IR/Module.h"
20#include "llvm/IR/PassManager.h"
23#include "llvm/Transforms/IPO.h"
29using namespace llvm;
30
31namespace {
32
33// Promote each local-linkage entity defined by ExportM and used by ImportM by
34// changing visibility and appending the given ModuleId.
35void promoteInternals(Module &ExportM, Module &ImportM, StringRef ModuleId,
36 SetVector<GlobalValue *> *PromoteExtra = nullptr) {
38 for (auto &ExportGV : ExportM.global_values()) {
39 if (!ExportGV.hasLocalLinkage())
40 continue;
41
42 auto Name = ExportGV.getName();
43 GlobalValue *ImportGV = nullptr;
44 const bool MustPromote = PromoteExtra && PromoteExtra->count(&ExportGV);
45 if (!MustPromote) {
46 ImportGV = ImportM.getNamedValue(Name);
47 if (!ImportGV)
48 continue;
49 ImportGV->removeDeadConstantUsers();
50 if (ImportGV->use_empty()) {
51 ImportGV->eraseFromParent();
52 continue;
53 }
54 }
55
56 std::string OldName = Name.str();
57 std::string NewName = (Name + ModuleId).str();
58
59 if (const auto *C = ExportGV.getComdat())
60 if (C->getName() == Name)
61 RenamedComdats.try_emplace(C, ExportM.getOrInsertComdat(NewName));
62
63 auto *ExternalAlias = GlobalAlias::create(
64 ExportGV.getType(), ExportGV.getAddressSpace(),
65 GlobalValue::ExternalLinkage, NewName, &ExportGV, &ExportM);
66 ExternalAlias->setVisibility(GlobalValue::HiddenVisibility);
67 ExportGV.replaceUsesWithIf(
68 ExternalAlias, [](Use &U) { return !isa<GlobalAlias>(U.getUser()); });
69
70 if (MustPromote) {
71 PromoteExtra->remove(&ExportGV);
72 PromoteExtra->insert(ExternalAlias);
73 }
74
75 if (ImportGV) {
76 ImportGV->setName(NewName);
78 ImportGV->reassignGUID();
79 }
80 }
81
82 if (!RenamedComdats.empty())
83 for (auto &GO : ExportM.global_objects())
84 if (auto *C = GO.getComdat()) {
85 auto Replacement = RenamedComdats.find(C);
86 if (Replacement != RenamedComdats.end())
87 GO.setComdat(Replacement->second);
88 }
89}
90
91// Promote all internal (i.e. distinct) type ids used by the module by replacing
92// them with external type ids formed using the module id.
93//
94// Note that this needs to be done before we clone the module because each clone
95// will receive its own set of distinct metadata nodes.
96void promoteTypeIds(Module &M, StringRef ModuleId) {
98 auto ExternalizeTypeId = [&](CallInst *CI, unsigned ArgNo) {
99 Metadata *MD =
100 cast<MetadataAsValue>(CI->getArgOperand(ArgNo))->getMetadata();
101
102 if (isa<MDNode>(MD) && cast<MDNode>(MD)->isDistinct()) {
103 Metadata *&GlobalMD = LocalToGlobal[MD];
104 if (!GlobalMD) {
105 std::string NewName = (Twine(LocalToGlobal.size()) + ModuleId).str();
106 GlobalMD = MDString::get(M.getContext(), NewName);
107 }
108
109 CI->setArgOperand(ArgNo,
110 MetadataAsValue::get(M.getContext(), GlobalMD));
111 }
112 };
113
114 if (Function *TypeTestFunc =
115 Intrinsic::getDeclarationIfExists(&M, Intrinsic::type_test)) {
116 for (const Use &U : TypeTestFunc->uses()) {
117 auto CI = cast<CallInst>(U.getUser());
118 ExternalizeTypeId(CI, 1);
119 }
120 }
121
122 if (Function *PublicTypeTestFunc =
123 Intrinsic::getDeclarationIfExists(&M, Intrinsic::public_type_test)) {
124 for (const Use &U : PublicTypeTestFunc->uses()) {
125 auto CI = cast<CallInst>(U.getUser());
126 ExternalizeTypeId(CI, 1);
127 }
128 }
129
130 if (Function *TypeCheckedLoadFunc =
131 Intrinsic::getDeclarationIfExists(&M, Intrinsic::type_checked_load)) {
132 for (const Use &U : TypeCheckedLoadFunc->uses()) {
133 auto CI = cast<CallInst>(U.getUser());
134 ExternalizeTypeId(CI, 2);
135 }
136 }
137
138 if (Function *TypeCheckedLoadRelativeFunc = Intrinsic::getDeclarationIfExists(
139 &M, Intrinsic::type_checked_load_relative)) {
140 for (const Use &U : TypeCheckedLoadRelativeFunc->uses()) {
141 auto CI = cast<CallInst>(U.getUser());
142 ExternalizeTypeId(CI, 2);
143 }
144 }
145
146 for (GlobalObject &GO : M.global_objects()) {
148 GO.getMetadata(LLVMContext::MD_type, MDs);
149
150 GO.eraseMetadata(LLVMContext::MD_type);
151 for (auto *MD : MDs) {
152 auto I = LocalToGlobal.find(MD->getOperand(1));
153 if (I == LocalToGlobal.end()) {
154 GO.addMetadata(LLVMContext::MD_type, *MD);
155 continue;
156 }
157 GO.addMetadata(
158 LLVMContext::MD_type,
159 *MDNode::get(M.getContext(), {MD->getOperand(0), I->second}));
160 }
161
163 GO.getMetadata(LLVMContext::MD_callgraph, CGMDs);
164
165 GO.eraseMetadata(LLVMContext::MD_callgraph);
166 for (auto *MD : CGMDs) {
167 if (MD->getNumOperands() == 1) {
168 auto I = LocalToGlobal.find(MD->getOperand(0));
169 if (I == LocalToGlobal.end()) {
170 GO.addMetadata(LLVMContext::MD_callgraph, *MD);
171 continue;
172 }
173 GO.addMetadata(LLVMContext::MD_callgraph,
174 *MDNode::get(M.getContext(), {I->second}));
175 }
176 }
177 }
178}
179
180// Drop unused globals, and drop type information from function declarations.
181// FIXME: If we made functions typeless then there would be no need to do this.
182void simplifyExternals(Module &M) {
183 FunctionType *EmptyFT =
184 FunctionType::get(Type::getVoidTy(M.getContext()), false);
185
187 if (F.isDeclaration() && F.use_empty()) {
188 F.eraseFromParent();
189 continue;
190 }
191
192 if (!F.isDeclaration() || F.getFunctionType() == EmptyFT ||
193 // Changing the type of an intrinsic may invalidate the IR.
194 F.getName().starts_with("llvm."))
195 continue;
196
198 F.getAddressSpace(), "", &M);
199 NewF->copyAttributesFrom(&F);
200 // Only copy function attribtues.
201 NewF->setAttributes(AttributeList::get(M.getContext(),
202 AttributeList::FunctionIndex,
203 F.getAttributes().getFnAttrs()));
204 NewF->takeName(&F);
205 NewF->setMetadata(LLVMContext::MD_guid,
206 F.getMetadata(LLVMContext::MD_guid));
207 F.replaceAllUsesWith(NewF);
208 F.eraseFromParent();
209 }
210
211 for (GlobalIFunc &I : llvm::make_early_inc_range(M.ifuncs())) {
212 if (I.use_empty())
213 I.eraseFromParent();
214 else
215 assert(I.getResolverFunction() && "ifunc misses its resolver function");
216 }
217
218 for (GlobalVariable &GV : llvm::make_early_inc_range(M.globals())) {
219 if (GV.isDeclaration() && GV.use_empty()) {
220 GV.eraseFromParent();
221 continue;
222 }
223 }
224}
225
226static void
227filterModule(Module *M,
228 function_ref<bool(const GlobalValue *)> ShouldKeepDefinition) {
229 std::vector<GlobalValue *> V;
230 for (GlobalValue &GV : M->global_values())
231 if (!ShouldKeepDefinition(&GV))
232 V.push_back(&GV);
233
234 for (GlobalValue *GV : V)
235 if (!convertToDeclaration(*GV))
236 GV->eraseFromParent();
237}
238
239void forEachVirtualFunction(Constant *C, function_ref<void(Function *)> Fn) {
240 if (auto *F = dyn_cast<Function>(C))
241 return Fn(F);
242 if (isa<GlobalValue>(C))
243 return;
244 for (Value *Op : C->operands())
245 forEachVirtualFunction(cast<Constant>(Op), Fn);
246}
247
248// Clone any @llvm[.compiler].used over to the new module and append
249// values whose defs were cloned into that module.
250static void cloneUsedGlobalVariables(const Module &SrcM, Module &DestM,
251 bool CompilerUsed) {
253 // First collect those in the llvm[.compiler].used set.
254 collectUsedGlobalVariables(SrcM, Used, CompilerUsed);
255 // Next build a set of the equivalent values defined in DestM.
256 for (auto *V : Used) {
257 auto *GV = DestM.getNamedValue(V->getName());
258 if (GV && !GV->isDeclaration())
259 NewUsed.push_back(GV);
260 }
261 // Finally, add them to a llvm[.compiler].used variable in DestM.
262 if (CompilerUsed)
263 appendToCompilerUsed(DestM, NewUsed);
264 else
265 appendToUsed(DestM, NewUsed);
266}
267
268#ifndef NDEBUG
269static bool enableUnifiedLTO(Module &M) {
270 bool UnifiedLTO = false;
271 if (auto *MD =
272 mdconst::extract_or_null<ConstantInt>(M.getModuleFlag("UnifiedLTO")))
273 UnifiedLTO = MD->getZExtValue();
274 return UnifiedLTO;
275}
276#endif
277
278bool mustEmitToMergedModule(const GlobalValue *GV) {
279 // The __cfi_check definition is filled in by the CrossDSOCFI pass which
280 // runs only in the merged module.
281 return GV->getName() == "__cfi_check";
282}
283
284// If it's possible to split M into regular and thin LTO parts, do so and write
285// a multi-module bitcode file with the two parts to OS. Otherwise, write only a
286// regular LTO bitcode file to OS.
287void splitAndWriteThinLTOBitcode(
288 raw_ostream &OS, raw_ostream *ThinLinkOS,
289 function_ref<AAResults &(Function &)> AARGetter, Module &M,
290 const bool ShouldPreserveUseListOrder) {
291 std::string ModuleId = getUniqueModuleId(&M);
292 if (ModuleId.empty()) {
293 assert(!enableUnifiedLTO(M));
294 // We couldn't generate a module ID for this module, write it out as a
295 // regular LTO module with an index for summary-based dead stripping.
296 ProfileSummaryInfo PSI(M);
297 M.addModuleFlag(Module::Error, "ThinLTO", uint32_t(0));
298 ModuleSummaryIndex Index = buildModuleSummaryIndex(M, nullptr, &PSI);
299 WriteBitcodeToFile(M, OS, ShouldPreserveUseListOrder, &Index,
300 /*UnifiedLTO=*/false);
301
302 if (ThinLinkOS)
303 // We don't have a ThinLTO part, but still write the module to the
304 // ThinLinkOS if requested so that the expected output file is produced.
305 WriteBitcodeToFile(M, *ThinLinkOS, ShouldPreserveUseListOrder, &Index,
306 /*UnifiedLTO=*/false);
307
308 return;
309 }
310
311 promoteTypeIds(M, ModuleId);
312
313 // Returns whether a global or its associated global has attached type
314 // metadata. The former may participate in CFI or whole-program
315 // devirtualization, so they need to appear in the merged module instead of
316 // the thin LTO module. Similarly, globals that are associated with globals
317 // with type metadata need to appear in the merged module because they will
318 // reference the global's section directly.
319 auto HasTypeMetadata = [](const GlobalObject *GO) {
320 if (MDNode *MD = GO->getMetadata(LLVMContext::MD_associated))
321 if (auto *AssocVM = dyn_cast_or_null<ValueAsMetadata>(MD->getOperand(0)))
322 if (auto *AssocGO = dyn_cast<GlobalObject>(AssocVM->getValue()))
323 if (AssocGO->hasMetadata(LLVMContext::MD_type))
324 return true;
325 return GO->hasMetadata(LLVMContext::MD_type);
326 };
327
328 // Collect the set of virtual functions that are eligible for virtual constant
329 // propagation. Each eligible function must not access memory, must return
330 // an integer of width <=64 bits, must take at least one argument, must not
331 // use its first argument (assumed to be "this") and all arguments other than
332 // the first one must be of <=64 bit integer type.
333 //
334 // Note that we test whether this copy of the function is readnone, rather
335 // than testing function attributes, which must hold for any copy of the
336 // function, even a less optimized version substituted at link time. This is
337 // sound because the virtual constant propagation optimizations effectively
338 // inline all implementations of the virtual function into each call site,
339 // rather than using function attributes to perform local optimization.
340 DenseSet<const Function *> EligibleVirtualFns;
341 // If any member of a comdat lives in MergedM, put all members of that
342 // comdat in MergedM to keep the comdat together.
343 DenseSet<const Comdat *> MergedMComdats;
344 for (GlobalVariable &GV : M.globals())
345 if (!GV.isDeclaration() && HasTypeMetadata(&GV)) {
346 if (const auto *C = GV.getComdat())
347 MergedMComdats.insert(C);
348 forEachVirtualFunction(GV.getInitializer(), [&](Function *F) {
349 auto *RT = dyn_cast<IntegerType>(F->getReturnType());
350 if (!RT || RT->getBitWidth() > 64 || F->arg_empty() ||
351 !F->arg_begin()->use_empty())
352 return;
353 for (auto &Arg : drop_begin(F->args())) {
354 auto *ArgT = dyn_cast<IntegerType>(Arg.getType());
355 if (!ArgT || ArgT->getBitWidth() > 64)
356 return;
357 }
358 if (!F->isDeclaration() &&
359 computeFunctionBodyMemoryAccess(*F, AARGetter(*F))
360 .doesNotAccessMemory())
361 EligibleVirtualFns.insert(F);
362 });
363 }
364
366 std::unique_ptr<Module> MergedM(
367 CloneModule(M, VMap, [&](const GlobalValue *GV) -> bool {
368 if (const auto *C = GV->getComdat())
369 if (MergedMComdats.count(C))
370 return true;
371 if (mustEmitToMergedModule(GV))
372 return true;
373 if (auto *F = dyn_cast<Function>(GV))
374 return EligibleVirtualFns.count(F);
375 if (auto *GVar =
377 return HasTypeMetadata(GVar);
378 return false;
379 }));
380 StripDebugInfo(*MergedM);
381 MergedM->removeModuleInlineAsm();
382
383 // Clone any llvm.*used globals to ensure the included values are
384 // not deleted.
385 cloneUsedGlobalVariables(M, *MergedM, /*CompilerUsed*/ false);
386 cloneUsedGlobalVariables(M, *MergedM, /*CompilerUsed*/ true);
387
388 for (Function &F : *MergedM)
389 if (!F.isDeclaration() && !mustEmitToMergedModule(&F)) {
390 // Reset the linkage of all functions eligible for virtual constant
391 // propagation. The canonical definitions live in the thin LTO module so
392 // that they can be imported.
394 F.setComdat(nullptr);
395 }
396
397 SetVector<GlobalValue *> CfiFunctions;
398 for (auto &F : M)
399 if ((!F.hasLocalLinkage() || F.hasAddressTaken()) && HasTypeMetadata(&F))
400 CfiFunctions.insert(&F);
401 for (auto &A : M.aliases())
402 if (auto *F = dyn_cast<Function>(A.getAliasee()))
403 if (HasTypeMetadata(F))
404 CfiFunctions.insert(&A);
405
406 // Remove all globals with type metadata, globals with comdats that live in
407 // MergedM, and aliases pointing to such globals from the thin LTO module.
408 filterModule(&M, [&](const GlobalValue *GV) {
410 if (HasTypeMetadata(GVar))
411 return false;
412 if (const auto *C = GV->getComdat())
413 if (MergedMComdats.count(C))
414 return false;
415 if (mustEmitToMergedModule(GV))
416 return false;
417 return true;
418 });
419
420 // CfiFunctions contains only symbols from M. promoteInternals tries to find
421 // match values from its first argument (the "exporting module") in
422 // CfiFunctions. So we only need CfiFunctions for the second promotion (M ->
423 // MergedM)
424 promoteInternals(*MergedM, M, ModuleId, nullptr);
425 promoteInternals(M, *MergedM, ModuleId, &CfiFunctions);
426
427 auto &Ctx = MergedM->getContext();
428 SmallVector<MDNode *, 8> CfiFunctionMDs;
429 for (auto *V : CfiFunctions) {
430 Function &F = *cast<Function>(V->getAliaseeObject());
432 F.getMetadata(LLVMContext::MD_type, Types);
433
435 Elts.push_back(MDString::get(Ctx, V->getName()));
439 else if (F.hasExternalWeakLinkage())
441 else
444 llvm::ConstantInt::get(Type::getInt8Ty(Ctx), Linkage)));
445 GlobalValue::GUID GUID = V->getGUID();
447 llvm::ConstantInt::get(Type::getInt64Ty(Ctx), GUID)));
448 append_range(Elts, Types);
449 CfiFunctionMDs.push_back(MDTuple::get(Ctx, Elts));
450 }
451
452 if(!CfiFunctionMDs.empty()) {
453 NamedMDNode *NMD = MergedM->getOrInsertNamedMetadata("cfi.functions");
454 for (auto *MD : CfiFunctionMDs)
455 NMD->addOperand(MD);
456 }
457
459 for (auto &A : M.aliases()) {
460 if (!isa<Function>(A.getAliasee()))
461 continue;
462
463 auto *F = cast<Function>(A.getAliasee());
464 FunctionAliases[F].push_back(&A);
465 }
466
467 if (!FunctionAliases.empty()) {
468 NamedMDNode *NMD = MergedM->getOrInsertNamedMetadata("aliases");
469 for (auto &Alias : FunctionAliases) {
471 Elts.push_back(MDString::get(Ctx, Alias.first->getName()));
472 for (auto *A : Alias.second)
473 Elts.push_back(MDString::get(Ctx, A->getName()));
474 NMD->addOperand(MDTuple::get(Ctx, Elts));
475 }
476 }
477
480 Function *F = M.getFunction(Name);
481 if (!F || F->use_empty())
482 return;
483
484 Symvers.push_back(MDTuple::get(
485 Ctx, {MDString::get(Ctx, Name), MDString::get(Ctx, Alias)}));
486 });
487
488 if (!Symvers.empty()) {
489 NamedMDNode *NMD = MergedM->getOrInsertNamedMetadata("symvers");
490 for (auto *MD : Symvers)
491 NMD->addOperand(MD);
492 }
493
494 simplifyExternals(*MergedM);
495
496 // FIXME: Try to re-use BSI and PFI from the original module here.
497 ProfileSummaryInfo PSI(M);
498 ModuleSummaryIndex Index = buildModuleSummaryIndex(M, nullptr, &PSI);
499
500 // Mark the merged module as requiring full LTO. We still want an index for
501 // it though, so that it can participate in summary-based dead stripping.
502 MergedM->addModuleFlag(Module::Error, "ThinLTO", uint32_t(0));
503 ModuleSummaryIndex MergedMIndex =
504 buildModuleSummaryIndex(*MergedM, nullptr, &PSI);
505
507
508 BitcodeWriter W(Buffer);
509 // Save the module hash produced for the full bitcode, which will
510 // be used in the backends, and use that in the minimized bitcode
511 // produced for the full link.
512 ModuleHash ModHash = {{0}};
513 W.writeModule(M, ShouldPreserveUseListOrder, &Index,
514 /*GenerateHash=*/true, &ModHash);
515 W.writeModule(*MergedM, ShouldPreserveUseListOrder, &MergedMIndex);
516 W.writeSymtab();
517 W.writeStrtab();
518 OS << Buffer;
519
520 // If a minimized bitcode module was requested for the thin link, only
521 // the information that is needed by thin link will be written in the
522 // given OS (the merged module will be written as usual).
523 if (ThinLinkOS) {
524 Buffer.clear();
525 BitcodeWriter W2(Buffer);
527 W2.writeThinLinkBitcode(M, Index, ModHash);
528 W2.writeModule(*MergedM, /*ShouldPreserveUseListOrder=*/false,
529 &MergedMIndex);
530 W2.writeSymtab();
531 W2.writeStrtab();
532 *ThinLinkOS << Buffer;
533 }
534}
535
536// Check if the LTO Unit splitting has been enabled.
537bool enableSplitLTOUnit(Module &M) {
538 bool EnableSplitLTOUnit = false;
540 M.getModuleFlag("EnableSplitLTOUnit")))
541 EnableSplitLTOUnit = MD->getZExtValue();
542 return EnableSplitLTOUnit;
543}
544
545// Returns whether this module needs to be split (if splitting is enabled).
546bool requiresSplit(Module &M) {
547 for (auto &GO : M.global_objects()) {
548 if (GO.hasMetadata(LLVMContext::MD_type))
549 return true;
550 if (mustEmitToMergedModule(&GO))
551 return true;
552 }
553 return false;
554}
555
556bool writeThinLTOBitcode(raw_ostream &OS, raw_ostream *ThinLinkOS,
557 function_ref<AAResults &(Function &)> AARGetter,
558 Module &M, const ModuleSummaryIndex *Index,
559 const bool ShouldPreserveUseListOrder) {
560 std::unique_ptr<ModuleSummaryIndex> NewIndex = nullptr;
561 // See if this module needs to be split. If so, we try to split it
562 // or at least promote type ids to enable WPD.
563 if (requiresSplit(M)) {
564 if (enableSplitLTOUnit(M)) {
565 splitAndWriteThinLTOBitcode(OS, ThinLinkOS, AARGetter, M,
566 ShouldPreserveUseListOrder);
567 return true;
568 }
569 // Promote type ids as needed for index-based WPD.
570 std::string ModuleId = getUniqueModuleId(&M);
571 if (!ModuleId.empty()) {
572 promoteTypeIds(M, ModuleId);
573 // Need to rebuild the index so that it contains type metadata
574 // for the newly promoted type ids.
575 // FIXME: Probably should not bother building the index at all
576 // in the caller of writeThinLTOBitcode (which does so via the
577 // ModuleSummaryIndexAnalysis pass), since we have to rebuild it
578 // anyway whenever there is type metadata (here or in
579 // splitAndWriteThinLTOBitcode). Just always build it once via the
580 // buildModuleSummaryIndex when Module(s) are ready.
581 ProfileSummaryInfo PSI(M);
582 NewIndex = std::make_unique<ModuleSummaryIndex>(
583 buildModuleSummaryIndex(M, nullptr, &PSI));
584 Index = NewIndex.get();
585 }
586 }
587
588 // Write it out as an unsplit ThinLTO module.
589
590 // Save the module hash produced for the full bitcode, which will
591 // be used in the backends, and use that in the minimized bitcode
592 // produced for the full link.
593 ModuleHash ModHash = {{0}};
594 WriteBitcodeToFile(M, OS, ShouldPreserveUseListOrder, Index,
595 /*GenerateHash=*/true, &ModHash);
596 // If a minimized bitcode module was requested for the thin link, only
597 // the information that is needed by thin link will be written in the
598 // given OS.
599 if (ThinLinkOS && Index)
600 writeThinLinkBitcodeToFile(M, *ThinLinkOS, *Index, ModHash);
601 return false;
602}
603
604} // anonymous namespace
605
610
611 bool Changed = writeThinLTOBitcode(
612 OS, ThinLinkOS,
613 [&FAM](Function &F) -> AAResults & {
614 return FAM.getResult<AAManager>(F);
615 },
617 ShouldPreserveUseListOrder);
618
620}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
This is the interface for LLVM's primary stateless and local alias analysis.
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
DXIL Finalize Linkage
Provides passes for computing function attributes based on interprocedural analyses.
Module.h This file contains the declarations for the Module class.
This header defines various interfaces for pass management in LLVM.
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
This is the interface to build a ModuleSummaryIndex for a module.
FunctionAnalysisManager FAM
if(PassOpts->AAPipeline)
A manager for alias analyses.
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Value * getArgOperand(unsigned i) const
void setArgOperand(unsigned i, Value *v)
This class represents a function call, abstracting a target machine's calling convention.
static ConstantAsMetadata * get(Constant *C)
Definition Metadata.h:537
This is an important base class in LLVM.
Definition Constant.h:43
LLVM_ABI void removeDeadConstantUsers() const
If there are any dead constant users dangling off of this constant, remove them.
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:223
std::pair< iterator, bool > try_emplace(KeyT &&Key, Ts &&...Args)
Definition DenseMap.h:299
unsigned size() const
Definition DenseMap.h:172
bool empty() const
Definition DenseMap.h:171
iterator end()
Definition DenseMap.h:141
Implements a dense probed hash-table based set.
Definition DenseSet.h:281
static LLVM_ABI FunctionType * get(Type *Result, ArrayRef< Type * > Params, bool isVarArg)
This static method is the primary way of constructing a FunctionType.
static Function * Create(FunctionType *Ty, LinkageTypes Linkage, unsigned AddrSpace, const Twine &N="", Module *M=nullptr)
Definition Function.h:168
void setAttributes(AttributeList Attrs)
Set the attribute list for this Function.
Definition Function.h:331
void copyAttributesFrom(const Function *Src)
copyAttributesFrom - copy all additional attributes (those not needed to create a Function) from the ...
Definition Function.cpp:842
static LLVM_ABI GlobalAlias * create(Type *Ty, unsigned AddressSpace, LinkageTypes Linkage, const Twine &Name, Constant *Aliasee, Module *Parent)
If a parent module is specified, the alias is automatically inserted into the end of the specified mo...
Definition Globals.cpp:692
LLVM_ABI void setMetadata(unsigned KindID, MDNode *Node)
Set a particular kind of metadata attachment.
LLVM_ABI bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
Definition Globals.cpp:408
uint64_t GUID
Declare a type to represent a global unique identifier for a global value.
LLVM_ABI const Comdat * getComdat() const
Definition Globals.cpp:274
LLVM_ABI const GlobalObject * getAliaseeObject() const
Definition Globals.cpp:521
LLVM_ABI void eraseFromParent()
This method unlinks 'this' from the containing module and deletes it.
Definition Globals.cpp:158
@ HiddenVisibility
The GV is hidden.
Definition GlobalValue.h:69
void setVisibility(VisibilityTypes V)
LLVM_ABI void reassignGUID()
Recompute and assign a GUID to this value, replacing the existing GUID.
Definition Globals.cpp:96
@ ExternalLinkage
Externally visible function.
Definition GlobalValue.h:53
@ AvailableExternallyLinkage
Available for inspection, not emission.
Definition GlobalValue.h:54
Metadata node.
Definition Metadata.h:1069
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1567
static LLVM_ABI MDString * get(LLVMContext &Context, StringRef Str)
Definition Metadata.cpp:615
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1513
This class implements a map that also provides access to all stored values in a deterministic order.
Definition MapVector.h:38
bool empty() const
Definition MapVector.h:79
static LLVM_ABI MetadataAsValue * get(LLVMContext &Context, Metadata *MD)
Definition Metadata.cpp:111
Root of the metadata hierarchy.
Definition Metadata.h:64
Analysis pass to provide the ModuleSummaryIndex object.
Class to hold module path string table and global value map, and encapsulate methods for operating on...
static LLVM_ABI void CollectAsmSymvers(const Module &M, function_ref< void(StringRef, StringRef)> AsmSymver)
Parse inline ASM and collect the symvers directives that are defined in the current module.
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:67
@ Error
Emits an error if two values disagree, otherwise the resulting value is that of the operands.
Definition Module.h:120
iterator_range< global_object_iterator > global_objects()
Definition Module.cpp:461
GlobalValue * getNamedValue(StringRef Name) const
Return the global value in the module with the specified name, of arbitrary type.
Definition Module.cpp:177
Comdat * getOrInsertComdat(StringRef Name)
Return the Comdat in the module with the specified name.
Definition Module.cpp:631
iterator_range< global_value_iterator > global_values()
Definition Module.cpp:469
A tuple of MDNodes.
Definition Metadata.h:1755
LLVM_ABI void addOperand(MDNode *M)
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses none()
Convenience factory function for the empty preserved set.
Definition Analysis.h:115
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
Analysis providing profile information.
A vector that has set insertion semantics.
Definition SetVector.h:57
bool insert(const value_type &X)
Insert a new element into the SetVector.
Definition SetVector.h:157
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
LLVM_ABI PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM)
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
static LLVM_ABI IntegerType * getInt64Ty(LLVMContext &C)
Definition Type.cpp:310
static LLVM_ABI Type * getVoidTy(LLVMContext &C)
Definition Type.cpp:282
static LLVM_ABI IntegerType * getInt8Ty(LLVMContext &C)
Definition Type.cpp:307
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
LLVM Value Representation.
Definition Value.h:75
LLVM_ABI void setName(const Twine &Name)
Change the name of the value.
Definition Value.cpp:394
bool use_empty() const
Definition Value.h:346
iterator_range< use_iterator > uses()
Definition Value.h:380
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:319
LLVM_ABI void takeName(Value *V)
Transfer the name from V to this value.
Definition Value.cpp:400
std::pair< iterator, bool > insert(const ValueT &V)
Definition DenseSet.h:209
size_type count(const_arg_type_t< ValueT > V) const
Return 1 if the specified key is in the set, 0 otherwise.
Definition DenseSet.h:187
An efficient, type-erasing, non-owning reference to a callable.
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
Changed
LLVM_ABI Function * getDeclarationIfExists(const Module *M, ID id)
Look up the Function declaration of the intrinsic id in the Module M and return it if it exists.
LLVM_ABI bool isJumpTableCanonical(Function *F)
std::enable_if_t< detail::IsValidPointer< X, Y >::value, X * > extract_or_null(Y &&MD)
Extract a Value from Metadata, allowing null.
Definition Metadata.h:683
This is an optimization pass for GlobalISel generic memory operations.
LLVM_ABI MemoryEffects computeFunctionBodyMemoryAccess(Function &F, AAResults &AAR)
Returns the memory access properties of this copy of the function.
LLVM_ABI void WriteBitcodeToFile(const Module &M, raw_ostream &Out, bool ShouldPreserveUseListOrder=false, const ModuleSummaryIndex *Index=nullptr, bool GenerateHash=false, ModuleHash *ModHash=nullptr)
Write the specified module to the specified raw output stream.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
std::array< uint32_t, 5 > ModuleHash
160 bits SHA1
LLVM_ABI void writeThinLinkBitcodeToFile(const Module &M, raw_ostream &Out, const ModuleSummaryIndex &Index, const ModuleHash &ModHash)
Write the specified thin link bitcode file (i.e., the minimized bitcode file) to the given raw output...
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition STLExtras.h:2208
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
Definition STLExtras.h:633
LLVM_ABI bool convertToDeclaration(GlobalValue &GV)
Converts value GV to declaration, or replaces with a declaration if it is an alias.
InnerAnalysisManagerProxy< FunctionAnalysisManager, Module > FunctionAnalysisManagerModuleProxy
Provide the FunctionAnalysisManager to Module proxy.
LLVM_ABI ModuleSummaryIndex buildModuleSummaryIndex(const Module &M, std::function< BlockFrequencyInfo *(const Function &F)> GetBFICallback, ProfileSummaryInfo *PSI, std::function< const StackSafetyInfo *(const Function &F)> GetSSICallback=[](const Function &F) -> const StackSafetyInfo *{ return nullptr;})
Direct function to compute a ModuleSummaryIndex from a given module.
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
LLVM_ABI std::string getUniqueModuleId(Module *M)
Produce a unique identifier for this module by taking the MD5 sum of the names of the module's strong...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
LLVM_ABI bool StripDebugInfo(Module &M)
Strip debug info in the module if it exists.
LLVM_ABI void appendToCompilerUsed(Module &M, ArrayRef< GlobalValue * > Values)
Adds global values to the llvm.compiler.used list.
DWARFExpression::Operation Op
ValueMap< const Value *, WeakTrackingVH > ValueToValueMapTy
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
LLVM_ABI std::unique_ptr< Module > CloneModule(const Module &M)
Return an exact copy of the specified module.
LLVM_ABI void appendToUsed(Module &M, ArrayRef< GlobalValue * > Values)
Adds global values to the llvm.used list.
CfiFunctionLinkage
The type of CFI jumptable needed for a function.
@ CFL_WeakDeclaration
AnalysisManager< Module > ModuleAnalysisManager
Convenience typedef for the Module analysis manager.
Definition MIRParser.h:39
LLVM_ABI GlobalVariable * collectUsedGlobalVariables(const Module &M, SmallVectorImpl< GlobalValue * > &Vec, bool CompilerUsed)
Given "llvm.used" or "llvm.compiler.used" as a global name, collect the initializer elements of that ...
Definition Module.cpp:932