LLVM 24.0.0git
LowerTypeTests.cpp
Go to the documentation of this file.
1//===- LowerTypeTests.cpp - type metadata lowering pass -------------------===//
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 pass lowers type metadata and calls to the llvm.type.test intrinsic.
10// It also ensures that globals are properly laid out for the
11// llvm.icall.branch.funnel intrinsic.
12// See http://llvm.org/docs/TypeMetadata.html for more information.
13//
14//===----------------------------------------------------------------------===//
15
17#include "IPOOptions.h"
18#include "llvm/ADT/APInt.h"
19#include "llvm/ADT/ArrayRef.h"
20#include "llvm/ADT/DenseMap.h"
23#include "llvm/ADT/MapVector.h"
25#include "llvm/ADT/STLExtras.h"
26#include "llvm/ADT/SetVector.h"
28#include "llvm/ADT/Statistic.h"
29#include "llvm/ADT/StringRef.h"
40#include "llvm/IR/Attributes.h"
41#include "llvm/IR/BasicBlock.h"
42#include "llvm/IR/Constant.h"
43#include "llvm/IR/Constants.h"
44#include "llvm/IR/DIBuilder.h"
45#include "llvm/IR/DataLayout.h"
47#include "llvm/IR/Function.h"
48#include "llvm/IR/GlobalAlias.h"
50#include "llvm/IR/GlobalValue.h"
52#include "llvm/IR/IRBuilder.h"
53#include "llvm/IR/InlineAsm.h"
54#include "llvm/IR/Instruction.h"
57#include "llvm/IR/Intrinsics.h"
58#include "llvm/IR/LLVMContext.h"
59#include "llvm/IR/MDBuilder.h"
60#include "llvm/IR/Metadata.h"
61#include "llvm/IR/Module.h"
64#include "llvm/IR/Operator.h"
65#include "llvm/IR/PassManager.h"
68#include "llvm/IR/Type.h"
69#include "llvm/IR/Use.h"
70#include "llvm/IR/User.h"
71#include "llvm/IR/Value.h"
75#include "llvm/Support/Debug.h"
76#include "llvm/Support/Error.h"
86#include "llvm/Transforms/IPO.h"
90#include <algorithm>
91#include <cassert>
92#include <cstdint>
93#include <optional>
94#include <set>
95#include <string>
96#include <system_error>
97#include <utility>
98#include <vector>
99
100using namespace llvm;
101using namespace lowertypetests;
102
103#define DEBUG_TYPE "lowertypetests"
104
105STATISTIC(ByteArraySizeBits, "Byte array size in bits");
106STATISTIC(ByteArraySizeBytes, "Byte array size in bytes");
107STATISTIC(NumByteArraysCreated, "Number of byte arrays created");
108STATISTIC(NumTypeTestCallsLowered, "Number of type test calls lowered");
109STATISTIC(NumTypeIdDisjointSets, "Number of disjoint sets of type identifiers");
110
112 if (Offset < ByteOffset)
113 return false;
114
115 if ((Offset - ByteOffset) % (uint64_t(1) << AlignLog2) != 0)
116 return false;
117
118 uint64_t BitOffset = (Offset - ByteOffset) >> AlignLog2;
119 if (BitOffset >= BitSize)
120 return false;
121
122 return Bits.count(BitSize - 1 - BitOffset);
123}
124
126 OS << "offset " << ByteOffset << " size " << BitSize << " align "
127 << (1 << AlignLog2);
128
129 if (isAllOnes()) {
130 OS << " all-ones\n";
131 return;
132 }
133
134 OS << " { ";
135 for (uint64_t B : Bits)
136 OS << B << ' ';
137 OS << "}\n";
138}
139
141 if (Min > Max)
142 Min = 0;
143
144 // Normalize each offset against the minimum observed offset, and compute
145 // the bitwise OR of each of the offsets. The number of trailing zeros
146 // in the mask gives us the log2 of the alignment of all offsets, which
147 // allows us to compress the bitset by only storing one bit per aligned
148 // address.
149 uint64_t Mask = 0;
150 for (uint64_t &Offset : Offsets) {
151 Offset -= Min;
152 Mask |= Offset;
153 }
154
155 BitSetInfo BSI;
156 BSI.ByteOffset = Min;
157
158 BSI.AlignLog2 = 0;
159 if (Mask != 0)
160 BSI.AlignLog2 = llvm::countr_zero(Mask);
161
162 // Build the compressed bitset while normalizing the offsets against the
163 // computed alignment.
164 BSI.BitSize = ((Max - Min) >> BSI.AlignLog2) + 1;
165 for (uint64_t Offset : Offsets) {
166 Offset >>= BSI.AlignLog2;
167 // We invert the order of bits when adding them to the bitset. This is
168 // because the offset that we test against is computed by subtracting the
169 // address that we are testing from the global's address, which means that
170 // the offset increases as the tested address decreases.
171 BSI.Bits.insert(BSI.BitSize - 1 - Offset);
172 }
173
174 return BSI;
175}
176
177void GlobalLayoutBuilder::addFragment(const std::set<uint64_t> &F) {
178 assert(Fragments.front().empty() && "Cannot add fragments after build()");
179
180 // Create a new fragment to hold the layout for F.
181 Fragments.emplace_back();
182 std::vector<uint64_t> &Fragment = Fragments.back();
183 uint64_t FragmentIndex = Fragments.size() - 1;
184
185 std::vector<std::vector<uint64_t>> SubFragments;
186 for (auto ObjIndex : F) {
187 uint64_t OldFragmentIndex = FragmentMap[ObjIndex];
188 if (OldFragmentIndex == 0) {
189 // We haven't seen this object index before, so just add it to the current
190 // fragment.
191 SubFragments.push_back({ObjIndex});
192 } else if (!Fragments[OldFragmentIndex].empty()) {
193 // This index belongs to an existing fragment. Copy the elements of the
194 // old fragment into this one and clear the old fragment. We don't update
195 // the fragment map just yet, this ensures that any further references to
196 // indices from the old fragment in this fragment do not insert any more
197 // indices.
198 SubFragments.push_back(std::move(Fragments[OldFragmentIndex]));
199 }
200 }
201
202 if (Less) {
203 llvm::stable_sort(SubFragments, [&](const std::vector<uint64_t> &A,
204 const std::vector<uint64_t> &B) {
205 return Less(A.back(), B.back());
206 });
207 }
208
209 for (auto &SF : SubFragments)
210 llvm::append_range(Fragment, std::move(SF));
211
212 // Update the fragment map to point our object indices to this fragment.
213 for (uint64_t ObjIndex : Fragment)
214 FragmentMap[ObjIndex] = FragmentIndex;
215}
216
217const std::vector<uint64_t> &GlobalLayoutBuilder::build() {
218 if (Less) {
219 // If multiple root fragments remain (e.g. disjoint signatures with no
220 // generalized type), order them so the one containing the hottest function
221 // is placed last.
222 llvm::erase_if(Fragments,
223 [](const std::vector<uint64_t> &F) { return F.empty(); });
224 llvm::stable_sort(Fragments, [&](const std::vector<uint64_t> &FA,
225 const std::vector<uint64_t> &FB) {
226 return Less(FA.back(), FB.back());
227 });
228 }
229
230 std::vector<uint64_t> Layout;
231 Layout.reserve(FragmentMap.size());
232 for (auto &&F : Fragments)
233 llvm::append_range(Layout, F);
234 Fragments.clear();
235 Fragments.push_back(std::move(Layout));
236 return Fragments.front();
237}
238
239void ByteArrayBuilder::allocate(const std::set<uint64_t> &Bits,
240 uint64_t BitSize, uint64_t &AllocByteOffset,
241 uint8_t &AllocMask) {
242 // Find the smallest current allocation.
243 unsigned Bit = 0;
244 for (unsigned I = 1; I != BitsPerByte; ++I)
245 if (BitAllocs[I] < BitAllocs[Bit])
246 Bit = I;
247
248 AllocByteOffset = BitAllocs[Bit];
249
250 // Add our size to it.
251 unsigned ReqSize = AllocByteOffset + BitSize;
252 BitAllocs[Bit] = ReqSize;
253 if (Bytes.size() < ReqSize)
254 Bytes.resize(ReqSize);
255
256 // Set our bits.
257 AllocMask = 1 << Bit;
258 for (uint64_t B : Bits)
259 Bytes[AllocByteOffset + B] |= AllocMask;
260}
261
263 if (F->isDeclarationForLinker())
264 return false;
266 F->getParent()->getModuleFlag("CFI Canonical Jump Tables"));
267 if (!CI || !CI->isZero())
268 return true;
269 return F->hasFnAttribute("cfi-canonical-jump-table");
270}
271
273 if (MDNode *MD = GO.getMetadata(LLVMContext::MD_associated))
274 if (auto *AssocVM = dyn_cast_or_null<ValueAsMetadata>(MD->getOperand(0)))
275 if (auto *AssocGO = dyn_cast<GlobalObject>(AssocVM->getValue()))
276 if (AssocGO->hasMetadata(LLVMContext::MD_type))
277 return true;
278 return GO.hasMetadata(LLVMContext::MD_type);
279}
280
282 SetVector<GlobalValue *> CfiFunctions;
283 for (auto &F : M)
284 if ((!F.hasLocalLinkage() || F.hasAddressTaken()) && hasTypeMetadata(F))
285 CfiFunctions.insert(&F);
286 for (auto &A : M.aliases())
287 if (auto *F = dyn_cast<Function>(A.getAliasee()))
288 if (hasTypeMetadata(*F))
289 CfiFunctions.insert(&A);
290 return CfiFunctions;
291}
292
293/// Extracts a numeric type identifier from an MDNode containing type metadata.
295 // This check excludes vtables for classes inside anonymous namespaces.
296 auto TM = dyn_cast<ValueAsMetadata>(MD.getOperand(1));
297 if (!TM)
298 return nullptr;
299 auto C = dyn_cast_or_null<ConstantInt>(TM->getValue());
300 if (!C)
301 return nullptr;
302 // We are looking for i64 constants.
303 if (C->getBitWidth() != 64)
304 return nullptr;
305
306 return C;
307}
308
310 SetVector<uint64_t> TypeIds;
312 for (const GlobalObject &GO : M.global_objects()) {
313 Types.clear();
314 GO.getMetadata(LLVMContext::MD_type, Types);
315 for (MDNode *Type : Types)
316 if (ConstantInt *TypeId = extractNumericTypeId(*Type))
317 TypeIds.insert(TypeId->getZExtValue());
318 }
319
320 if (NamedMDNode *CfiFunctionsMD = M.getNamedMetadata("cfi.functions")) {
321 for (auto *Func : CfiFunctionsMD->operands()) {
322 assert(Func->getNumOperands() >= 3);
323 assert(isa<ConstantAsMetadata>(Func->getOperand(2)));
324 for (unsigned I = 3; I < Func->getNumOperands(); ++I)
325 if (ConstantInt *TypeId =
326 extractNumericTypeId(*cast<MDNode>(Func->getOperand(I))))
327 TypeIds.insert(TypeId->getZExtValue());
328 }
329 }
330 return TypeIds;
331}
332
333namespace {
334
335/// The type of CFI jumptable needed for a function.
336enum class CfiFunctionLinkage : uint8_t {
337 Definition = 0,
338 Declaration = 1,
339 WeakDeclaration = 2,
340};
341
342/// The hotness of a CFI jumptable function entry.
343class CfiFunctionHotness {
344 enum class Kind : uint8_t {
345 Unknown = 0, // It's higher rank than Cold, but convenient to store as zero.
346 Cold = 1,
347 Other = 2,
348 Hot = 3,
349 };
350
351 Kind Type = Kind::Unknown;
352
353 CfiFunctionHotness(Kind Type) : Type(Type) {}
354
355public:
356 CfiFunctionHotness() = default;
357
358 // Computes the execution weight for F across its entry count and basic block
359 // counts. Placing the hottest function (i.e. the function with the highest
360 // weight) as the last jump table entry makes it more likely to benefit from
361 // the SHT_LLVM_CFI_JUMP_TABLE last-entry optimization and locks the jump
362 // table into the target's section, which is likely hot.
363 // The most important goal is to put functions which end up in .hot at the
364 // end of jumptable, to keep jump table in the same section.
365 static CfiFunctionHotness
366 fromFunction(Function &F, ProfileSummaryInfo &PSI,
367 function_ref<const BlockFrequencyInfo &(Function &)> BFIGetter) {
368 if (F.isDeclaration())
369 return Kind::Unknown;
370
371 // We want to mimic CodeGenPrepare::_run to match section assignments.
372 const BlockFrequencyInfo &BFI = BFIGetter(F);
373 if (F.hasFnAttribute(Attribute::Hot) ||
374 PSI.isFunctionHotInCallGraph(&F, BFI)) {
375 return Kind::Hot;
376 }
377
378 if (PSI.isFunctionColdInCallGraph(&F, BFI) ||
379 F.hasFnAttribute(Attribute::Cold)) {
380 return Kind::Cold;
381 }
382
384 ? Kind::Unknown
385 : Kind::Other;
386 }
387
388 static CfiFunctionHotness fromUint6(uint8_t V) {
389 return CfiFunctionHotness(static_cast<Kind>(V & 0x3));
390 }
391
392 uint8_t asUint6() const { return static_cast<uint8_t>(Type) & 0x3; }
393
394 bool operator==(const CfiFunctionHotness &Other) const {
395 return Type == Other.Type;
396 }
397
398 bool operator<(const CfiFunctionHotness &Other) const {
399 auto Rank = [](Kind K) -> int {
400 return (K == Kind::Cold) ? -1 : static_cast<int>(K);
401 };
402 return Rank(Type) < Rank(Other.Type);
403 }
404};
405
406} // namespace
407
408static CfiFunctionLinkage decodeCfiFunctionLinkage(uint8_t Encoded) {
409 return static_cast<CfiFunctionLinkage>(Encoded & 0x3);
410}
411
412static CfiFunctionHotness decodeCfiFunctionHotness(uint8_t Encoded) {
413 return CfiFunctionHotness::fromUint6(Encoded >> 2);
414}
415
416static uint8_t encodeCfiFunctionLinkage(CfiFunctionLinkage Linkage,
417 CfiFunctionHotness Hotness) {
418 uint8_t Encoded =
419 (Hotness.asUint6() << 2) | (static_cast<uint8_t>(Linkage) & 0x3);
421 assert(decodeCfiFunctionHotness(Encoded) == Hotness);
422 return Encoded;
423}
424
426 Module &DestM, ArrayRef<GlobalValue *> CfiFunctions,
428 function_ref<const BlockFrequencyInfo &(Function &)> BFIGetter) {
429 const IPOOptions &Opts = getIPOOptions(DestM);
430 auto &Ctx = DestM.getContext();
431 SmallVector<MDNode *, 8> CfiFunctionMDs;
432 for (auto *V : CfiFunctions) {
433 Function &F = *cast<Function>(V->getAliaseeObject());
435 F.getMetadata(LLVMContext::MD_type, Types);
436
438 Elts.push_back(MDString::get(Ctx, V->getName()));
439 CfiFunctionLinkage Linkage = CfiFunctionLinkage::Declaration;
441 Linkage = CfiFunctionLinkage::Definition;
442 else if (F.hasExternalWeakLinkage())
443 Linkage = CfiFunctionLinkage::WeakDeclaration;
444
445 CfiFunctionHotness Hotness =
446 Opts.reorder_cfi_jump_tables_profiles
447 ? CfiFunctionHotness::fromFunction(F, PSI, BFIGetter)
448 : CfiFunctionHotness();
449
450 uint8_t EncodedLinkage = encodeCfiFunctionLinkage(Linkage, Hotness);
451
453 llvm::ConstantInt::get(Type::getInt8Ty(Ctx), EncodedLinkage)));
454 GlobalValue::GUID GUID = V->getGUID();
456 llvm::ConstantInt::get(Type::getInt64Ty(Ctx), GUID)));
457 append_range(Elts, Types);
458 CfiFunctionMDs.push_back(MDTuple::get(Ctx, Elts));
459 }
460
461 if (!CfiFunctionMDs.empty()) {
462 NamedMDNode *NMD = DestM.getOrInsertNamedMetadata("cfi.functions");
463 for (auto *MD : CfiFunctionMDs)
464 NMD->addOperand(MD);
465 }
466}
467
468static void createCfiAliasesMetadata(Module &DestM, const Module &SrcM) {
469 auto &Ctx = DestM.getContext();
471 for (const auto &A : SrcM.aliases()) {
472 if (!isa<Function>(A.getAliasee()))
473 continue;
474
475 const auto *F = cast<Function>(A.getAliasee());
476 FunctionAliases[F].push_back(&A);
477 }
478
479 if (!FunctionAliases.empty()) {
480 NamedMDNode *NMD = DestM.getOrInsertNamedMetadata("aliases");
481 for (auto &Alias : FunctionAliases) {
483 Elts.push_back(MDString::get(Ctx, Alias.first->getName()));
484 for (auto *A : Alias.second)
485 Elts.push_back(MDString::get(Ctx, A->getName()));
486 NMD->addOperand(MDTuple::get(Ctx, Elts));
487 }
488 }
489}
490
491static void createCfiSymversMetadata(Module &DestM, const Module &SrcM) {
492 auto &Ctx = DestM.getContext();
495 SrcM, [&](StringRef Name, StringRef Alias) {
496 const Function *F = SrcM.getFunction(Name);
497 if (!F || F->use_empty())
498 return;
499
500 Symvers.push_back(MDTuple::get(
501 Ctx, {MDString::get(Ctx, Name), MDString::get(Ctx, Alias)}));
502 });
503
504 if (!Symvers.empty()) {
505 NamedMDNode *NMD = DestM.getOrInsertNamedMetadata("symvers");
506 for (auto *MD : Symvers)
507 NMD->addOperand(MD);
508 }
509}
510
512 Module &DestM, const Module &SrcM, ArrayRef<GlobalValue *> CfiFunctions,
514 function_ref<const BlockFrequencyInfo &(Function &)> BFIGetter) {
515 createCfiFunctionsMetadata(DestM, CfiFunctions, PSI, BFIGetter);
516 createCfiAliasesMetadata(DestM, SrcM);
517 createCfiSymversMetadata(DestM, SrcM);
518}
519
520namespace {
521
522struct ByteArrayInfo {
523 std::set<uint64_t> Bits;
524 uint64_t BitSize;
525 GlobalVariable *ByteArray;
526 GlobalVariable *MaskGlobal;
527 uint8_t *MaskPtr = nullptr;
528};
529
530/// A POD-like structure that we use to store a global reference together with
531/// its metadata types. In this pass we frequently need to query the set of
532/// metadata types referenced by a global, which at the IR level is an expensive
533/// operation involving a map lookup; this data structure helps to reduce the
534/// number of times we need to do this lookup.
535class GlobalTypeMember final : TrailingObjects<GlobalTypeMember, MDNode *> {
536 friend TrailingObjects;
537
538 GlobalObject *GO;
539 size_t NTypes;
540
541 // For functions: true if the jump table is canonical. This essentially means
542 // whether the canonical address (i.e. the symbol table entry) of the function
543 // is provided by the local jump table. This is normally the same as whether
544 // the function is defined locally, but if canonical jump tables are disabled
545 // by the user then the jump table never provides a canonical definition.
546 bool IsJumpTableCanonical;
547
548 // For functions: true if this function is either defined or used in a thinlto
549 // module and its jumptable entry needs to be exported to thinlto backends.
550 bool IsExported;
551
552public:
553 static GlobalTypeMember *create(BumpPtrAllocator &Alloc, GlobalObject *GO,
554 bool IsJumpTableCanonical, bool IsExported,
555 ArrayRef<MDNode *> Types) {
556 auto *GTM = static_cast<GlobalTypeMember *>(Alloc.Allocate(
557 totalSizeToAlloc<MDNode *>(Types.size()), alignof(GlobalTypeMember)));
558 GTM->GO = GO;
559 GTM->NTypes = Types.size();
560 GTM->IsJumpTableCanonical = IsJumpTableCanonical;
561 GTM->IsExported = IsExported;
562 llvm::copy(Types, GTM->getTrailingObjects());
563 return GTM;
564 }
565
566 GlobalObject *getGlobal() const {
567 return GO;
568 }
569
570 bool isJumpTableCanonical() const {
571 return IsJumpTableCanonical;
572 }
573
574 bool isExported() const {
575 return IsExported;
576 }
577
578 ArrayRef<MDNode *> types() const { return getTrailingObjects(NTypes); }
579};
580
581struct ICallBranchFunnel final
582 : TrailingObjects<ICallBranchFunnel, GlobalTypeMember *> {
583 static ICallBranchFunnel *create(BumpPtrAllocator &Alloc, CallInst *CI,
585 unsigned UniqueId) {
586 auto *Call = static_cast<ICallBranchFunnel *>(
587 Alloc.Allocate(totalSizeToAlloc<GlobalTypeMember *>(Targets.size()),
588 alignof(ICallBranchFunnel)));
589 Call->CI = CI;
590 Call->UniqueId = UniqueId;
591 Call->NTargets = Targets.size();
592 llvm::copy(Targets, Call->getTrailingObjects());
593 return Call;
594 }
595
596 CallInst *CI;
597 ArrayRef<GlobalTypeMember *> targets() const {
598 return getTrailingObjects(NTargets);
599 }
600
601 unsigned UniqueId;
602
603private:
604 size_t NTargets;
605};
606
607struct ScopedSaveAliaseesAndUsed {
608 Module &M;
610 std::vector<std::pair<GlobalAlias *, Function *>> FunctionAliases;
611 std::vector<std::pair<GlobalIFunc *, Function *>> ResolverIFuncs;
612
613 // This function only removes functions from llvm.used and llvm.compiler.used.
614 // We cannot remove global variables because they need to follow RAUW, as
615 // they may be deleted by buildBitSetsFromGlobalVariables.
616 void collectAndEraseUsedFunctions(Module &M,
617 SmallVectorImpl<GlobalValue *> &Vec,
618 bool CompilerUsed) {
619 auto *GV = collectUsedGlobalVariables(M, Vec, CompilerUsed);
620 if (!GV)
621 return;
622 // There's no API to only remove certain array elements from
623 // llvm.used/llvm.compiler.used, so we remove all of them and add back only
624 // the non-functions.
625 GV->eraseFromParent();
626 auto NonFuncBegin =
627 std::stable_partition(Vec.begin(), Vec.end(), [](GlobalValue *GV) {
628 return isa<Function>(GV);
629 });
630 if (CompilerUsed)
631 appendToCompilerUsed(M, {NonFuncBegin, Vec.end()});
632 else
633 appendToUsed(M, {NonFuncBegin, Vec.end()});
634 Vec.resize(NonFuncBegin - Vec.begin());
635 }
636
637 ScopedSaveAliaseesAndUsed(Module &M) : M(M) {
638 // The users of this class want to replace all function references except
639 // for aliases and llvm.used/llvm.compiler.used with references to a jump
640 // table. We avoid replacing aliases in order to avoid introducing a double
641 // indirection (or an alias pointing to a declaration in ThinLTO mode), and
642 // we avoid replacing llvm.used/llvm.compiler.used because these global
643 // variables describe properties of the global, not the jump table (besides,
644 // offseted references to the jump table in llvm.used are invalid).
645 // Unfortunately, LLVM doesn't have a "RAUW except for these (possibly
646 // indirect) users", so what we do is save the list of globals referenced by
647 // llvm.used/llvm.compiler.used and aliases, erase the used lists, let RAUW
648 // replace the aliasees and then set them back to their original values at
649 // the end.
650 collectAndEraseUsedFunctions(M, Used, false);
651 collectAndEraseUsedFunctions(M, CompilerUsed, true);
652
653 for (auto &GA : M.aliases()) {
654 // FIXME: This should look past all aliases not just interposable ones,
655 // see discussion on D65118.
656 if (auto *F = dyn_cast<Function>(GA.getAliasee()->stripPointerCasts()))
657 FunctionAliases.push_back({&GA, F});
658 }
659
660 for (auto &GI : M.ifuncs())
661 if (auto *F = dyn_cast<Function>(GI.getResolver()->stripPointerCasts()))
662 ResolverIFuncs.push_back({&GI, F});
663 }
664
665 ~ScopedSaveAliaseesAndUsed() {
666 appendToUsed(M, Used);
667 appendToCompilerUsed(M, CompilerUsed);
668
669 for (auto P : FunctionAliases)
670 P.first->setAliasee(P.second);
671
672 for (auto P : ResolverIFuncs) {
673 // This does not preserve pointer casts that may have been stripped by the
674 // constructor, but the resolver's type is different from that of the
675 // ifunc anyway.
676 P.first->setResolver(P.second);
677 }
678 }
679};
680
681class LowerTypeTestsModule {
682 const IPOOptions &Opts;
683 Module &M;
684
685 ModuleSummaryIndex *ExportSummary;
686 const ModuleSummaryIndex *ImportSummary;
687
688 Triple::ArchType Arch;
689 Triple::ObjectFormatType ObjectFormat;
690
691 // Determines which kind of Thumb jump table we generate. If arch is
692 // either 'arm' or 'thumb' we need to find this out, because
693 // selectJumpTableArmEncoding may decide to use Thumb in either case.
694 bool CanUseArmJumpTable = false, CanUseThumbBWJumpTable = false;
695
696 // Cache variable used by hasBranchTargetEnforcement().
697 int HasBranchTargetEnforcement = -1;
698
699 // Map from function to hotness passed via cfi.functions metadata.
700 DenseMap<const Function *, CfiFunctionHotness> FunctionSummaryHotness;
701
702 IntegerType *Int1Ty = Type::getInt1Ty(M.getContext());
703 IntegerType *Int8Ty = Type::getInt8Ty(M.getContext());
704 PointerType *PtrTy = PointerType::getUnqual(M.getContext());
705 ArrayType *Int8Arr0Ty = ArrayType::get(Type::getInt8Ty(M.getContext()), 0);
706 IntegerType *Int32Ty = Type::getInt32Ty(M.getContext());
707 IntegerType *Int64Ty = Type::getInt64Ty(M.getContext());
708 IntegerType *IntPtrTy = M.getDataLayout().getIntPtrType(M.getContext(), 0);
709
710 // Indirect function call index assignment counter for WebAssembly
711 uint64_t IndirectIndex = 1;
712
713 // Mapping from type identifiers to the call sites that test them, as well as
714 // whether the type identifier needs to be exported to ThinLTO backends as
715 // part of the regular LTO phase of the ThinLTO pipeline (see exportTypeId).
716 struct TypeIdUserInfo {
717 std::vector<CallInst *> CallSites;
718 bool IsExported = false;
719 };
720 DenseMap<Metadata *, TypeIdUserInfo> TypeIdUsers;
721
722 /// This structure describes how to lower type tests for a particular type
723 /// identifier. It is either built directly from the global analysis (during
724 /// regular LTO or the regular LTO phase of ThinLTO), or indirectly using type
725 /// identifier summaries and external symbol references (in ThinLTO backends).
726 struct TypeIdLowering {
728
729 /// All except Unsat: the address of the last element within the combined
730 /// global.
731 Constant *OffsetedGlobal;
732
733 /// ByteArray, Inline, AllOnes: log2 of the required global alignment
734 /// relative to the start address.
735 Constant *AlignLog2;
736
737 /// ByteArray, Inline, AllOnes: one less than the size of the memory region
738 /// covering members of this type identifier as a multiple of 2^AlignLog2.
739 Constant *SizeM1;
740
741 /// ByteArray: the byte array to test the address against.
742 Constant *TheByteArray;
743
744 /// ByteArray: the bit mask to apply to bytes loaded from the byte array.
745 Constant *BitMask;
746
747 /// Inline: the bit mask to test the address against.
748 Constant *InlineBits;
749 };
750
751 std::vector<ByteArrayInfo> ByteArrayInfos;
752
753 Function *WeakInitializerFn = nullptr;
754
755 GlobalVariable *GlobalAnnotation;
756 DenseSet<Value *> FunctionAnnotations;
757
758 // Cross-DSO CFI emits jumptable entries for exported functions as well as
759 // address taken functions in case they are address taken in other modules.
760 bool CrossDsoCfi = M.getModuleFlag("Cross-DSO CFI") != nullptr;
761
762 std::optional<DIBuilder> JumpTableDIB;
763 DICompileUnit *JumpTableCU = nullptr;
764 DIFile *JumpTableFile = nullptr;
765 DISubroutineType *JumpTableFnTy = nullptr;
766
767 bool shouldExportConstantsAsAbsoluteSymbols();
768 uint8_t *exportTypeId(StringRef TypeId, const TypeIdLowering &TIL);
769 TypeIdLowering importTypeId(StringRef TypeId);
770 void importTypeTest(CallInst *CI);
771 void importFunction(Function *F, bool isJumpTableCanonical);
772
773 ByteArrayInfo *createByteArray(const BitSetInfo &BSI);
774 void allocateByteArrays();
775 Value *createBitSetTest(IRBuilder<> &B, const TypeIdLowering &TIL,
776 Value *BitOffset);
777 void lowerTypeTestCalls(
778 ArrayRef<Metadata *> TypeIds, Constant *CombinedGlobalAddr,
779 const DenseMap<GlobalTypeMember *, uint64_t> &GlobalLayout);
780 Value *lowerTypeTestCall(Metadata *TypeId, CallInst *CI,
781 const TypeIdLowering &TIL);
782
783 void buildBitSetsFromGlobalVariables(ArrayRef<Metadata *> TypeIds,
786 selectJumpTableArmEncoding(ArrayRef<GlobalTypeMember *> Functions);
787 bool hasBranchTargetEnforcement();
788 unsigned getJumpTableEntrySize(Triple::ArchType JumpTableArch);
789 InlineAsm *createJumpTableEntryAsm(Triple::ArchType JumpTableArch);
790 void verifyTypeMDNode(GlobalObject *GO, MDNode *Type);
791 void buildBitSetsFromFunctions(ArrayRef<Metadata *> TypeIds,
793 void buildBitSetsFromFunctionsNative(ArrayRef<Metadata *> TypeIds,
795 void buildBitSetsFromFunctionsWASM(ArrayRef<Metadata *> TypeIds,
797 void
798 buildBitSetsFromDisjointSet(ArrayRef<Metadata *> TypeIds,
800 ArrayRef<ICallBranchFunnel *> ICallBranchFunnels);
801
802 void replaceWeakDeclarationWithJumpTablePtr(Function *F, Constant *JT,
803 bool IsJumpTableCanonical);
804 void moveInitializerToModuleConstructor(GlobalVariable *GV);
805 void findGlobalVariableUsersOf(Constant *C,
806 SmallSetVector<GlobalVariable *, 8> &Out);
807
809 createJumpTableDebugInfo(Function *F, ArrayRef<GlobalTypeMember *> Functions);
810 void createJumpTable(Function *F, ArrayRef<GlobalTypeMember *> Functions,
811 Triple::ArchType JumpTableArch);
812
813 /// replaceCfiUses - Go through the uses list for this definition and make
814 /// each use point to "New" instead of "Old" when the use is outside the
815 /// block. 'Old's use list is expected to have at least one element. Unlike
816 /// replaceAllUsesWith this function skips blockaddr and direct call uses.
817 void replaceCfiUses(Function *Old, Value *New, bool IsJumpTableCanonical);
818
819 /// replaceDirectCalls - Go through the uses list for this definition and
820 /// replace each use, which is a direct function call.
821 void replaceDirectCalls(Value *Old, Value *New);
822
823 bool isFunctionAnnotation(Value *V) const {
824 return FunctionAnnotations.contains(V);
825 }
826
827 void maybeReplaceComdat(Function *F, StringRef OriginalName);
828
829public:
830 LowerTypeTestsModule(Module &M, ModuleAnalysisManager &AM,
831 ModuleSummaryIndex *ExportSummary,
832 const ModuleSummaryIndex *ImportSummary);
833 ~LowerTypeTestsModule() {
834 if (JumpTableDIB)
835 JumpTableDIB->finalize();
836 }
837
838 bool lower();
839
840 // Lower the module using the action and summary passed as command line
841 // arguments. For testing purposes only.
842 static bool runForTesting(Module &M, ModuleAnalysisManager &AM);
843};
844} // end anonymous namespace
845
846/// Build a bit set for list of offsets.
848 // Compute the byte offset of each address associated with this type
849 // identifier.
850 return BitSetBuilder(Offsets).build();
851}
852
853/// Build a test that bit BitOffset mod sizeof(Bits)*8 is set in
854/// Bits. This pattern matches to the bt instruction on x86.
856 Value *BitOffset) {
857 auto BitsType = cast<IntegerType>(Bits->getType());
858 unsigned BitWidth = BitsType->getBitWidth();
859
860 BitOffset = B.CreateZExtOrTrunc(BitOffset, BitsType);
861 Value *BitIndex =
862 B.CreateAnd(BitOffset, ConstantInt::get(BitsType, BitWidth - 1));
863 Value *BitMask = B.CreateShl(ConstantInt::get(BitsType, 1), BitIndex);
864 Value *MaskedBits = B.CreateAnd(Bits, BitMask);
865 return B.CreateICmpNE(MaskedBits, ConstantInt::get(BitsType, 0));
866}
867
868ByteArrayInfo *LowerTypeTestsModule::createByteArray(const BitSetInfo &BSI) {
869 // Create globals to stand in for byte arrays and masks. These never actually
870 // get initialized, we RAUW and erase them later in allocateByteArrays() once
871 // we know the offset and mask to use.
872 auto ByteArrayGlobal = new GlobalVariable(
873 M, Int8Ty, /*isConstant=*/true, GlobalValue::PrivateLinkage, nullptr);
874 auto MaskGlobal = new GlobalVariable(M, Int8Ty, /*isConstant=*/true,
876
877 ByteArrayInfos.emplace_back();
878 ByteArrayInfo *BAI = &ByteArrayInfos.back();
879
880 BAI->Bits = BSI.Bits;
881 BAI->BitSize = BSI.BitSize;
882 BAI->ByteArray = ByteArrayGlobal;
883 BAI->MaskGlobal = MaskGlobal;
884 return BAI;
885}
886
887void LowerTypeTestsModule::allocateByteArrays() {
888 llvm::stable_sort(ByteArrayInfos,
889 [](const ByteArrayInfo &BAI1, const ByteArrayInfo &BAI2) {
890 return BAI1.BitSize > BAI2.BitSize;
891 });
892
893 std::vector<uint64_t> ByteArrayOffsets(ByteArrayInfos.size());
894
896 for (unsigned I = 0; I != ByteArrayInfos.size(); ++I) {
897 ByteArrayInfo *BAI = &ByteArrayInfos[I];
898
899 uint8_t Mask;
900 BAB.allocate(BAI->Bits, BAI->BitSize, ByteArrayOffsets[I], Mask);
901
902 BAI->MaskGlobal->replaceAllUsesWith(
903 ConstantExpr::getIntToPtr(ConstantInt::get(Int8Ty, Mask), PtrTy));
904 BAI->MaskGlobal->eraseFromParent();
905 if (BAI->MaskPtr)
906 *BAI->MaskPtr = Mask;
907 }
908
909 Constant *ByteArrayConst = ConstantDataArray::get(M.getContext(), BAB.Bytes);
910 auto ByteArray =
911 new GlobalVariable(M, ByteArrayConst->getType(), /*isConstant=*/true,
912 GlobalValue::PrivateLinkage, ByteArrayConst);
913
914 for (unsigned I = 0; I != ByteArrayInfos.size(); ++I) {
915 ByteArrayInfo *BAI = &ByteArrayInfos[I];
917 ByteArray, ConstantInt::get(IntPtrTy, ByteArrayOffsets[I]));
918
919 // Create an alias instead of RAUW'ing the gep directly. On x86 this ensures
920 // that the pc-relative displacement is folded into the lea instead of the
921 // test instruction getting another displacement.
922 GlobalAlias *Alias = GlobalAlias::create(
923 Int8Ty, 0, GlobalValue::PrivateLinkage, "bits", GEP, &M);
924 BAI->ByteArray->replaceAllUsesWith(Alias);
925 BAI->ByteArray->eraseFromParent();
926 }
927
928 ByteArraySizeBits = BAB.BitAllocs[0] + BAB.BitAllocs[1] + BAB.BitAllocs[2] +
929 BAB.BitAllocs[3] + BAB.BitAllocs[4] + BAB.BitAllocs[5] +
930 BAB.BitAllocs[6] + BAB.BitAllocs[7];
931 ByteArraySizeBytes = BAB.Bytes.size();
932}
933
934/// Build a test that bit BitOffset is set in the type identifier that was
935/// lowered to TIL, which must be either an Inline or a ByteArray.
936Value *LowerTypeTestsModule::createBitSetTest(IRBuilder<> &B,
937 const TypeIdLowering &TIL,
938 Value *BitOffset) {
939 if (TIL.TheKind == TypeTestResolution::Inline) {
940 // If the bit set is sufficiently small, we can avoid a load by bit testing
941 // a constant.
942 return createMaskedBitTest(B, TIL.InlineBits, BitOffset);
943 } else {
944 Constant *ByteArray = TIL.TheByteArray;
945 if (Opts.lowertypetests_avoid_reuse && !ImportSummary) {
946 // Each use of the byte array uses a different alias. This makes the
947 // backend less likely to reuse previously computed byte array addresses,
948 // improving the security of the CFI mechanism based on this pass.
949 // This won't work when importing because TheByteArray is external.
951 "bits_use", ByteArray, &M);
952 }
953
954 Value *ByteAddr = B.CreateGEP(Int8Ty, ByteArray, BitOffset);
955 Value *Byte = B.CreateLoad(Int8Ty, ByteAddr);
956
957 Value *ByteAndMask =
958 B.CreateAnd(Byte, ConstantExpr::getPtrToInt(TIL.BitMask, Int8Ty));
959 return B.CreateICmpNE(ByteAndMask, ConstantInt::get(Int8Ty, 0));
960 }
961}
962
963static bool isKnownTypeIdMember(Metadata *TypeId, const DataLayout &DL,
964 Value *V, uint64_t COffset) {
965 if (auto GV = dyn_cast<GlobalObject>(V)) {
967 GV->getMetadata(LLVMContext::MD_type, Types);
968 for (MDNode *Type : Types) {
969 if (Type->getOperand(1) != TypeId)
970 continue;
973 cast<ConstantAsMetadata>(Type->getOperand(0))->getValue())
974 ->getZExtValue();
975 if (COffset == Offset)
976 return true;
977 }
978 return false;
979 }
980
981 if (auto GEP = dyn_cast<GEPOperator>(V)) {
982 APInt APOffset(DL.getIndexSizeInBits(0), 0);
983 bool Result = GEP->accumulateConstantOffset(DL, APOffset);
984 if (!Result)
985 return false;
986 COffset += APOffset.getZExtValue();
987 return isKnownTypeIdMember(TypeId, DL, GEP->getPointerOperand(), COffset);
988 }
989
990 if (auto Op = dyn_cast<Operator>(V)) {
991 if (Op->getOpcode() == Instruction::BitCast)
992 return isKnownTypeIdMember(TypeId, DL, Op->getOperand(0), COffset);
993
994 if (Op->getOpcode() == Instruction::Select)
995 return isKnownTypeIdMember(TypeId, DL, Op->getOperand(1), COffset) &&
996 isKnownTypeIdMember(TypeId, DL, Op->getOperand(2), COffset);
997 }
998
999 return false;
1000}
1001
1002/// Lower a llvm.type.test call to its implementation. Returns the value to
1003/// replace the call with.
1004Value *LowerTypeTestsModule::lowerTypeTestCall(Metadata *TypeId, CallInst *CI,
1005 const TypeIdLowering &TIL) {
1006 // Delay lowering if the resolution is currently unknown.
1007 if (TIL.TheKind == TypeTestResolution::Unknown)
1008 return nullptr;
1009 if (TIL.TheKind == TypeTestResolution::Unsat)
1010 return ConstantInt::getFalse(M.getContext());
1011
1012 Value *Ptr = CI->getArgOperand(0);
1013 const DataLayout &DL = M.getDataLayout();
1014 if (isKnownTypeIdMember(TypeId, DL, Ptr, 0))
1015 return ConstantInt::getTrue(M.getContext());
1016
1017 BasicBlock *InitialBB = CI->getParent();
1018
1019 IRBuilder<> B(CI);
1020
1021 Value *PtrAsInt = B.CreatePtrToInt(Ptr, IntPtrTy);
1022
1023 Constant *OffsetedGlobalAsInt =
1024 ConstantExpr::getPtrToInt(TIL.OffsetedGlobal, IntPtrTy);
1025 if (TIL.TheKind == TypeTestResolution::Single)
1026 return B.CreateICmpEQ(PtrAsInt, OffsetedGlobalAsInt);
1027
1028 // Here we compute `last element - address`. The reason why we do this instead
1029 // of computing `address - first element` is that it leads to a slightly
1030 // shorter instruction sequence on x86. Because it doesn't matter how we do
1031 // the subtraction on other architectures, we do so unconditionally.
1032 Value *PtrOffset = B.CreateSub(OffsetedGlobalAsInt, PtrAsInt);
1033
1034 // We need to check that the offset both falls within our range and is
1035 // suitably aligned. We can check both properties at the same time by
1036 // performing a right rotate by log2(alignment) followed by an integer
1037 // comparison against the bitset size. The rotate will move the lower
1038 // order bits that need to be zero into the higher order bits of the
1039 // result, causing the comparison to fail if they are nonzero. The rotate
1040 // also conveniently gives us a bit offset to use during the load from
1041 // the bitset.
1042 Value *BitOffset = B.CreateIntrinsic(IntPtrTy, Intrinsic::fshr,
1043 {PtrOffset, PtrOffset, TIL.AlignLog2});
1044
1045 Value *OffsetInRange = B.CreateICmpULE(BitOffset, TIL.SizeM1);
1046
1047 // If the bit set is all ones, testing against it is unnecessary.
1048 if (TIL.TheKind == TypeTestResolution::AllOnes)
1049 return OffsetInRange;
1050
1051 // See if the intrinsic is used in the following common pattern:
1052 // br(llvm.type.test(...), thenbb, elsebb)
1053 // where nothing happens between the type test and the br.
1054 // If so, create slightly simpler IR.
1055 if (CI->hasOneUse())
1056 if (auto *Br = dyn_cast<CondBrInst>(*CI->user_begin()))
1057 if (CI->getNextNode() == Br) {
1058 BasicBlock *Then = InitialBB->splitBasicBlock(CI->getIterator());
1059 BasicBlock *Else = Br->getSuccessor(1);
1060 CondBrInst *NewBr = CondBrInst::Create(OffsetInRange, Then, Else);
1061 NewBr->setMetadata(LLVMContext::MD_prof,
1062 Br->getMetadata(LLVMContext::MD_prof));
1063 ReplaceInstWithInst(InitialBB->getTerminator(), NewBr);
1064
1065 // Update phis in Else resulting from InitialBB being split
1066 for (auto &Phi : Else->phis())
1067 Phi.addIncoming(Phi.getIncomingValueForBlock(Then), InitialBB);
1068
1069 IRBuilder<> ThenB(CI);
1070 return createBitSetTest(ThenB, TIL, BitOffset);
1071 }
1072
1073 MDBuilder MDB(M.getContext());
1075 OffsetInRange, CI, false,
1077 : MDB.createLikelyBranchWeights()));
1078
1079 // Now that we know that the offset is in range and aligned, load the
1080 // appropriate bit from the bitset.
1081 Value *Bit = createBitSetTest(ThenB, TIL, BitOffset);
1082
1083 // The value we want is 0 if we came directly from the initial block
1084 // (having failed the range or alignment checks), or the loaded bit if
1085 // we came from the block in which we loaded it.
1086 B.SetInsertPoint(CI);
1087 PHINode *P = B.CreatePHI(Int1Ty, 2);
1088 P->addIncoming(ConstantInt::get(Int1Ty, 0), InitialBB);
1089 P->addIncoming(Bit, ThenB.GetInsertBlock());
1090 return P;
1091}
1092
1093/// Given a disjoint set of type identifiers and globals, lay out the globals,
1094/// build the bit sets and lower the llvm.type.test calls.
1095void LowerTypeTestsModule::buildBitSetsFromGlobalVariables(
1097 // Build a new global with the combined contents of the referenced globals.
1098 // This global is a struct whose even-indexed elements contain the original
1099 // contents of the referenced globals and whose odd-indexed elements contain
1100 // any padding required to align the next element to the next power of 2 plus
1101 // any additional padding required to meet its alignment requirements.
1102 std::vector<Constant *> GlobalInits;
1103 const DataLayout &DL = M.getDataLayout();
1104 DenseMap<GlobalTypeMember *, uint64_t> GlobalLayout;
1105 Align MaxAlign;
1106 uint64_t CurOffset = 0;
1107 uint64_t DesiredPadding = 0;
1108 for (GlobalTypeMember *G : Globals) {
1109 auto *GV = cast<GlobalVariable>(G->getGlobal());
1111 DL.getValueOrABITypeAlignment(GV->getAlign(), GV->getValueType());
1112 MaxAlign = std::max(MaxAlign, Alignment);
1113 uint64_t GVOffset = alignTo(CurOffset + DesiredPadding, Alignment);
1114 GlobalLayout[G] = GVOffset;
1115 if (GVOffset != 0) {
1116 uint64_t Padding = GVOffset - CurOffset;
1117 GlobalInits.push_back(
1118 ConstantAggregateZero::get(ArrayType::get(Int8Ty, Padding)));
1119 }
1120
1121 GlobalInits.push_back(GV->getInitializer());
1122 uint64_t InitSize = GV->getGlobalSize(DL);
1123 CurOffset = GVOffset + InitSize;
1124
1125 // Compute the amount of padding that we'd like for the next element.
1126 DesiredPadding = NextPowerOf2(InitSize - 1) - InitSize;
1127
1128 // Experiments of different caps with Chromium on both x64 and ARM64
1129 // have shown that the 32-byte cap generates the smallest binary on
1130 // both platforms while different caps yield similar performance.
1131 // (see https://lists.llvm.org/pipermail/llvm-dev/2018-July/124694.html)
1132 if (DesiredPadding > 32)
1133 DesiredPadding = alignTo(InitSize, 32) - InitSize;
1134 }
1135
1136 Constant *NewInit = ConstantStruct::getAnon(M.getContext(), GlobalInits);
1137 auto *CombinedGlobal =
1138 new GlobalVariable(M, NewInit->getType(), /*isConstant=*/true,
1140 CombinedGlobal->setAlignment(MaxAlign);
1141
1142 StructType *NewTy = cast<StructType>(NewInit->getType());
1143 lowerTypeTestCalls(TypeIds, CombinedGlobal, GlobalLayout);
1144
1145 // Build aliases pointing to offsets into the combined global for each
1146 // global from which we built the combined global, and replace references
1147 // to the original globals with references to the aliases.
1148 for (unsigned I = 0; I != Globals.size(); ++I) {
1149 GlobalVariable *GV = cast<GlobalVariable>(Globals[I]->getGlobal());
1150
1151 // Multiply by 2 to account for padding elements.
1152 Constant *CombinedGlobalIdxs[] = {ConstantInt::get(Int32Ty, 0),
1153 ConstantInt::get(Int32Ty, I * 2)};
1154 Constant *CombinedGlobalElemPtr = ConstantExpr::getGetElementPtr(
1155 DL, NewInit->getType(), CombinedGlobal, CombinedGlobalIdxs,
1157 assert(GV->getType()->getAddressSpace() == 0);
1158 GlobalAlias *GAlias =
1159 GlobalAlias::create(NewTy->getElementType(I * 2), 0, GV->getLinkage(),
1160 "", CombinedGlobalElemPtr, &M);
1161 GAlias->setVisibility(GV->getVisibility());
1162 GAlias->takeName(GV);
1163 GV->replaceAllUsesWith(GAlias);
1164 GV->eraseFromParent();
1165 }
1166}
1167
1168bool LowerTypeTestsModule::shouldExportConstantsAsAbsoluteSymbols() {
1169 return (Arch == Triple::x86 || Arch == Triple::x86_64) &&
1170 ObjectFormat == Triple::ELF;
1171}
1172
1173/// Export the given type identifier so that ThinLTO backends may import it.
1174/// Type identifiers are exported by adding coarse-grained information about how
1175/// to test the type identifier to the summary, and creating symbols in the
1176/// object file (aliases and absolute symbols) containing fine-grained
1177/// information about the type identifier.
1178///
1179/// Returns a pointer to the location in which to store the bitmask, if
1180/// applicable.
1181uint8_t *LowerTypeTestsModule::exportTypeId(StringRef TypeId,
1182 const TypeIdLowering &TIL) {
1183 TypeTestResolution &TTRes =
1184 ExportSummary->getOrInsertTypeIdSummary(TypeId).TTRes;
1185 TTRes.TheKind = TIL.TheKind;
1186
1187 auto ExportGlobal = [&](StringRef Name, Constant *C) {
1188 GlobalAlias *GA =
1190 "__typeid_" + TypeId + "_" + Name, C, &M);
1192 };
1193
1194 auto ExportConstant = [&](StringRef Name, uint64_t &Storage, Constant *C) {
1195 if (shouldExportConstantsAsAbsoluteSymbols())
1196 ExportGlobal(Name, ConstantExpr::getIntToPtr(C, PtrTy));
1197 else
1198 Storage = cast<ConstantInt>(C)->getZExtValue();
1199 };
1200
1201 if (TIL.TheKind != TypeTestResolution::Unsat)
1202 ExportGlobal("global_addr", TIL.OffsetedGlobal);
1203
1204 if (TIL.TheKind == TypeTestResolution::ByteArray ||
1205 TIL.TheKind == TypeTestResolution::Inline ||
1206 TIL.TheKind == TypeTestResolution::AllOnes) {
1207 ExportConstant("align", TTRes.AlignLog2, TIL.AlignLog2);
1208 ExportConstant("size_m1", TTRes.SizeM1, TIL.SizeM1);
1209
1210 uint64_t BitSize = cast<ConstantInt>(TIL.SizeM1)->getZExtValue() + 1;
1211 if (TIL.TheKind == TypeTestResolution::Inline)
1212 TTRes.SizeM1BitWidth = (BitSize <= 32) ? 5 : 6;
1213 else
1214 TTRes.SizeM1BitWidth = (BitSize <= 128) ? 7 : 32;
1215 }
1216
1217 if (TIL.TheKind == TypeTestResolution::ByteArray) {
1218 ExportGlobal("byte_array", TIL.TheByteArray);
1219 if (shouldExportConstantsAsAbsoluteSymbols())
1220 ExportGlobal("bit_mask", TIL.BitMask);
1221 else
1222 return &TTRes.BitMask;
1223 }
1224
1225 if (TIL.TheKind == TypeTestResolution::Inline)
1226 ExportConstant("inline_bits", TTRes.InlineBits, TIL.InlineBits);
1227
1228 return nullptr;
1229}
1230
1231LowerTypeTestsModule::TypeIdLowering
1232LowerTypeTestsModule::importTypeId(StringRef TypeId) {
1233 const TypeIdSummary *TidSummary = ImportSummary->getTypeIdSummary(TypeId);
1234 if (!TidSummary)
1235 return {}; // Unsat: no globals match this type id.
1236 const TypeTestResolution &TTRes = TidSummary->TTRes;
1237
1238 TypeIdLowering TIL;
1239 TIL.TheKind = TTRes.TheKind;
1240
1241 auto ImportGlobal = [&](StringRef Name) {
1242 // Give the global a type of length 0 so that it is not assumed not to alias
1243 // with any other global.
1244 GlobalVariable *GV = M.getOrInsertGlobal(
1245 ("__typeid_" + TypeId + "_" + Name).str(), Int8Arr0Ty);
1247 return GV;
1248 };
1249
1250 auto ImportConstant = [&](StringRef Name, uint64_t Const, unsigned AbsWidth,
1251 Type *Ty) {
1252 if (!shouldExportConstantsAsAbsoluteSymbols()) {
1253 Constant *C =
1254 ConstantInt::get(isa<IntegerType>(Ty) ? Ty : Int64Ty, Const);
1255 if (!isa<IntegerType>(Ty))
1257 return C;
1258 }
1259
1260 Constant *C = ImportGlobal(Name);
1261 auto *GV = cast<GlobalVariable>(C->stripPointerCasts());
1262 if (isa<IntegerType>(Ty))
1264 if (GV->getMetadata(LLVMContext::MD_absolute_symbol))
1265 return C;
1266
1267 auto SetAbsRange = [&](uint64_t Min, uint64_t Max) {
1268 auto *MinC = ConstantAsMetadata::get(ConstantInt::get(IntPtrTy, Min));
1269 auto *MaxC = ConstantAsMetadata::get(ConstantInt::get(IntPtrTy, Max));
1270 GV->setMetadata(LLVMContext::MD_absolute_symbol,
1271 MDNode::get(M.getContext(), {MinC, MaxC}));
1272 };
1273 if (AbsWidth == IntPtrTy->getBitWidth()) {
1274 uint64_t AllOnes = IntPtrTy->getBitMask();
1275 SetAbsRange(AllOnes, AllOnes); // Full set.
1276 } else {
1277 SetAbsRange(0, 1ull << AbsWidth);
1278 }
1279 return C;
1280 };
1281
1282 if (TIL.TheKind != TypeTestResolution::Unsat) {
1283 auto *GV = ImportGlobal("global_addr");
1284 // This is either a vtable (in .data.rel.ro) or a jump table (in .text).
1285 // Either way it's expected to be in the low 2 GiB, so set the small code
1286 // model.
1287 //
1288 // For .data.rel.ro, we currently place all such sections in the low 2 GiB
1289 // [1], and for .text the sections are expected to be in the low 2 GiB under
1290 // the small and medium code models [2] and this pass only supports those
1291 // code models (e.g. jump tables use jmp instead of movabs/jmp).
1292 //
1293 // [1]https://github.com/llvm/llvm-project/pull/137742
1294 // [2]https://maskray.me/blog/2023-05-14-relocation-overflow-and-code-models
1296 TIL.OffsetedGlobal = GV;
1297 }
1298
1299 if (TIL.TheKind == TypeTestResolution::ByteArray ||
1300 TIL.TheKind == TypeTestResolution::Inline ||
1301 TIL.TheKind == TypeTestResolution::AllOnes) {
1302 TIL.AlignLog2 = ImportConstant("align", TTRes.AlignLog2, 8, IntPtrTy);
1303 TIL.SizeM1 =
1304 ImportConstant("size_m1", TTRes.SizeM1, TTRes.SizeM1BitWidth, IntPtrTy);
1305 }
1306
1307 if (TIL.TheKind == TypeTestResolution::ByteArray) {
1308 TIL.TheByteArray = ImportGlobal("byte_array");
1309 TIL.BitMask = ImportConstant("bit_mask", TTRes.BitMask, 8, PtrTy);
1310 }
1311
1312 if (TIL.TheKind == TypeTestResolution::Inline)
1313 TIL.InlineBits = ImportConstant(
1314 "inline_bits", TTRes.InlineBits, 1 << TTRes.SizeM1BitWidth,
1315 TTRes.SizeM1BitWidth <= 5 ? Int32Ty : Int64Ty);
1316
1317 return TIL;
1318}
1319
1320void LowerTypeTestsModule::importTypeTest(CallInst *CI) {
1321 auto TypeIdMDVal = dyn_cast<MetadataAsValue>(CI->getArgOperand(1));
1322 if (!TypeIdMDVal)
1323 report_fatal_error("Second argument of llvm.type.test must be metadata");
1324
1325 auto TypeIdStr = dyn_cast<MDString>(TypeIdMDVal->getMetadata());
1326 // If this is a local unpromoted type, which doesn't have a metadata string,
1327 // treat as Unknown and delay lowering, so that we can still utilize it for
1328 // later optimizations.
1329 if (!TypeIdStr)
1330 return;
1331
1332 TypeIdLowering TIL = importTypeId(TypeIdStr->getString());
1333 Value *Lowered = lowerTypeTestCall(TypeIdStr, CI, TIL);
1334 if (Lowered) {
1335 CI->replaceAllUsesWith(Lowered);
1336 CI->eraseFromParent();
1337 }
1338}
1339
1340void LowerTypeTestsModule::maybeReplaceComdat(Function *F,
1341 StringRef OriginalName) {
1342 // For COFF we should also rename the comdat if this function also
1343 // happens to be the key function. Even if the comdat name changes, this
1344 // should still be fine since comdat and symbol resolution happens
1345 // before LTO, so all symbols which would prevail have been selected.
1346 if (F->hasComdat() && ObjectFormat == Triple::COFF &&
1347 F->getComdat()->getName() == OriginalName) {
1348 Comdat *OldComdat = F->getComdat();
1349 Comdat *NewComdat = M.getOrInsertComdat(F->getName());
1350 for (GlobalObject &GO : M.global_objects()) {
1351 if (GO.getComdat() == OldComdat)
1352 GO.setComdat(NewComdat);
1353 }
1354 }
1355}
1356
1357// ThinLTO backend: the function F has a jump table entry; update this module
1358// accordingly. isJumpTableCanonical describes the type of the jump table entry.
1359void LowerTypeTestsModule::importFunction(Function *F,
1360 bool isJumpTableCanonical) {
1361 assert(F->getType()->getAddressSpace() == 0);
1362
1363 GlobalValue::VisibilityTypes Visibility = F->getVisibility();
1364 std::string Name = std::string(F->getName());
1365
1366 if (F->isDeclarationForLinker() && isJumpTableCanonical) {
1367 // Non-dso_local functions may be overriden at run time,
1368 // don't short curcuit them
1369 if (!F->isDSOLocal())
1370 return;
1371 if (F->isDeclaration()) {
1372 // Direct calls do not need the type check, so let them skip the jump
1373 // table and call the real function directly.
1374 Function *RealF = Function::Create(F->getFunctionType(),
1376 F->getAddressSpace(),
1377 Name + ".cfi", &M);
1379 replaceDirectCalls(F, RealF);
1380 return;
1381 }
1382 // Otherwise F is an available_externally definition imported from
1383 // another module. Handle it like a local definition below: the body is
1384 // renamed to Name.cfi and stays the target of direct calls, so it remains
1385 // inlinable, while address-taken uses are redirected to the jump table
1386 // entry. If the body is not inlined and is dropped later, the reference
1387 // to Name.cfi resolves to the real function at link time, exactly as for
1388 // a declaration.
1389 }
1390
1391 Function *FDecl;
1392 if (!isJumpTableCanonical) {
1393 // Either a declaration of an external function or a reference to a locally
1394 // defined jump table.
1395 FDecl = Function::Create(F->getFunctionType(), GlobalValue::ExternalLinkage,
1396 F->getAddressSpace(), Name + ".cfi_jt", &M);
1398 } else {
1399 F->setName(Name + ".cfi");
1400 maybeReplaceComdat(F, Name);
1401 FDecl = Function::Create(F->getFunctionType(), GlobalValue::ExternalLinkage,
1402 F->getAddressSpace(), Name, &M);
1403 FDecl->setVisibility(Visibility);
1404 FDecl->setDSOLocal(F->isDSOLocal());
1405 Visibility = GlobalValue::HiddenVisibility;
1406
1407 // Update aliases pointing to this function to also include the ".cfi" suffix,
1408 // We expect the jump table entry to either point to the real function or an
1409 // alias. Redirect all other users to the jump table entry.
1410 for (auto &U : F->uses()) {
1411 if (auto *A = dyn_cast<GlobalAlias>(U.getUser())) {
1412 // MemProf duplicate-clone aliases are created in the ThinLTO backend
1413 // after the thin link has finalized the CFI jump table and !aliases in
1414 // the merged module, and are only called directly. Leave them aliasing
1415 // the local .cfi body (restored by ScopedSaveAliaseesAndUsed) rather
1416 // than redirecting them to a non-existent jump table entry.
1417 if (isMemProfClone(*A))
1418 continue;
1419 std::string AliasName = A->getName().str() + ".cfi";
1420 Function *AliasDecl = Function::Create(
1421 F->getFunctionType(), GlobalValue::ExternalLinkage,
1422 F->getAddressSpace(), "", &M);
1423 AliasDecl->takeName(A);
1424 A->replaceAllUsesWith(AliasDecl);
1425 A->setName(AliasName);
1426 AliasDecl->setDSOLocal(A->isDSOLocal());
1427 }
1428 }
1429 }
1430
1431 if (F->hasExternalWeakLinkage())
1432 replaceWeakDeclarationWithJumpTablePtr(F, FDecl, isJumpTableCanonical);
1433 else
1434 replaceCfiUses(F, FDecl, isJumpTableCanonical);
1435
1436 // Set visibility late because it's used in replaceCfiUses() to determine
1437 // whether uses need to be replaced.
1438 F->setVisibility(Visibility);
1439}
1440
1441static auto
1443 const DenseMap<GlobalTypeMember *, uint64_t> &GlobalLayout) {
1445 // Pre-populate the map with interesting type identifiers.
1446 for (Metadata *TypeId : TypeIds)
1447 OffsetsByTypeID[TypeId];
1448 for (const auto &[Mem, MemOff] : GlobalLayout) {
1449 for (MDNode *Type : Mem->types()) {
1450 auto It = OffsetsByTypeID.find(Type->getOperand(1));
1451 if (It == OffsetsByTypeID.end())
1452 continue;
1455 cast<ConstantAsMetadata>(Type->getOperand(0))->getValue())
1456 ->getZExtValue();
1457 It->second.push_back(MemOff + Offset);
1458 }
1459 }
1460
1462 BitSets.reserve(TypeIds.size());
1463 for (Metadata *TypeId : TypeIds) {
1464 BitSets.emplace_back(TypeId, buildBitSet(OffsetsByTypeID[TypeId]));
1465 LLVM_DEBUG({
1466 if (auto MDS = dyn_cast<MDString>(TypeId))
1467 dbgs() << MDS->getString() << ": ";
1468 else
1469 dbgs() << "<unnamed>: ";
1470 BitSets.back().second.print(dbgs());
1471 });
1472 }
1473
1474 return BitSets;
1475}
1476
1477void LowerTypeTestsModule::lowerTypeTestCalls(
1478 ArrayRef<Metadata *> TypeIds, Constant *CombinedGlobalAddr,
1479 const DenseMap<GlobalTypeMember *, uint64_t> &GlobalLayout) {
1480 // For each type identifier in this disjoint set...
1481 for (const auto &[TypeId, BSI] : buildBitSets(TypeIds, GlobalLayout)) {
1482 ByteArrayInfo *BAI = nullptr;
1483 TypeIdLowering TIL;
1484
1485 uint64_t GlobalOffset =
1486 BSI.ByteOffset + ((BSI.BitSize - 1) << BSI.AlignLog2);
1487 TIL.OffsetedGlobal = ConstantExpr::getPtrAdd(
1488 CombinedGlobalAddr, ConstantInt::get(IntPtrTy, GlobalOffset)),
1489 TIL.AlignLog2 = ConstantInt::get(IntPtrTy, BSI.AlignLog2);
1490 TIL.SizeM1 = ConstantInt::get(IntPtrTy, BSI.BitSize - 1);
1491 if (BSI.isAllOnes()) {
1492 TIL.TheKind = (BSI.BitSize == 1) ? TypeTestResolution::Single
1493 : TypeTestResolution::AllOnes;
1494 } else if (BSI.BitSize <= IntPtrTy->getBitWidth()) {
1495 TIL.TheKind = TypeTestResolution::Inline;
1496 uint64_t InlineBits = 0;
1497 for (auto Bit : BSI.Bits)
1498 InlineBits |= uint64_t(1) << Bit;
1499 if (InlineBits == 0)
1500 TIL.TheKind = TypeTestResolution::Unsat;
1501 else
1502 TIL.InlineBits = ConstantInt::get(
1503 (BSI.BitSize <= 32) ? Int32Ty : Int64Ty, InlineBits);
1504 } else {
1505 TIL.TheKind = TypeTestResolution::ByteArray;
1506 ++NumByteArraysCreated;
1507 BAI = createByteArray(BSI);
1508 TIL.TheByteArray = BAI->ByteArray;
1509 TIL.BitMask = BAI->MaskGlobal;
1510 }
1511
1512 TypeIdUserInfo &TIUI = TypeIdUsers[TypeId];
1513
1514 if (TIUI.IsExported) {
1515 uint8_t *MaskPtr = exportTypeId(cast<MDString>(TypeId)->getString(), TIL);
1516 if (BAI)
1517 BAI->MaskPtr = MaskPtr;
1518 }
1519
1520 // Lower each call to llvm.type.test for this type identifier.
1521 for (CallInst *CI : TIUI.CallSites) {
1522 ++NumTypeTestCallsLowered;
1523 Value *Lowered = lowerTypeTestCall(TypeId, CI, TIL);
1524 if (Lowered) {
1525 CI->replaceAllUsesWith(Lowered);
1526 CI->eraseFromParent();
1527 }
1528 }
1529 }
1530}
1531
1532void LowerTypeTestsModule::verifyTypeMDNode(GlobalObject *GO, MDNode *Type) {
1533 if (Type->getNumOperands() != 2)
1534 report_fatal_error("All operands of type metadata must have 2 elements");
1535
1536 if (GO->isThreadLocal())
1537 report_fatal_error("Bit set element may not be thread-local");
1538 if (isa<GlobalVariable>(GO) && GO->hasSection())
1540 "A member of a type identifier may not have an explicit section");
1541
1542 // FIXME: We previously checked that global var member of a type identifier
1543 // must be a definition, but the IR linker may leave type metadata on
1544 // declarations. We should restore this check after fixing PR31759.
1545
1546 auto OffsetConstMD = dyn_cast<ConstantAsMetadata>(Type->getOperand(0));
1547 if (!OffsetConstMD)
1548 report_fatal_error("Type offset must be a constant");
1549 auto OffsetInt = dyn_cast<ConstantInt>(OffsetConstMD->getValue());
1550 if (!OffsetInt)
1551 report_fatal_error("Type offset must be an integer constant");
1552}
1553
1554static const unsigned kX86JumpTableEntrySize = 8;
1555static const unsigned kX86IBTJumpTableEntrySize = 16;
1556static const unsigned kARMJumpTableEntrySize = 4;
1557static const unsigned kARMBTIJumpTableEntrySize = 8;
1558static const unsigned kARMv6MJumpTableEntrySize = 16;
1559static const unsigned kRISCVJumpTableEntrySize = 8;
1560static const unsigned kLOONGARCH64JumpTableEntrySize = 8;
1561static const unsigned kHexagonJumpTableEntrySize = 4;
1562
1563bool LowerTypeTestsModule::hasBranchTargetEnforcement() {
1564 if (HasBranchTargetEnforcement == -1) {
1565 // First time this query has been called. Find out the answer by checking
1566 // the module flags.
1567 if (const auto *BTE = mdconst::extract_or_null<ConstantInt>(
1568 M.getModuleFlag("branch-target-enforcement")))
1569 HasBranchTargetEnforcement = !BTE->isZero();
1570 else
1571 HasBranchTargetEnforcement = 0;
1572 }
1573 return HasBranchTargetEnforcement;
1574}
1575
1576unsigned
1577LowerTypeTestsModule::getJumpTableEntrySize(Triple::ArchType JumpTableArch) {
1578 switch (JumpTableArch) {
1579 case Triple::x86:
1580 case Triple::x86_64:
1581 if (const auto *MD = mdconst::extract_or_null<ConstantInt>(
1582 M.getModuleFlag("cf-protection-branch")))
1583 if (MD->getZExtValue())
1586 case Triple::arm:
1588 case Triple::thumb:
1589 if (CanUseThumbBWJumpTable) {
1590 if (hasBranchTargetEnforcement())
1593 } else {
1595 }
1596 case Triple::aarch64:
1597 if (hasBranchTargetEnforcement())
1600 case Triple::riscv32:
1601 case Triple::riscv64:
1605 case Triple::hexagon:
1607 default:
1608 report_fatal_error("Unsupported architecture for jump tables");
1609 }
1610}
1611
1612// Create an inline asm constant representing a jump table entry for the target.
1613// This consists of an instruction sequence containing a relative branch to
1614// Dest.
1615InlineAsm *
1616LowerTypeTestsModule::createJumpTableEntryAsm(Triple::ArchType JumpTableArch) {
1617 std::string Asm;
1618 raw_string_ostream AsmOS(Asm);
1619
1620 if (JumpTableArch == Triple::x86 || JumpTableArch == Triple::x86_64) {
1621 bool Endbr = false;
1622 if (const auto *MD = mdconst::extract_or_null<ConstantInt>(
1623 M.getModuleFlag("cf-protection-branch")))
1624 Endbr = !MD->isZero();
1625 if (Endbr)
1626 AsmOS << (JumpTableArch == Triple::x86 ? "endbr32\n" : "endbr64\n");
1627 AsmOS << "jmp ${0:c}@plt\n";
1628 if (Endbr)
1629 AsmOS << ".balign 16, 0xcc\n";
1630 else
1631 AsmOS << "int3\nint3\nint3\n";
1632 } else if (JumpTableArch == Triple::arm) {
1633 AsmOS << "b $0\n";
1634 } else if (JumpTableArch == Triple::aarch64) {
1635 if (hasBranchTargetEnforcement())
1636 AsmOS << "bti c\n";
1637 AsmOS << "b $0\n";
1638 } else if (JumpTableArch == Triple::thumb) {
1639 if (!CanUseThumbBWJumpTable) {
1640 // In Armv6-M, this sequence will generate a branch without corrupting
1641 // any registers. We use two stack words; in the second, we construct the
1642 // address we'll pop into pc, and the first is used to save and restore
1643 // r0 which we use as a temporary register.
1644 //
1645 // To support position-independent use cases, the offset of the target
1646 // function is stored as a relative offset (which will expand into an
1647 // R_ARM_REL32 relocation in ELF, and presumably the equivalent in other
1648 // object file types), and added to pc after we load it. (The alternative
1649 // B.W is automatically pc-relative.)
1650 //
1651 // There are five 16-bit Thumb instructions here, so the .balign 4 adds a
1652 // sixth halfword of padding, and then the offset consumes a further 4
1653 // bytes, for a total of 16, which is very convenient since entries in
1654 // this jump table need to have power-of-two size.
1655 AsmOS << "push {r0,r1}\n"
1656 << "ldr r0, 1f\n"
1657 << "0: add r0, r0, pc\n"
1658 << "str r0, [sp, #4]\n"
1659 << "pop {r0,pc}\n"
1660 << ".balign 4\n"
1661 << "1: .word $0 - (0b + 4)\n";
1662 } else {
1663 if (hasBranchTargetEnforcement())
1664 AsmOS << "bti\n";
1665 AsmOS << "b.w $0\n";
1666 }
1667 } else if (JumpTableArch == Triple::riscv32 ||
1668 JumpTableArch == Triple::riscv64) {
1669 AsmOS << "tail $0@plt\n";
1670 } else if (JumpTableArch == Triple::loongarch64) {
1671 AsmOS << "pcalau12i $$t0, %pc_hi20($0)\n"
1672 << "jirl $$r0, $$t0, %pc_lo12($0)\n";
1673 } else if (JumpTableArch == Triple::hexagon) {
1674 AsmOS << "jump $0\n";
1675 } else {
1676 report_fatal_error("Unsupported architecture for jump tables");
1677 }
1678
1679 return InlineAsm::get(
1680 FunctionType::get(Type::getVoidTy(M.getContext()), PtrTy, false),
1681 AsmOS.str(), "s",
1682 /*hasSideEffects=*/true);
1683}
1684
1685/// Given a disjoint set of type identifiers and functions, build the bit sets
1686/// and lower the llvm.type.test calls, architecture dependently.
1687void LowerTypeTestsModule::buildBitSetsFromFunctions(
1689 if (Arch == Triple::x86 || Arch == Triple::x86_64 || Arch == Triple::arm ||
1690 Arch == Triple::thumb || Arch == Triple::aarch64 ||
1691 Arch == Triple::riscv32 || Arch == Triple::riscv64 ||
1692 Arch == Triple::loongarch64 || Arch == Triple::hexagon)
1693 buildBitSetsFromFunctionsNative(TypeIds, Functions);
1694 else if (Arch == Triple::wasm32 || Arch == Triple::wasm64)
1695 buildBitSetsFromFunctionsWASM(TypeIds, Functions);
1696 else
1697 report_fatal_error("Unsupported architecture for jump tables");
1698}
1699
1700void LowerTypeTestsModule::moveInitializerToModuleConstructor(
1701 GlobalVariable *GV) {
1702 if (WeakInitializerFn == nullptr) {
1703 WeakInitializerFn = Function::Create(
1704 FunctionType::get(Type::getVoidTy(M.getContext()),
1705 /* IsVarArg */ false),
1707 M.getDataLayout().getProgramAddressSpace(),
1708 "__cfi_global_var_init", &M);
1709 BasicBlock *BB =
1710 BasicBlock::Create(M.getContext(), "entry", WeakInitializerFn);
1711 ReturnInst::Create(M.getContext(), BB);
1712 WeakInitializerFn->setSection(
1713 ObjectFormat == Triple::MachO
1714 ? "__TEXT,__StaticInit,regular,pure_instructions"
1715 : ".text.startup");
1716 // This code is equivalent to relocation application, and should run at the
1717 // earliest possible time (i.e. with the highest priority).
1718 appendToGlobalCtors(M, WeakInitializerFn, /* Priority */ 0);
1719 }
1720
1721 IRBuilder<> IRB(WeakInitializerFn->getEntryBlock().getTerminator());
1722 GV->setConstant(false);
1723 IRB.CreateAlignedStore(GV->getInitializer(), GV, GV->getAlign());
1725}
1726
1727void LowerTypeTestsModule::findGlobalVariableUsersOf(
1728 Constant *C, SmallSetVector<GlobalVariable *, 8> &Out) {
1729 for (auto *U : C->users()){
1730 if (auto *GV = dyn_cast<GlobalVariable>(U))
1731 Out.insert(GV);
1732 else if (auto *C2 = dyn_cast<Constant>(U))
1733 findGlobalVariableUsersOf(C2, Out);
1734 }
1735}
1736
1737// Replace all uses of F with (F ? JT : 0).
1738void LowerTypeTestsModule::replaceWeakDeclarationWithJumpTablePtr(
1739 Function *F, Constant *JT, bool IsJumpTableCanonical) {
1740 // The target expression can not appear in a constant initializer on most
1741 // (all?) targets. Switch to a runtime initializer.
1742 SmallSetVector<GlobalVariable *, 8> GlobalVarUsers;
1743 findGlobalVariableUsersOf(F, GlobalVarUsers);
1744 for (auto *GV : GlobalVarUsers) {
1745 if (GV == GlobalAnnotation)
1746 continue;
1747 moveInitializerToModuleConstructor(GV);
1748 }
1749
1750 // Can not RAUW F with an expression that uses F. Replace with a temporary
1751 // placeholder first.
1752 Function *PlaceholderFn =
1754 F->getAddressSpace(), "", &M);
1755 replaceCfiUses(F, PlaceholderFn, IsJumpTableCanonical);
1756
1758 // Don't use range based loop, because use list will be modified.
1759 while (!PlaceholderFn->use_empty()) {
1760 Use &U = *PlaceholderFn->use_begin();
1761 auto *InsertPt = dyn_cast<Instruction>(U.getUser());
1762 assert(InsertPt && "Non-instruction users should have been eliminated");
1763 auto *PN = dyn_cast<PHINode>(InsertPt);
1764 if (PN)
1765 InsertPt = PN->getIncomingBlock(U)->getTerminator();
1766 IRBuilder Builder(InsertPt);
1767 Value *ICmp = Builder.CreateICmp(CmpInst::ICMP_NE, F,
1768 Constant::getNullValue(F->getType()));
1769 Value *Select = Builder.CreateSelect(ICmp, JT,
1770 Constant::getNullValue(F->getType()));
1771
1772 if (auto *SI = dyn_cast<SelectInst>(Select))
1774 // For phi nodes, we need to update the incoming value for all operands
1775 // with the same predecessor.
1776 if (PN)
1777 PN->setIncomingValueForBlock(InsertPt->getParent(), Select);
1778 else
1779 U.set(Select);
1780 }
1781 PlaceholderFn->eraseFromParent();
1782}
1783
1784static bool isThumbFunction(Function *F, Triple::ArchType ModuleArch) {
1785 Attribute TFAttr = F->getFnAttribute("target-features");
1786 if (TFAttr.isValid()) {
1788 TFAttr.getValueAsString().split(Features, ',');
1789 for (StringRef Feature : Features) {
1790 if (Feature == "-thumb-mode")
1791 return false;
1792 else if (Feature == "+thumb-mode")
1793 return true;
1794 }
1795 }
1796
1797 return ModuleArch == Triple::thumb;
1798}
1799
1800// Each jump table must be either ARM or Thumb as a whole for the bit-test math
1801// to work. Pick one that matches the majority of members to minimize interop
1802// veneers inserted by the linker.
1803Triple::ArchType LowerTypeTestsModule::selectJumpTableArmEncoding(
1804 ArrayRef<GlobalTypeMember *> Functions) {
1805 if (Arch != Triple::arm && Arch != Triple::thumb)
1806 return Arch;
1807
1808 if (!CanUseThumbBWJumpTable && CanUseArmJumpTable) {
1809 // In architectures that provide Arm and Thumb-1 but not Thumb-2,
1810 // we should always prefer the Arm jump table format, because the
1811 // Thumb-1 one is larger and slower.
1812 return Triple::arm;
1813 }
1814
1815 // Otherwise, go with majority vote.
1816 unsigned ArmCount = 0, ThumbCount = 0;
1817 for (const auto GTM : Functions) {
1818 if (!GTM->isJumpTableCanonical()) {
1819 // PLT stubs are always ARM.
1820 // FIXME: This is the wrong heuristic for non-canonical jump tables.
1821 ++ArmCount;
1822 continue;
1823 }
1824
1825 Function *F = cast<Function>(GTM->getGlobal());
1826 ++(isThumbFunction(F, Arch) ? ThumbCount : ArmCount);
1827 }
1828
1829 return ArmCount > ThumbCount ? Triple::arm : Triple::thumb;
1830}
1831
1832// Create location for each function entry which should look like this:
1833// frame #0: c::c() (.cfi_jt) at sanitizer/ubsan_interface.h:0:0
1834// frame #1: __ubsan_check_cfi_icall_jt at sanitizer/ubsan_interface.h:0
1835SmallVector<DILocation *> LowerTypeTestsModule::createJumpTableDebugInfo(
1837 if (!JumpTableDIB) {
1838 auto CUs = M.debug_compile_units();
1839 if (!CUs.empty())
1840 JumpTableCU = *CUs.begin();
1841 JumpTableDIB.emplace(M, /*AllowUnresolved=*/true, JumpTableCU);
1842 JumpTableFile = JumpTableDIB->createFile("ubsan_interface.h", "sanitizer");
1843 if (!JumpTableCU) {
1844 // Synthetic module (like ld-temp.o), it frequently lacks a DICompileUnit
1845 // even if the rest of the program has debug info.
1846 JumpTableCU = JumpTableDIB->createCompileUnit(
1847 DISourceLanguageName(dwarf::DW_LANG_C), JumpTableFile, "llvm", true,
1849 }
1850 JumpTableFnTy = JumpTableDIB->createSubroutineType(nullptr);
1851 }
1852
1853 DISubprogram *UbsanSP = JumpTableDIB->createFunction(
1854 JumpTableCU, "__ubsan_check_cfi_icall_jt", {}, JumpTableFile, 0,
1855 JumpTableFnTy, 0, DINode::FlagArtificial, DISubprogram::SPFlagDefinition);
1856
1857 F->setSubprogram(UbsanSP);
1858
1859 DILocation *UbsanLoc = DILocation::get(M.getContext(), 0, 0, UbsanSP);
1860
1862 Locations.reserve(Functions.size());
1863
1864 for (auto *Func : Functions) {
1865 StringRef FuncName = Func->getGlobal()->getName();
1866 FuncName.consume_back(".cfi");
1867 DISubprogram *JumpSP = JumpTableDIB->createFunction(
1868 JumpTableCU, (FuncName + ".cfi_jt").str(), {}, JumpTableFile, 0,
1869 JumpTableFnTy, 0, DINode::FlagArtificial,
1870 DISubprogram::SPFlagDefinition);
1871
1872 DILocation *EntryLoc =
1873 DILocation::get(M.getContext(), 0, 0, JumpSP, UbsanLoc);
1874
1875 Locations.push_back(EntryLoc);
1876 }
1877
1878 return Locations;
1879}
1880
1881void LowerTypeTestsModule::createJumpTable(
1883 Triple::ArchType JumpTableArch) {
1884 unsigned JumpTableEntrySize = getJumpTableEntrySize(JumpTableArch);
1885 // Give the jumptable section this type in order to enable jumptable
1886 // relaxation. Only do this if cross-DSO CFI is disabled because jumptable
1887 // relaxation violates cross-DSO CFI's restrictions on the ordering of the
1888 // jumptable relative to other sections.
1889 if (!CrossDsoCfi)
1890 F->setMetadata(LLVMContext::MD_elf_section_properties,
1891 MDNode::get(F->getContext(),
1893 ConstantAsMetadata::get(ConstantInt::get(
1894 Int64Ty, ELF::SHT_LLVM_CFI_JUMP_TABLE)),
1895 ConstantAsMetadata::get(ConstantInt::get(
1896 Int64Ty, JumpTableEntrySize))}));
1897
1898 BasicBlock *BB = BasicBlock::Create(M.getContext(), "entry", F);
1899 IRBuilder<> IRB(BB);
1900
1902 if (M.getDwarfVersion() != 0 && Opts.lowertypetests_jump_table_debug_info)
1903 Locations = createJumpTableDebugInfo(F, Functions);
1904
1905 InlineAsm *JumpTableAsm = createJumpTableEntryAsm(JumpTableArch);
1906
1907 // Check if all entries have the NoUnwind attribute.
1908 // If all entries have it, we can safely mark the
1909 // cfi.jumptable as NoUnwind, otherwise, direct calls
1910 // to the jump table will not handle exceptions properly
1911 bool areAllEntriesNounwind = true;
1912 assert(Locations.empty() || Functions.size() == Locations.size());
1913 for (auto [GTM, Loc] : zip_longest(Functions, Locations)) {
1914 if (Loc.has_value())
1915 IRB.SetCurrentDebugLocation(*Loc);
1916 if (!cast<Function>((*GTM)->getGlobal())
1917 ->hasFnAttribute(Attribute::NoUnwind)) {
1918 areAllEntriesNounwind = false;
1919 }
1920 IRB.CreateCall(JumpTableAsm, (*GTM)->getGlobal());
1921 }
1922 IRB.CreateUnreachable();
1923
1924 // Align the whole table by entry size.
1925 F->setPreferredAlignment(Align(JumpTableEntrySize));
1926 F->addFnAttr(Attribute::Naked);
1927 if (JumpTableArch == Triple::arm)
1928 F->addFnAttr("target-features", "-thumb-mode");
1929 if (JumpTableArch == Triple::thumb) {
1930 if (hasBranchTargetEnforcement()) {
1931 // If we're generating a Thumb jump table with BTI, add a target-features
1932 // setting to ensure BTI can be assembled.
1933 F->addFnAttr("target-features", "+thumb-mode,+pacbti");
1934 } else {
1935 F->addFnAttr("target-features", "+thumb-mode");
1936 if (CanUseThumbBWJumpTable) {
1937 // Thumb jump table assembly needs Thumb2. The following attribute is
1938 // added by Clang for -march=armv7.
1939 F->addFnAttr("target-cpu", "cortex-a8");
1940 }
1941 }
1942 }
1943 // When -mbranch-protection= is used, the inline asm adds a BTI. Suppress BTI
1944 // for the function to avoid double BTI. This is a no-op without
1945 // -mbranch-protection=.
1946 if (JumpTableArch == Triple::aarch64 || JumpTableArch == Triple::thumb) {
1947 if (F->hasFnAttribute("branch-target-enforcement"))
1948 F->removeFnAttr("branch-target-enforcement");
1949 if (F->hasFnAttribute("sign-return-address"))
1950 F->removeFnAttr("sign-return-address");
1951 }
1952 if (JumpTableArch == Triple::riscv32 || JumpTableArch == Triple::riscv64) {
1953 // Make sure the jump table assembly is not modified by the assembler or
1954 // the linker.
1955 F->addFnAttr("target-features", "-c,-relax");
1956 }
1957 // When -fcf-protection= is used, the inline asm adds an ENDBR. Suppress ENDBR
1958 // for the function to avoid double ENDBR. This is a no-op without
1959 // -fcf-protection=.
1960 if (JumpTableArch == Triple::x86 || JumpTableArch == Triple::x86_64)
1961 F->addFnAttr(Attribute::NoCfCheck);
1962
1963 // Make sure we don't emit .eh_frame for this function if it isn't needed.
1964 if (areAllEntriesNounwind)
1965 F->addFnAttr(Attribute::NoUnwind);
1966
1967 // Make sure we do not inline any calls to the cfi.jumptable.
1968 F->addFnAttr(Attribute::NoInline);
1969}
1970
1971/// Given a disjoint set of type identifiers and functions, build a jump table
1972/// for the functions, build the bit sets and lower the llvm.type.test calls.
1973void LowerTypeTestsModule::buildBitSetsFromFunctionsNative(
1975 // Unlike the global bitset builder, the function bitset builder cannot
1976 // re-arrange functions in a particular order and base its calculations on the
1977 // layout of the functions' entry points, as we have no idea how large a
1978 // particular function will end up being (the size could even depend on what
1979 // this pass does!) Instead, we build a jump table, which is a block of code
1980 // consisting of one branch instruction for each of the functions in the bit
1981 // set that branches to the target function, and redirect any taken function
1982 // addresses to the corresponding jump table entry. In the object file's
1983 // symbol table, the symbols for the target functions also refer to the jump
1984 // table entries, so that addresses taken outside the module will pass any
1985 // verification done inside the module.
1986 //
1987 // In more concrete terms, suppose we have three functions f, g, h which are
1988 // of the same type, and a function foo that returns their addresses:
1989 //
1990 // f:
1991 // mov 0, %eax
1992 // ret
1993 //
1994 // g:
1995 // mov 1, %eax
1996 // ret
1997 //
1998 // h:
1999 // mov 2, %eax
2000 // ret
2001 //
2002 // foo:
2003 // mov f, %eax
2004 // mov g, %edx
2005 // mov h, %ecx
2006 // ret
2007 //
2008 // We output the jump table as module-level inline asm string. The end result
2009 // will (conceptually) look like this:
2010 //
2011 // f = .cfi.jumptable
2012 // g = .cfi.jumptable + 4
2013 // h = .cfi.jumptable + 8
2014 // .cfi.jumptable:
2015 // jmp f.cfi ; 5 bytes
2016 // int3 ; 1 byte
2017 // int3 ; 1 byte
2018 // int3 ; 1 byte
2019 // jmp g.cfi ; 5 bytes
2020 // int3 ; 1 byte
2021 // int3 ; 1 byte
2022 // int3 ; 1 byte
2023 // jmp h.cfi ; 5 bytes
2024 // int3 ; 1 byte
2025 // int3 ; 1 byte
2026 // int3 ; 1 byte
2027 //
2028 // f.cfi:
2029 // mov 0, %eax
2030 // ret
2031 //
2032 // g.cfi:
2033 // mov 1, %eax
2034 // ret
2035 //
2036 // h.cfi:
2037 // mov 2, %eax
2038 // ret
2039 //
2040 // foo:
2041 // mov f, %eax
2042 // mov g, %edx
2043 // mov h, %ecx
2044 // ret
2045 //
2046 // Because the addresses of f, g, h are evenly spaced at a power of 2, in the
2047 // normal case the check can be carried out using the same kind of simple
2048 // arithmetic that we normally use for globals.
2049
2050 // FIXME: find a better way to represent the jumptable in the IR.
2051 assert(!Functions.empty());
2052
2053 // Decide on the jump table encoding, so that we know how big the
2054 // entries will be.
2055 Triple::ArchType JumpTableArch = selectJumpTableArmEncoding(Functions);
2056
2057 // Build a simple layout based on the regular layout of jump tables.
2058 DenseMap<GlobalTypeMember *, uint64_t> GlobalLayout;
2059 unsigned EntrySize = getJumpTableEntrySize(JumpTableArch);
2060 for (unsigned I = 0; I != Functions.size(); ++I)
2061 GlobalLayout[Functions[I]] = I * EntrySize;
2062
2063 Function *JumpTableFn =
2065 /* IsVarArg */ false),
2067 M.getDataLayout().getProgramAddressSpace(),
2068 ".cfi.jumptable", &M);
2069 ArrayType *JumpTableEntryType = ArrayType::get(Int8Ty, EntrySize);
2071 ArrayType::get(JumpTableEntryType, Functions.size());
2073 JumpTableFn, PointerType::getUnqual(M.getContext()));
2074
2075 lowerTypeTestCalls(TypeIds, JumpTable, GlobalLayout);
2076
2077 SmallVector<GlobalValue *> UsedJtAliases;
2078
2079 // Build aliases pointing to offsets into the jump table, and replace
2080 // references to the original functions with references to the aliases.
2081 for (unsigned I = 0; I != Functions.size(); ++I) {
2082 Function *F = cast<Function>(Functions[I]->getGlobal());
2083 bool IsJumpTableCanonical = Functions[I]->isJumpTableCanonical();
2084
2085 Constant *CombinedGlobalElemPtr = ConstantExpr::getGetElementPtr(
2086 F->getDataLayout(), JumpTableType, JumpTable,
2087 {ConstantInt::get(IntPtrTy, 0), ConstantInt::get(IntPtrTy, I)},
2089
2090 const bool IsExported = Functions[I]->isExported();
2091 if (!IsJumpTableCanonical) {
2094 GlobalAlias *JtAlias = GlobalAlias::create(JumpTableEntryType, 0, LT,
2095 F->getName() + ".cfi_jt",
2096 CombinedGlobalElemPtr, &M);
2097 if (IsExported)
2099 else
2100 UsedJtAliases.push_back(JtAlias);
2101 }
2102
2103 if (IsExported) {
2104 GlobalValue::GUID GUID = F->getGUID();
2105 if (IsJumpTableCanonical)
2106 ExportSummary->cfiFunctionDefs().addSymbolWithThinLTOGUID(F->getName(),
2107 GUID);
2108 else
2109 ExportSummary->cfiFunctionDecls().addSymbolWithThinLTOGUID(F->getName(),
2110 GUID);
2111 }
2112
2113 if (!IsJumpTableCanonical) {
2114 if (F->hasExternalWeakLinkage())
2115 replaceWeakDeclarationWithJumpTablePtr(F, CombinedGlobalElemPtr,
2116 IsJumpTableCanonical);
2117 else
2118 replaceCfiUses(F, CombinedGlobalElemPtr, IsJumpTableCanonical);
2119 } else {
2120 assert(F->getType()->getAddressSpace() == 0);
2121
2122 GlobalAlias *FAlias =
2123 GlobalAlias::create(JumpTableEntryType, 0, F->getLinkage(), "",
2124 CombinedGlobalElemPtr, &M);
2125 FAlias->setVisibility(F->getVisibility());
2126 FAlias->setDSOLocal(F->isDSOLocal());
2127 FAlias->takeName(F);
2128 if (FAlias->hasName()) {
2129 F->setName(FAlias->getName() + ".cfi");
2130 maybeReplaceComdat(F, FAlias->getName());
2131 }
2132 replaceCfiUses(F, FAlias, IsJumpTableCanonical);
2133 if (!F->hasLocalLinkage())
2134 F->setVisibility(GlobalVariable::HiddenVisibility);
2135 }
2136 }
2137
2138 if (!UsedJtAliases.empty())
2139 appendToUsed(M, UsedJtAliases);
2140
2141 createJumpTable(JumpTableFn, Functions, JumpTableArch);
2142}
2143
2144/// Assign a dummy layout using an incrementing counter, tag each function
2145/// with its index represented as metadata, and lower each type test to an
2146/// integer range comparison. During generation of the indirect function call
2147/// table in the backend, it will assign the given indexes.
2148/// Note: Dynamic linking is not supported, as the WebAssembly ABI has not yet
2149/// been finalized.
2150void LowerTypeTestsModule::buildBitSetsFromFunctionsWASM(
2152 assert(!Functions.empty());
2153
2154 // Build consecutive monotonic integer ranges for each call target set
2155 DenseMap<GlobalTypeMember *, uint64_t> GlobalLayout;
2156
2157 for (GlobalTypeMember *GTM : Functions) {
2158 Function *F = cast<Function>(GTM->getGlobal());
2159
2160 // Skip functions that are not address taken, to avoid bloating the table
2161 if (!F->hasAddressTaken())
2162 continue;
2163
2164 // Store metadata with the index for each function
2165 MDNode *MD = MDNode::get(F->getContext(),
2167 ConstantInt::get(Int64Ty, IndirectIndex))));
2168 F->setMetadata("wasm.index", MD);
2169
2170 // Assign the counter value
2171 GlobalLayout[GTM] = IndirectIndex++;
2172 }
2173
2174 // The indirect function table index space starts at zero, so pass a NULL
2175 // pointer as the subtracted "jump table" offset.
2176 lowerTypeTestCalls(TypeIds, ConstantPointerNull::get(PtrTy),
2177 GlobalLayout);
2178}
2179
2180void LowerTypeTestsModule::buildBitSetsFromDisjointSet(
2182 ArrayRef<ICallBranchFunnel *> ICallBranchFunnels) {
2183 DenseMap<Metadata *, uint64_t> TypeIdIndices;
2184 for (unsigned I = 0; I != TypeIds.size(); ++I)
2185 TypeIdIndices[TypeIds[I]] = I;
2186
2187 // For each type identifier, build a set of indices that refer to members of
2188 // the type identifier.
2189 std::vector<std::set<uint64_t>> TypeMembers(TypeIds.size());
2190 unsigned GlobalIndex = 0;
2191 DenseMap<GlobalTypeMember *, uint64_t> GlobalIndices;
2192 for (GlobalTypeMember *GTM : Globals) {
2193 for (MDNode *Type : GTM->types()) {
2194 // Type = { offset, type identifier }
2195 auto I = TypeIdIndices.find(Type->getOperand(1));
2196 if (I != TypeIdIndices.end())
2197 TypeMembers[I->second].insert(GlobalIndex);
2198 }
2199 GlobalIndices[GTM] = GlobalIndex;
2200 GlobalIndex++;
2201 }
2202
2203 for (ICallBranchFunnel *JT : ICallBranchFunnels) {
2204 TypeMembers.emplace_back();
2205 std::set<uint64_t> &TMSet = TypeMembers.back();
2206 for (GlobalTypeMember *T : JT->targets())
2207 TMSet.insert(GlobalIndices[T]);
2208 }
2209
2210 // Order the sets of indices by size. The GlobalLayoutBuilder works best
2211 // when given small index sets first.
2212 llvm::stable_sort(TypeMembers, [](const std::set<uint64_t> &O1,
2213 const std::set<uint64_t> &O2) {
2214 return O1.size() < O2.size();
2215 });
2216
2217 bool IsGlobalSet =
2218 Globals.empty() || isa<GlobalVariable>(Globals[0]->getGlobal());
2219
2220 unique_function<bool(uint64_t, uint64_t)> Less;
2221 if (!IsGlobalSet && !FunctionSummaryHotness.empty() &&
2222 Opts.reorder_cfi_jump_tables_profiles) {
2223 // Estimated weight of each jump entry.
2224 std::vector<CfiFunctionHotness> GTMHotness;
2225 GTMHotness.reserve(Globals.size());
2226 for (GlobalTypeMember *GTM : Globals) {
2227 GTMHotness.push_back(
2228 FunctionSummaryHotness.lookup(cast<Function>(GTM->getGlobal())));
2229 }
2230
2231 // Order jump table entries by hotness ascending so that the hottest
2232 // entry is placed at the end of the jump table:
2233 // 1. Under jump table relaxation (SHT_LLVM_CFI_JUMP_TABLE), the linker
2234 // moves the jump table directly before the target of the last entry
2235 // and deletes its branch so the target function body acts as the
2236 // last entry.
2237 // 2. The jump table is placed into the output section of that last
2238 // target. Jump tables are critical to performance; if the last
2239 // entry were a cold function, the jump table would be dragged into a
2240 // cold binary section (such as .text.unlikely). Placing the hottest
2241 // entry at the end ensures the jump table lands in a hot section and
2242 // the hottest callee benefits from fall-through without a branch.
2243 Less = [GTMHotness = std::move(GTMHotness)](uint64_t A, uint64_t B) {
2244 return GTMHotness[A] < GTMHotness[B];
2245 };
2246 }
2247
2248 // Create a GlobalLayoutBuilder and provide it with index sets as layout
2249 // fragments. The GlobalLayoutBuilder tries to lay out members of fragments as
2250 // close together as possible.
2251 GlobalLayoutBuilder GLB(Globals.size(), std::move(Less));
2252 for (auto &&MemSet : TypeMembers)
2253 GLB.addFragment(MemSet);
2254
2255 // Build a vector of globals with the computed layout.
2256 std::vector<GlobalTypeMember *> OrderedGTMs(Globals.size());
2257 auto OGTMI = OrderedGTMs.begin();
2258 for (uint64_t Offset : GLB.build()) {
2259 if (IsGlobalSet != isa<GlobalVariable>(Globals[Offset]->getGlobal()))
2260 report_fatal_error("Type identifier may not contain both global "
2261 "variables and functions");
2262 *OGTMI++ = Globals[Offset];
2263 }
2264
2265 // Build the bitsets from this disjoint set.
2266 if (IsGlobalSet)
2267 buildBitSetsFromGlobalVariables(TypeIds, OrderedGTMs);
2268 else
2269 buildBitSetsFromFunctions(TypeIds, OrderedGTMs);
2270}
2271
2272/// Lower all type tests in this module.
2273LowerTypeTestsModule::LowerTypeTestsModule(
2274 Module &M, ModuleAnalysisManager &AM, ModuleSummaryIndex *ExportSummary,
2275 const ModuleSummaryIndex *ImportSummary)
2276 : Opts(getIPOOptions(M)), M(M), ExportSummary(ExportSummary),
2277 ImportSummary(ImportSummary) {
2278 assert(!(ExportSummary && ImportSummary));
2279 Triple TargetTriple(M.getTargetTriple());
2280 Arch = TargetTriple.getArch();
2281 auto &FAM = AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
2282
2283 if (Arch == Triple::arm)
2284 CanUseArmJumpTable = true;
2285 if (Arch == Triple::arm || Arch == Triple::thumb) {
2286 for (Function &F : M) {
2287 // Skip declarations since we should not query the TTI for them.
2288 if (F.isDeclaration())
2289 continue;
2290 auto &TTI = FAM.getResult<TargetIRAnalysis>(F);
2291 if (TTI.hasArmWideBranch(false))
2292 CanUseArmJumpTable = true;
2293 if (TTI.hasArmWideBranch(true))
2294 CanUseThumbBWJumpTable = true;
2295 }
2296 }
2297 ObjectFormat = TargetTriple.getObjectFormat();
2298
2299 // Function annotation describes or applies to function itself, and
2300 // shouldn't be associated with jump table thunk generated for CFI.
2301 GlobalAnnotation = M.getGlobalVariable("llvm.global.annotations");
2302 if (GlobalAnnotation && GlobalAnnotation->hasInitializer()) {
2303 const ConstantArray *CA =
2304 cast<ConstantArray>(GlobalAnnotation->getInitializer());
2305 FunctionAnnotations.insert_range(CA->operands());
2306 }
2307}
2308
2309bool LowerTypeTestsModule::runForTesting(Module &M, ModuleAnalysisManager &AM) {
2310 const IPOOptions &Opts = getIPOOptions(M);
2311 StringRef ReadSummary = Opts.lowertypetests_read_summary;
2312 StringRef WriteSummary = Opts.lowertypetests_write_summary;
2313 PassSummaryAction SummaryAction = Opts.lowertypetests_summary_action;
2314 std::unique_ptr<ModuleSummaryIndex> Summary;
2315
2316 // Handle the command-line summary arguments. This code is for testing
2317 // purposes only, so we handle errors directly.
2318 if (!ReadSummary.empty()) {
2319 ExitOnError ExitOnErr(
2320 ("-lowertypetests-read-summary: " + ReadSummary + ": ").str());
2321 auto ReadSummaryFile = ExitOnErr(
2322 errorOrToExpected(MemoryBuffer::getFile(ReadSummary, /*IsText=*/true)));
2323 // TODO: Convert the rest of tests (some YAML features are missing from
2324 // textual summary assembly) and remove YAML from this file.
2325 if (ReadSummaryFile->getBuffer().starts_with("---")) {
2326 Summary = std::make_unique<ModuleSummaryIndex>(/*HaveGVs=*/false);
2327 yaml::Input In(ReadSummaryFile->getBuffer());
2328 In >> *Summary;
2329 ExitOnErr(errorCodeToError(In.error()));
2330 } else {
2331 SMDiagnostic Err;
2332 Summary =
2333 parseSummaryIndexAssembly(ReadSummaryFile->getMemBufferRef(), Err);
2334 if (!Summary) {
2335 Err.print(ReadSummary.str().c_str(), errs());
2336 report_fatal_error("Failed to parse summary index assembly");
2337 }
2338 }
2339 } else {
2340 Summary = std::make_unique<ModuleSummaryIndex>(/*HaveGVs=*/false);
2341 }
2342
2343 bool Changed =
2344 LowerTypeTestsModule(
2345 M, AM,
2346 SummaryAction == PassSummaryAction::Export ? Summary.get() : nullptr,
2347 SummaryAction == PassSummaryAction::Import ? Summary.get() : nullptr)
2348 .lower();
2349
2350 if (!WriteSummary.empty()) {
2351 ExitOnError ExitOnErr(
2352 ("-lowertypetests-write-summary: " + WriteSummary + ": ").str());
2353 std::error_code EC;
2354 raw_fd_ostream OS(WriteSummary, EC, sys::fs::OF_TextWithCRLF);
2355 ExitOnErr(errorCodeToError(EC));
2356
2357 yaml::Output Out(OS);
2358 Out << *Summary;
2359 }
2360
2361 return Changed;
2362}
2363
2364static bool isDirectCall(Use& U) {
2365 auto *Usr = dyn_cast<CallInst>(U.getUser());
2366 return Usr && Usr->isCallee(&U);
2367}
2368
2369void LowerTypeTestsModule::replaceCfiUses(Function *Old, Value *New,
2370 bool IsJumpTableCanonical) {
2371 SmallSetVector<Constant *, 4> Constants;
2372 for (Use &U : llvm::make_early_inc_range(Old->uses())) {
2373 // Skip no_cfi values, which refer to the function body instead of the jump
2374 // table.
2375 if (isa<NoCFIValue>(U.getUser()))
2376 continue;
2377
2378 // Skip direct calls to externally defined or dso_local functions.
2379 if (isDirectCall(U) && (Old->isDSOLocal() || !IsJumpTableCanonical))
2380 continue;
2381
2382 // Skip function annotation.
2383 if (isFunctionAnnotation(U.getUser()))
2384 continue;
2385
2386 // Must handle Constants specially, we cannot call replaceUsesOfWith on a
2387 // constant because they are uniqued.
2388 if (auto *C = dyn_cast<Constant>(U.getUser())) {
2389 if (!isa<GlobalValue>(C)) {
2390 // Save unique users to avoid processing operand replacement
2391 // more than once.
2392 Constants.insert(C);
2393 continue;
2394 }
2395 }
2396
2397 U.set(New);
2398 }
2399
2400 // Process operand replacement of saved constants.
2401 for (auto *C : Constants)
2402 C->handleOperandChange(Old, New);
2403}
2404
2405void LowerTypeTestsModule::replaceDirectCalls(Value *Old, Value *New) {
2407}
2408
2409// Sound wherever the caller has already dropped the type tests: the check
2410// folds to true, the trap branch becomes dead, and later passes fold it
2411// away. Required because the backend cannot select these intrinsics
2412// ("must be lowered by the LowerTypeTests pass before code generation").
2414 Module &M, Function &CheckedLoadFn, bool IsRelative,
2415 SmallSetVector<Function *, 8> *ModifiedFunctions) {
2416 bool Changed = false;
2417 for (User *User : llvm::make_early_inc_range(CheckedLoadFn.users())) {
2419 if (!I)
2420 continue;
2421 IRBuilder<> IRB(I);
2422 Value *Ptr = I->getOperand(0);
2423 Value *Offset = I->getOperand(1);
2424 Type *PtrTy = I->getType()->getStructElementType(0);
2425 ConstantInt *True = ConstantInt::getTrue(M.getContext());
2427 if (IsRelative) {
2429 Intrinsic::load_relative, {Offset->getType()}, {Ptr, Offset},
2430 /*FMFSource=*/nullptr, "rel_load");
2431 } else {
2432 Value *PtrAdd = IRB.CreatePtrAddWithSExtOrTrunc(Ptr, Offset);
2433 Load = IRB.CreateLoad(PtrTy, PtrAdd, "vfunc");
2434 }
2435
2436 Value *Replacement = PoisonValue::get(I->getType());
2437 Replacement = IRB.CreateInsertValue(Replacement, True, {1});
2438 Replacement = IRB.CreateInsertValue(Replacement, Load, {0});
2439 I->replaceAllUsesWith(Replacement);
2440
2441 if (ModifiedFunctions)
2442 ModifiedFunctions->insert(I->getFunction());
2443
2444 LLVM_DEBUG(dbgs() << DEBUG_TYPE << ": erase " << *I << "\n");
2445 I->eraseFromParent();
2446 Changed = true;
2447 }
2448 if (Changed) {
2449 CheckedLoadFn.eraseFromParent();
2450 for (GlobalVariable &GV : M.globals())
2451 GV.eraseMetadata(LLVMContext::MD_vcall_visibility);
2452 }
2453 return Changed;
2454}
2455
2456static void dropTypeTests(Module &M, Function &TypeTestFunc, bool ShouldDropAll,
2457 SmallSetVector<Function *, 8> &ModifiedFunctions) {
2458 for (Use &U : llvm::make_early_inc_range(TypeTestFunc.uses())) {
2459 auto *CI = cast<CallInst>(U.getUser());
2460 ModifiedFunctions.insert(CI->getFunction());
2461 // Find and erase llvm.assume intrinsics for this llvm.type.test call.
2462 for (Use &CIU : llvm::make_early_inc_range(CI->uses()))
2463 if (auto *Assume = dyn_cast<AssumeInst>(CIU.getUser()))
2464 Assume->eraseFromParent();
2465 // If the assume was merged with another assume, we might have a use on a
2466 // phi or select (which will feed the assume). Simply replace the use on
2467 // the phi/select with "true" and leave the merged assume.
2468 //
2469 // If ShouldDropAll is set, then we we need to update any remaining uses,
2470 // regardless of the instruction type.
2471 if (!CI->use_empty()) {
2472 assert(ShouldDropAll || all_of(CI->users(), [](User *U) -> bool {
2473 return isa<PHINode>(U) || isa<SelectInst>(U);
2474 }));
2475 CI->replaceAllUsesWith(ConstantInt::getTrue(M.getContext()));
2476 }
2477 CI->eraseFromParent();
2478 }
2479}
2480
2481static bool dropTypeTests(Module &M, bool ShouldDropAll,
2482 SmallSetVector<Function *, 8> &ModifiedFunctions) {
2483 Function *TypeTestFunc =
2484 Intrinsic::getDeclarationIfExists(&M, Intrinsic::type_test);
2485 if (TypeTestFunc)
2486 dropTypeTests(M, *TypeTestFunc, ShouldDropAll, ModifiedFunctions);
2487 // Only drop checked loads when dropping everything: in Assume mode a
2488 // checked load may feed a CFI trap check, which must keep diagnosing
2489 // loudly instead of being turned to true.
2490 bool DroppedCheckedLoads = false;
2491 if (ShouldDropAll) {
2492 if (Function *F =
2493 Intrinsic::getDeclarationIfExists(&M, Intrinsic::type_checked_load))
2494 DroppedCheckedLoads |= lowertypetests::cleanUpTypeCheckedLoad(
2495 M, *F, false, &ModifiedFunctions);
2497 &M, Intrinsic::type_checked_load_relative))
2498 DroppedCheckedLoads |= lowertypetests::cleanUpTypeCheckedLoad(
2499 M, *F, true, &ModifiedFunctions);
2500 }
2501 // Normally we'd have already removed all @llvm.public.type.test calls,
2502 // except for in the case where we originally were performing ThinLTO but
2503 // decided not to in the backend.
2504 Function *PublicTypeTestFunc =
2505 Intrinsic::getDeclarationIfExists(&M, Intrinsic::public_type_test);
2506 if (PublicTypeTestFunc)
2507 dropTypeTests(M, *PublicTypeTestFunc, ShouldDropAll, ModifiedFunctions);
2508 bool Changed = TypeTestFunc || PublicTypeTestFunc || DroppedCheckedLoads;
2509 if (Changed || ShouldDropAll) {
2510 // We have deleted the type intrinsics, so we no longer have enough
2511 // information to reason about the liveness of virtual function pointers
2512 // in GlobalDCE.
2513 for (GlobalVariable &GV : M.globals())
2514 Changed |= GV.eraseMetadata(LLVMContext::MD_vcall_visibility);
2515 }
2516 return Changed;
2517}
2518
2519bool LowerTypeTestsModule::lower() {
2520 Function *TypeTestFunc =
2521 Intrinsic::getDeclarationIfExists(&M, Intrinsic::type_test);
2522
2523 // If only some of the modules were split, we cannot correctly perform
2524 // this transformation. We already checked for the presense of type tests
2525 // with partially split modules during the thin link, and would have emitted
2526 // an error if any were found, so here we can simply return.
2527 if ((ExportSummary && ExportSummary->partiallySplitLTOUnits()) ||
2528 (ImportSummary && ImportSummary->partiallySplitLTOUnits()))
2529 return false;
2530
2531 Function *ICallBranchFunnelFunc =
2532 Intrinsic::getDeclarationIfExists(&M, Intrinsic::icall_branch_funnel);
2533 if ((!TypeTestFunc || TypeTestFunc->use_empty()) &&
2534 (!ICallBranchFunnelFunc || ICallBranchFunnelFunc->use_empty()) &&
2535 !ExportSummary && !ImportSummary)
2536 return false;
2537
2538 if (ImportSummary) {
2539 if (TypeTestFunc)
2540 for (Use &U : llvm::make_early_inc_range(TypeTestFunc->uses()))
2541 importTypeTest(cast<CallInst>(U.getUser()));
2542
2543 if (ICallBranchFunnelFunc && !ICallBranchFunnelFunc->use_empty())
2545 "unexpected call to llvm.icall.branch.funnel during import phase");
2546
2547 // For internal linkage cfiFunction defs/decls, we only needed the alias
2548 // through the linker. We can replace those aliases with the aliased
2549 // function here.
2551 for (auto &A : llvm::make_early_inc_range(M.aliases())) {
2552 if (A.hasLocalLinkage())
2553 continue;
2554 if (ImportSummary->cfiFunctionDefs().contains(A.getName()) ||
2555 ImportSummary->cfiFunctionDecls().contains(A.getName())) {
2556 if (auto *F = dyn_cast_or_null<Function>(A.getAliaseeObject())) {
2557 if (F->hasExternalLinkage()) {
2558 // The original internal linkage function was independently promoted
2559 // by thinlink. While, pre-link, all static references to it
2560 // (implicitly, module-internal) were replaced with references to
2561 // the alias, thinlink might decide to promote it because (for
2562 // example) it turns out to be a hot indirect call target in a
2563 // different module.
2564 // In that case, we need to remember its thinlink-promoted name
2565 // because it's potentially referenced elsewhere, and make sure
2566 // there's an alias to it.
2567 PromotedFuncs.emplace_back(F, F->getName());
2568 } else {
2569 F->setLinkage(GlobalValue::ExternalLinkage);
2570 F->setVisibility(GlobalValue::HiddenVisibility);
2571 }
2572 A.replaceAllUsesWith(F);
2573 F->takeName(&A);
2574 A.eraseFromParent();
2575 }
2576 }
2577 }
2578
2581 for (auto &F : M) {
2582 // CFI functions are either external, or promoted. A local function may
2583 // have the same name, but it's not the one we are looking for.
2584 if (F.hasLocalLinkage())
2585 continue;
2586 if (ImportSummary->cfiFunctionDefs().contains(F.getName()))
2587 Defs.push_back(&F);
2588 else if (ImportSummary->cfiFunctionDecls().contains(F.getName()))
2589 Decls.push_back(&F);
2590 }
2591
2592 {
2593 ScopedSaveAliaseesAndUsed S(M);
2594 for (auto *F : Defs)
2595 importFunction(F, /*isJumpTableCanonical*/ true);
2596 for (auto *F : Decls)
2597 importFunction(F, /*isJumpTableCanonical*/ false);
2598 }
2599 // Add an alias with the thinlink promotion name.
2600 for (auto &[F, Name] : PromotedFuncs)
2601 GlobalAlias::create(GlobalValue::LinkageTypes::ExternalLinkage, Name, F);
2602
2603 return true;
2604 }
2605
2606 // Equivalence class set containing type identifiers and the globals that
2607 // reference them. This is used to partition the set of type identifiers in
2608 // the module into disjoint sets.
2609 using GlobalClassesTy = EquivalenceClasses<
2610 PointerUnion<GlobalTypeMember *, Metadata *, ICallBranchFunnel *>>;
2611 GlobalClassesTy GlobalClasses;
2612
2613 // Verify the type metadata and build a few data structures to let us
2614 // efficiently enumerate the type identifiers associated with a global:
2615 // a list of GlobalTypeMembers (a GlobalObject stored alongside a vector
2616 // of associated type metadata) and a mapping from type identifiers to their
2617 // list of GlobalTypeMembers and last observed index in the list of globals.
2618 // The indices will be used later to deterministically order the list of type
2619 // identifiers.
2621 struct TIInfo {
2622 unsigned UniqueId;
2623 std::vector<GlobalTypeMember *> RefGlobals;
2624 };
2625 DenseMap<Metadata *, TIInfo> TypeIdInfo;
2626 unsigned CurUniqueId = 0;
2628
2629 struct ExportedFunctionInfo {
2630 CfiFunctionLinkage Linkage;
2631 MDNode *FuncMD; // {name, linkage, type[, type...]}
2632 };
2633 MapVector<StringRef, ExportedFunctionInfo> ExportedFunctions;
2634 if (ExportSummary) {
2635 NamedMDNode *CfiFunctionsMD = M.getNamedMetadata("cfi.functions");
2636 if (CfiFunctionsMD) {
2637 // A set of all functions that are address taken by a live global object.
2638 DenseSet<GlobalValue::GUID> AddressTaken;
2639 for (auto &I : *ExportSummary)
2640 for (auto &GVS : I.second.getSummaryList())
2641 if (GVS->isLive())
2642 for (const auto &Ref : GVS->refs()) {
2643 AddressTaken.insert(Ref.getGUID());
2644 for (auto &RefGVS : Ref.getSummaryList())
2645 if (auto Alias = dyn_cast<AliasSummary>(RefGVS.get()))
2646 AddressTaken.insert(Alias->getAliaseeGUID());
2647 }
2649 if (AddressTaken.count(GUID))
2650 return true;
2651 auto VI = ExportSummary->getValueInfo(GUID);
2652 if (!VI)
2653 return false;
2654 for (auto &I : VI.getSummaryList())
2655 if (auto Alias = dyn_cast<AliasSummary>(I.get()))
2656 if (AddressTaken.count(Alias->getAliaseeGUID()))
2657 return true;
2658 return false;
2659 };
2660 for (auto *FuncMD : CfiFunctionsMD->operands()) {
2661 assert(FuncMD->getNumOperands() >= 2);
2662 StringRef FunctionName =
2663 cast<MDString>(FuncMD->getOperand(0))->getString();
2664 CfiFunctionLinkage Linkage = decodeCfiFunctionLinkage(
2665 cast<ConstantAsMetadata>(FuncMD->getOperand(1))
2666 ->getValue()
2667 ->getUniqueInteger()
2668 .getZExtValue());
2669 const GlobalValue::GUID GUID =
2670 cast<ConstantAsMetadata>(FuncMD->getOperand(2))
2671 ->getValue()
2672 ->getUniqueInteger()
2673 .getZExtValue();
2674 // Do not emit jumptable entries for functions that are not-live and
2675 // have no live references (and are not exported with cross-DSO CFI.)
2676 if (!ExportSummary->isGUIDLive(GUID))
2677 continue;
2678 if (!IsAddressTaken(GUID)) {
2679 if (!CrossDsoCfi || Linkage != CfiFunctionLinkage::Definition)
2680 continue;
2681
2682 bool Exported = false;
2683 if (auto VI = ExportSummary->getValueInfo(GUID))
2684 for (const auto &GVS : VI.getSummaryList())
2685 if (GVS->isLive() && !GlobalValue::isLocalLinkage(GVS->linkage()))
2686 Exported = true;
2687
2688 if (!Exported)
2689 continue;
2690 }
2691 auto P = ExportedFunctions.insert({FunctionName, {Linkage, FuncMD}});
2692 if (!P.second &&
2693 P.first->second.Linkage != CfiFunctionLinkage::Definition)
2694 P.first->second = {Linkage, FuncMD};
2695 }
2696
2697 for (const auto &P : ExportedFunctions) {
2698 StringRef FunctionName = P.first;
2699 CfiFunctionLinkage Linkage = P.second.Linkage;
2700 MDNode *FuncMD = P.second.FuncMD;
2701 Function *F = M.getFunction(FunctionName);
2702 if (F && F->hasLocalLinkage()) {
2703 // Locally defined function that happens to have the same name as a
2704 // function defined in a ThinLTO module. Rename it to move it out of
2705 // the way of the external reference that we're about to create.
2706 // Note that setName will find a unique name for the function, so even
2707 // if there is an existing function with the suffix there won't be a
2708 // name collision.
2709 F->setName(F->getName() + ".1");
2710 F = nullptr;
2711 }
2712
2713 if (!F) {
2715 FunctionType::get(Type::getVoidTy(M.getContext()), false),
2716 GlobalVariable::ExternalLinkage,
2717 M.getDataLayout().getProgramAddressSpace(), FunctionName, &M);
2718 F->setMetadata(
2719 LLVMContext::MD_guid,
2720 MDTuple::get(M.getContext(), {FuncMD->getOperand(2).get()}));
2721 if (ExportSummary) {
2724 ->getValue()
2725 ->getUniqueInteger()
2726 .getZExtValue();
2727 if (auto VI = ExportSummary->getValueInfo(GUID))
2728 F->setDSOLocal(
2729 VI.isDSOLocal(ExportSummary->withDSOLocalPropagation()));
2730 }
2731 }
2732 // If the function is available_externally, remove its definition so
2733 // that it is handled the same way as a declaration. Later we will try
2734 // to create an alias using this function's linkage, which will fail if
2735 // the linkage is available_externally. This will also result in us
2736 // following the code path below to replace the type metadata.
2737 if (F->hasAvailableExternallyLinkage()) {
2738 // Maintain !guid metadata.
2739 auto *OrigGUIDMD = F->getMetadata(LLVMContext::MD_guid);
2740 F->setLinkage(GlobalValue::ExternalLinkage);
2741 F->deleteBody();
2742 F->setComdat(nullptr);
2743 F->clearMetadata();
2744 F->setMetadata(LLVMContext::MD_guid, OrigGUIDMD);
2745 }
2746
2747 // Update the linkage for extern_weak declarations when a definition
2748 // exists.
2749 if (Linkage == CfiFunctionLinkage::Definition &&
2750 F->hasExternalWeakLinkage())
2751 F->setLinkage(GlobalValue::ExternalLinkage);
2752
2753 // If the function in the full LTO module is a declaration, replace its
2754 // type metadata with the type metadata we found in cfi.functions. That
2755 // metadata is presumed to be more accurate than the metadata attached
2756 // to the declaration.
2757 if (F->isDeclaration()) {
2758 if (Linkage == CfiFunctionLinkage::WeakDeclaration)
2760
2761 F->eraseMetadata(LLVMContext::MD_type);
2762 for (unsigned I = 3; I < FuncMD->getNumOperands(); ++I)
2763 F->addMetadata(LLVMContext::MD_type,
2764 *cast<MDNode>(FuncMD->getOperand(I).get()));
2765 }
2766 uint8_t Encoded = cast<ConstantAsMetadata>(FuncMD->getOperand(1))
2767 ->getValue()
2768 ->getUniqueInteger()
2769 .getZExtValue();
2770 // TODO: Implement for Full LTO.
2771 FunctionSummaryHotness[F] = decodeCfiFunctionHotness(Encoded);
2772 }
2773 }
2774 }
2775
2776 struct AliasToCreate {
2777 Function *Alias;
2778 std::string TargetName;
2779 };
2780 std::vector<AliasToCreate> AliasesToCreate;
2781
2782 // Parse alias data to replace stand-in function declarations for aliases
2783 // with an alias to the intended target.
2784 if (ExportSummary) {
2785 if (NamedMDNode *AliasesMD = M.getNamedMetadata("aliases")) {
2786 for (auto *AliasMD : AliasesMD->operands()) {
2788 for (MDString *MDS : make_isa_range<MDString>(AliasMD->operands())) {
2789 StringRef AliasName = MDS->getString();
2790 if (!ExportedFunctions.count(AliasName))
2791 continue;
2792 auto *AliasF = M.getFunction(AliasName);
2793 if (AliasF)
2794 Aliases.push_back(AliasF);
2795 }
2796
2797 if (Aliases.empty())
2798 continue;
2799
2800 for (unsigned I = 1; I != Aliases.size(); ++I) {
2801 auto *AliasF = Aliases[I];
2802 ExportedFunctions.erase(AliasF->getName());
2803 AliasesToCreate.push_back(
2804 {AliasF, std::string(Aliases[0]->getName())});
2805 }
2806 }
2807 }
2808 }
2809
2810 DenseMap<GlobalObject *, GlobalTypeMember *> GlobalTypeMembers;
2811 for (GlobalObject &GO : M.global_objects()) {
2813 continue;
2814
2815 Types.clear();
2816 GO.getMetadata(LLVMContext::MD_type, Types);
2817
2818 bool IsJumpTableCanonical = false;
2819 bool IsExported = false;
2820 if (Function *F = dyn_cast<Function>(&GO)) {
2821 IsJumpTableCanonical = isJumpTableCanonical(F);
2822 if (auto It = ExportedFunctions.find(F->getName());
2823 It != ExportedFunctions.end()) {
2824 IsJumpTableCanonical |=
2825 It->second.Linkage == CfiFunctionLinkage::Definition;
2826 IsExported = true;
2827 // TODO: The logic here checks only that the function is address taken,
2828 // not that the address takers are live. This can be updated to check
2829 // their liveness and emit fewer jumptable entries once monolithic LTO
2830 // builds also emit summaries.
2831 } else if (!F->hasAddressTaken()) {
2832 if (!CrossDsoCfi || !IsJumpTableCanonical || F->hasLocalLinkage())
2833 continue;
2834 }
2835
2836 // TODO: Pre-fill for full LTO.
2837 // if (!ExportSummary)
2838 // FunctionSummaryHotness[F] = getHotness(*F, PSI, BFIGetter);
2839 }
2840
2841 auto *GTM = GlobalTypeMember::create(Alloc, &GO, IsJumpTableCanonical,
2842 IsExported, Types);
2843 GlobalTypeMembers[&GO] = GTM;
2844 for (MDNode *Type : Types) {
2845 verifyTypeMDNode(&GO, Type);
2846 auto &Info = TypeIdInfo[Type->getOperand(1)];
2847 Info.UniqueId = ++CurUniqueId;
2848 Info.RefGlobals.push_back(GTM);
2849 }
2850 }
2851
2852 auto AddTypeIdUse = [&](Metadata *TypeId) -> TypeIdUserInfo & {
2853 // Add the call site to the list of call sites for this type identifier. We
2854 // also use TypeIdUsers to keep track of whether we have seen this type
2855 // identifier before. If we have, we don't need to re-add the referenced
2856 // globals to the equivalence class.
2857 auto Ins = TypeIdUsers.insert({TypeId, {}});
2858 if (Ins.second) {
2859 // Add the type identifier to the equivalence class.
2860 auto &GCI = GlobalClasses.insert(TypeId);
2861 GlobalClassesTy::member_iterator CurSet = GlobalClasses.findLeader(GCI);
2862
2863 // Add the referenced globals to the type identifier's equivalence class.
2864 for (GlobalTypeMember *GTM : TypeIdInfo[TypeId].RefGlobals)
2865 CurSet = GlobalClasses.unionSets(
2866 CurSet, GlobalClasses.findLeader(GlobalClasses.insert(GTM)));
2867 }
2868
2869 return Ins.first->second;
2870 };
2871
2872 if (TypeTestFunc) {
2873 for (const Use &U : TypeTestFunc->uses()) {
2874 auto CI = cast<CallInst>(U.getUser());
2875 // If this type test is only used by llvm.assume instructions, it
2876 // was used for whole program devirtualization, and is being kept
2877 // for use by other optimization passes. We do not need or want to
2878 // lower it here. We also don't want to rewrite any associated globals
2879 // unnecessarily. These will be removed by a subsequent LTT invocation
2880 // with the DropTypeTests flag set.
2881 bool OnlyAssumeUses = !CI->use_empty();
2882 for (Instruction *CIU : CI->users()) {
2883 if (isa<AssumeInst>(CIU))
2884 continue;
2885 OnlyAssumeUses = false;
2886 break;
2887 }
2888 if (OnlyAssumeUses)
2889 continue;
2890
2891 auto TypeIdMDVal = dyn_cast<MetadataAsValue>(CI->getArgOperand(1));
2892 if (!TypeIdMDVal)
2893 report_fatal_error("Second argument of llvm.type.test must be metadata");
2894 auto TypeId = TypeIdMDVal->getMetadata();
2895 AddTypeIdUse(TypeId).CallSites.push_back(CI);
2896 }
2897 }
2898
2899 if (ICallBranchFunnelFunc) {
2900 for (const Use &U : ICallBranchFunnelFunc->uses()) {
2901 if (Arch != Triple::x86_64)
2903 "llvm.icall.branch.funnel not supported on this target");
2904
2905 auto CI = cast<CallInst>(U.getUser());
2906
2907 std::vector<GlobalTypeMember *> Targets;
2908 if (CI->arg_size() % 2 != 1)
2909 report_fatal_error("number of arguments should be odd");
2910
2911 GlobalClassesTy::member_iterator CurSet;
2912 for (unsigned I = 1; I != CI->arg_size(); I += 2) {
2913 int64_t Offset;
2915 CI->getOperand(I), Offset, M.getDataLayout()));
2916 if (!Base)
2918 "Expected branch funnel operand to be global value");
2919
2920 auto It = GlobalTypeMembers.find(Base);
2921 if (It == GlobalTypeMembers.end())
2922 reportFatalUsageError("Expected branch funnel operand to be a "
2923 "defined global value with type metadata");
2924 GlobalTypeMember *GTM = It->second;
2925 Targets.push_back(GTM);
2926 GlobalClassesTy::member_iterator NewSet =
2927 GlobalClasses.findLeader(GlobalClasses.insert(GTM));
2928 if (I == 1)
2929 CurSet = NewSet;
2930 else
2931 CurSet = GlobalClasses.unionSets(CurSet, NewSet);
2932 }
2933
2934 GlobalClasses.unionSets(
2935 CurSet, GlobalClasses.findLeader(
2936 GlobalClasses.insert(ICallBranchFunnel::create(
2937 Alloc, CI, Targets, ++CurUniqueId))));
2938 }
2939 }
2940
2941 if (ExportSummary) {
2942 DenseMap<GlobalValue::GUID, TinyPtrVector<Metadata *>> MetadataByGUID;
2943 for (auto &P : TypeIdInfo) {
2944 if (auto *TypeId = dyn_cast<MDString>(P.first))
2946 TypeId->getString())]
2947 .push_back(TypeId);
2948 }
2949
2950 for (auto &P : *ExportSummary) {
2951 for (auto &S : P.second.getSummaryList()) {
2952 if (!ExportSummary->isGlobalValueLive(S.get()))
2953 continue;
2954 if (auto *FS = dyn_cast<FunctionSummary>(S->getBaseObject()))
2955 for (GlobalValue::GUID G : FS->type_tests())
2956 for (Metadata *MD : MetadataByGUID[G])
2957 AddTypeIdUse(MD).IsExported = true;
2958 }
2959 }
2960 }
2961
2962 if (GlobalClasses.empty())
2963 return false;
2964
2965 {
2966 ScopedSaveAliaseesAndUsed S(M);
2967 // For each disjoint set we found...
2968 for (const auto &C : GlobalClasses) {
2969 if (!C->isLeader())
2970 continue;
2971
2972 ++NumTypeIdDisjointSets;
2973 // Build the list of type identifiers in this disjoint set.
2974 std::vector<Metadata *> TypeIds;
2975 std::vector<GlobalTypeMember *> Globals;
2976 std::vector<ICallBranchFunnel *> ICallBranchFunnels;
2977 for (auto M : GlobalClasses.members(*C)) {
2978 if (isa<Metadata *>(M))
2979 TypeIds.push_back(cast<Metadata *>(M));
2980 else if (isa<GlobalTypeMember *>(M))
2981 Globals.push_back(cast<GlobalTypeMember *>(M));
2982 else
2983 ICallBranchFunnels.push_back(cast<ICallBranchFunnel *>(M));
2984 }
2985
2986 // Order type identifiers by unique ID for determinism. This ordering is
2987 // stable as there is a one-to-one mapping between metadata and unique
2988 // IDs.
2989 llvm::sort(TypeIds, [&](Metadata *M1, Metadata *M2) {
2990 return TypeIdInfo[M1].UniqueId < TypeIdInfo[M2].UniqueId;
2991 });
2992
2993 // Same for the branch funnels.
2994 llvm::sort(ICallBranchFunnels,
2995 [&](ICallBranchFunnel *F1, ICallBranchFunnel *F2) {
2996 return F1->UniqueId < F2->UniqueId;
2997 });
2998
2999 // Build bitsets for this disjoint set.
3000 buildBitSetsFromDisjointSet(TypeIds, Globals, ICallBranchFunnels);
3001 }
3002 }
3003
3004 allocateByteArrays();
3005
3006 for (auto A : AliasesToCreate) {
3007 auto *Target = M.getNamedValue(A.TargetName);
3008 if (!isa<GlobalAlias>(Target))
3009 continue;
3010 auto *AliasGA = GlobalAlias::create("", Target);
3011 AliasGA->setVisibility(A.Alias->getVisibility());
3012 AliasGA->setLinkage(A.Alias->getLinkage());
3013 AliasGA->setDSOLocal(A.Alias->isDSOLocal());
3014 AliasGA->takeName(A.Alias);
3015 A.Alias->replaceAllUsesWith(AliasGA);
3016 A.Alias->eraseFromParent();
3017 }
3018
3019 // Emit .symver directives for exported functions, if they exist.
3020 if (ExportSummary) {
3021 if (NamedMDNode *SymversMD = M.getNamedMetadata("symvers")) {
3022 for (auto *Symver : SymversMD->operands()) {
3023 assert(Symver->getNumOperands() >= 2);
3024 StringRef SymbolName =
3025 cast<MDString>(Symver->getOperand(0))->getString();
3026 StringRef Alias = cast<MDString>(Symver->getOperand(1))->getString();
3027
3028 if (!ExportedFunctions.count(SymbolName))
3029 continue;
3030
3031 M.appendModuleInlineAsm(
3032 (llvm::Twine(".symver ") + SymbolName + ", " + Alias).str());
3033 }
3034 }
3035 }
3036
3037 return true;
3038}
3039
3042 bool Changed;
3043 if (UseCommandLine)
3044 Changed = LowerTypeTestsModule::runForTesting(M, AM);
3045 else
3046 Changed = LowerTypeTestsModule(M, AM, ExportSummary, ImportSummary).lower();
3047 if (!Changed)
3048 return PreservedAnalyses::all();
3049 return PreservedAnalyses::none();
3050}
3051
3053 raw_ostream &OS, function_ref<StringRef(StringRef)> MapClassName2PassName) {
3054 static_cast<PassInfoMixin<DropTypeTestsPass> *>(this)->printPipeline(
3055 OS, MapClassName2PassName);
3056 OS << '<';
3057 switch (Kind) {
3058 case DropTestKind::Assume:
3059 OS << "assume";
3060 break;
3061 case DropTestKind::All:
3062 OS << "all";
3063 break;
3064 }
3065 OS << '>';
3066}
3067
3069 bool ShouldDropAll = Kind == DropTestKind::All;
3072 // Dropping all type tests erases the checked load declarations. Since the
3073 // proxy is preserved, their analyses need to be cleared before they are
3074 // deleted.
3075 if (ShouldDropAll) {
3076 for (Intrinsic::ID ID : {Intrinsic::type_checked_load,
3077 Intrinsic::type_checked_load_relative}) {
3079 FAM.clear(*F, F->getName());
3080 }
3081 }
3082
3083 SmallSetVector<Function *, 8> ModifiedFunctions;
3084 if (!dropTypeTests(M, ShouldDropAll, ModifiedFunctions))
3085 return PreservedAnalyses::all();
3086
3087 PreservedAnalyses FuncPA;
3088 FuncPA.preserveSet<CFGAnalyses>();
3089 for (Function *F : ModifiedFunctions)
3090 FAM.invalidate(*F, FuncPA);
3091
3095 return PA;
3096}
3097
3100 bool Changed = false;
3101 bool ReplacedConstant = false;
3102 SmallSetVector<Function *, 8> ModifiedFunctions;
3103 // Figure out whether inlining has exposed a constant address to a lowered
3104 // type test, and remove the test if so and the address is known to pass the
3105 // test. Unfortunately this pass ends up needing to reverse engineer what
3106 // LowerTypeTests did; this is currently inherent to the design of ThinLTO
3107 // importing where LowerTypeTests needs to run at the start.
3108 //
3109 // We look for things like:
3110 //
3111 // sub (i64 ptrtoint (ptr @_Z2fpv to i64), i64 ptrtoint (ptr
3112 // @__typeid__ZTSFvvE_global_addr to i64))
3113 //
3114 // which gets replaced with 0 if _Z2fpv (more specifically _Z2fpv.cfi, the
3115 // function referred to by the jump table) is a member of the type _ZTSFvv, as
3116 // well as things like
3117 //
3118 // icmp eq ptr @_Z2fpv, @__typeid__ZTSFvvE_global_addr
3119 //
3120 // which gets replaced with true if _Z2fpv is a member.
3121 for (auto &GV : M.globals()) {
3122 if (!GV.getName().starts_with("__typeid_") ||
3123 !GV.getName().ends_with("_global_addr"))
3124 continue;
3125 // __typeid_foo_global_addr -> foo
3126 auto *MD = MDString::get(M.getContext(),
3127 GV.getName().substr(9, GV.getName().size() - 21));
3128 auto MaySimplifyPtr = [&](Value *Ptr) {
3129 if (auto *GV = dyn_cast<GlobalValue>(Ptr))
3130 if (auto *CFIGV = M.getNamedValue((GV->getName() + ".cfi").str()))
3131 Ptr = CFIGV;
3132 return isKnownTypeIdMember(MD, M.getDataLayout(), Ptr, 0);
3133 };
3134 auto MaySimplifyInt = [&](Value *Op) {
3135 auto *PtrAsInt = dyn_cast<ConstantExpr>(Op);
3136 if (!PtrAsInt || PtrAsInt->getOpcode() != Instruction::PtrToInt)
3137 return false;
3138 return MaySimplifyPtr(PtrAsInt->getOperand(0));
3139 };
3140 for (User *U : make_early_inc_range(GV.users())) {
3141 if (auto *CI = dyn_cast<ICmpInst>(U)) {
3142 if (CI->getPredicate() == CmpInst::ICMP_EQ &&
3143 MaySimplifyPtr(CI->getOperand(0))) {
3144 // This is an equality comparison (TypeTestResolution::Single case in
3145 // lowerTypeTestCall). In this case we just replace the comparison
3146 // with true.
3147 ModifiedFunctions.insert(CI->getFunction());
3148 CI->replaceAllUsesWith(ConstantInt::getTrue(M.getContext()));
3149 CI->eraseFromParent();
3150 Changed = true;
3151 continue;
3152 }
3153 }
3154 auto *CE = dyn_cast<ConstantExpr>(U);
3155 if (!CE || CE->getOpcode() != Instruction::PtrToInt)
3156 continue;
3157 for (Use &U : make_early_inc_range(CE->uses())) {
3158 auto *CE = dyn_cast<ConstantExpr>(U.getUser());
3159 if (U.getOperandNo() == 0 && CE &&
3160 CE->getOpcode() == Instruction::Sub &&
3161 MaySimplifyInt(CE->getOperand(1))) {
3162 // This is a computation of PtrOffset as generated by
3163 // LowerTypeTestsModule::lowerTypeTestCall above. If
3164 // isKnownTypeIdMember passes we just pretend it evaluated to 0. This
3165 // should cause later passes to remove the range and alignment checks.
3166 // The bitset checks won't be removed but those are uncommon.
3167 CE->replaceAllUsesWith(ConstantInt::get(CE->getType(), 0));
3168 ReplacedConstant = true;
3169 Changed = true;
3170 }
3171 auto *CI = dyn_cast<ICmpInst>(U.getUser());
3172 if (U.getOperandNo() == 1 && CI &&
3173 CI->getPredicate() == CmpInst::ICMP_EQ &&
3174 MaySimplifyInt(CI->getOperand(0))) {
3175 // This is an equality comparison. Unlike in the case above it
3176 // remained as an integer compare.
3177 ModifiedFunctions.insert(CI->getFunction());
3178 CI->replaceAllUsesWith(ConstantInt::getTrue(M.getContext()));
3179 CI->eraseFromParent();
3180 Changed = true;
3181 }
3182 }
3183 }
3184 }
3185
3186 if (!Changed)
3187 return PreservedAnalyses::all();
3188
3191 PreservedAnalyses FuncPA;
3192 FuncPA.preserveSet<CFGAnalyses>();
3193 for (Function *F : ModifiedFunctions)
3194 FAM.invalidate(*F, FuncPA);
3195
3198 // Replacing a constant may affect any function using it, but not its CFG.
3199 if (ReplacedConstant)
3201 else
3203 return PA;
3204}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
const AArch64InstrInfo MachineBasicBlock::iterator InsertPt
uint64_t uint64_t
AMDGPU Register Bank Select
This file implements a class to represent arbitrary precision integral constant values and operations...
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
This file defines the BumpPtrAllocator interface.
This file contains the simple types necessary to represent the attributes associated with functions a...
bpf unwind lower
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
DXIL Finalize Linkage
dxil translate DXIL Translate Metadata
This file defines the DenseMap class.
Generic implementation of equivalence classes through the use Tarjan's efficient union-find algorithm...
This file provides a collection of function (or more generally, callable) type erasure utilities supp...
#define DEBUG_TYPE
Hexagon Common GEP
Module.h This file contains the declarations for the Module class.
This header defines various interfaces for pass management in LLVM.
This defines the Use class.
static const unsigned kARMJumpTableEntrySize
static const unsigned kLOONGARCH64JumpTableEntrySize
static bool isKnownTypeIdMember(Metadata *TypeId, const DataLayout &DL, Value *V, uint64_t COffset)
static const unsigned kX86IBTJumpTableEntrySize
static ConstantInt * extractNumericTypeId(MDNode &MD)
Extracts a numeric type identifier from an MDNode containing type metadata.
static const unsigned kRISCVJumpTableEntrySize
static auto buildBitSets(ArrayRef< Metadata * > TypeIds, const DenseMap< GlobalTypeMember *, uint64_t > &GlobalLayout)
static Value * createMaskedBitTest(IRBuilder<> &B, Value *Bits, Value *BitOffset)
Build a test that bit BitOffset mod sizeof(Bits)*8 is set in Bits.
static bool isThumbFunction(Function *F, Triple::ArchType ModuleArch)
static const unsigned kX86JumpTableEntrySize
static void createCfiSymversMetadata(Module &DestM, const Module &SrcM)
static void dropTypeTests(Module &M, Function &TypeTestFunc, bool ShouldDropAll, SmallSetVector< Function *, 8 > &ModifiedFunctions)
static const unsigned kARMBTIJumpTableEntrySize
static CfiFunctionLinkage decodeCfiFunctionLinkage(uint8_t Encoded)
static void createCfiFunctionsMetadata(Module &DestM, ArrayRef< GlobalValue * > CfiFunctions, ProfileSummaryInfo &PSI, function_ref< const BlockFrequencyInfo &(Function &)> BFIGetter)
static BitSetInfo buildBitSet(ArrayRef< uint64_t > Offsets)
Build a bit set for list of offsets.
static const unsigned kARMv6MJumpTableEntrySize
static uint8_t encodeCfiFunctionLinkage(CfiFunctionLinkage Linkage, CfiFunctionHotness Hotness)
static CfiFunctionHotness decodeCfiFunctionHotness(uint8_t Encoded)
static const unsigned kHexagonJumpTableEntrySize
static void createCfiAliasesMetadata(Module &DestM, const Module &SrcM)
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
#define G(x, y, z)
Definition MD5.cpp:55
Machine Check Debug Module
This file implements a map that provides insertion order iteration.
This file contains the declarations for metadata subclasses.
#define T
ModuleSummaryIndex.h This file contains the declarations the classes that hold the module index and s...
#define P(N)
FunctionAnalysisManager FAM
This file defines the PointerUnion class, which is a discriminated union of pointer types.
This file contains the declarations for profiling metadata utility functions.
static StringRef getName(Value *V)
This file contains some templates that are useful if you are working with the STL at all.
This file implements a set that has insertion order iteration characteristics.
This file defines the SmallVector class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:170
#define LLVM_DEBUG(...)
Definition Debug.h:119
This pass exposes codegen information to IR-level passes.
This header defines support for implementing classes that have some trailing object (or arrays of obj...
static bool isDirectCall(const MCInst &Inst)
Class for arbitrary precision integers.
Definition APInt.h:78
uint64_t getZExtValue() const
Get zero extended value.
Definition APInt.h:1560
This templated class represents "all analyses that operate over <aparticular IR unit>" (e....
Definition Analysis.h:50
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
size_t size() const
Get the array size.
Definition ArrayRef.h:141
bool empty() const
Check if the array is empty.
Definition ArrayRef.h:136
static LLVM_ABI ArrayType * get(Type *ElementType, uint64_t NumElements)
This static method is the primary way to construct an ArrayType.
Functions, function parameters, and return types can have attributes to indicate how they should be t...
Definition Attributes.h:106
LLVM_ABI StringRef getValueAsString() const
Return the attribute's value as a string.
bool isValid() const
Return true if the attribute is any kind of attribute.
Definition Attributes.h:260
LLVM_ABI BasicBlock * splitBasicBlock(iterator I, const Twine &BBName="")
Split the basic block into two basic blocks at the specified instruction.
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
Definition BasicBlock.h:205
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Definition BasicBlock.h:236
BlockFrequencyInfo pass uses BlockFrequencyInfoImpl implementation to estimate IR basic block frequen...
Represents analyses that only rely on functions' control flow.
Definition Analysis.h:73
Value * getArgOperand(unsigned i) const
unsigned arg_size() const
void addSymbolWithThinLTOGUID(StringRef Name, GlobalValue::GUID GUID)
Add the function name and the GUID that ThinLTO uses for it.
bool contains(StringRef Name) const
@ ICMP_NE
not equal
Definition InstrTypes.h:762
static CondBrInst * Create(Value *Cond, BasicBlock *IfTrue, BasicBlock *IfFalse, InsertPosition InsertBefore=nullptr)
static LLVM_ABI ConstantAggregateZero * get(Type *Ty)
ConstantArray - Constant Array Declarations.
Definition Constants.h:590
static ConstantAsMetadata * get(Constant *C)
Definition Metadata.h:549
static Constant * get(LLVMContext &Context, ArrayRef< ElementTy > Elts)
get() constructor - Return a constant with array type with an element count and element type matching...
Definition Constants.h:878
static LLVM_ABI Constant * getIntToPtr(Constant *C, Type *Ty, bool OnlyIfReduced=false)
static LLVM_ABI Constant * getPointerCast(Constant *C, Type *Ty)
Create a BitCast, AddrSpaceCast, or a PtrToInt cast constant expression.
static LLVM_SUPPRESS_DEPRECATED_DECLARATIONS_POP Constant * getInBoundsPtrAdd(Constant *Ptr, Constant *Offset)
Create a getelementptr inbounds i8, ptr, offset constant expression.
Definition Constants.h:1550
static Constant * getPtrAdd(Constant *Ptr, Constant *Offset, GEPNoWrapFlags NW=GEPNoWrapFlags::none(), std::optional< ConstantRange > InRange=std::nullopt, Type *OnlyIfReduced=nullptr)
Create a getelementptr i8, ptr, offset constant expression.
Definition Constants.h:1518
static LLVM_ABI Constant * getPtrToInt(Constant *C, Type *Ty, bool OnlyIfReduced=false)
static LLVM_SUPPRESS_DEPRECATED_DECLARATIONS_PUSH Constant * getGetElementPtr(Type *Ty, Constant *C, ArrayRef< Constant * > IdxList, GEPNoWrapFlags NW=GEPNoWrapFlags::none(), std::optional< ConstantRange > InRange=std::nullopt, Type *OnlyIfReducedTy=nullptr)
Getelementptr form.
Definition Constants.h:1477
This is the shared class of boolean and integer constants.
Definition Constants.h:87
static LLVM_ABI ConstantInt * getTrue(LLVMContext &Context)
static LLVM_ABI ConstantInt * getFalse(LLVMContext &Context)
static LLVM_ABI ConstantPointerNull * get(PointerType *T)
Static factory methods - Return objects of the specified value.
static Constant * getAnon(ArrayRef< Constant * > V, bool Packed=false)
Return an anonymous struct that has the specified elements.
Definition Constants.h:643
static LLVM_ABI Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:63
bool empty() const
Definition DenseMap.h:716
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:766
iterator end()
Definition DenseMap.h:686
ValueT lookup(const_arg_type_t< KeyT > Val) const
Return the entry for the specified key, or a default constructed value if no such entry exists.
Definition DenseMap.h:793
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition DenseMap.h:827
LLVM_ABI PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM)
LLVM_ABI void printPipeline(raw_ostream &OS, function_ref< StringRef(StringRef)> MapClassName2PassName)
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:169
const BasicBlock & getEntryBlock() const
Definition Function.h:803
void eraseFromParent()
eraseFromParent - This method unlinks 'this' from the containing module and deletes it.
Definition Function.cpp:451
static GEPNoWrapFlags inBounds()
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:695
LLVM_ABI void setMetadata(unsigned KindID, MDNode *Node)
Set a particular kind of metadata attachment.
bool hasMetadata() const
Return true if this GlobalObject has any metadata attached to it.
LLVM_ABI void setComdat(Comdat *C)
Definition Globals.cpp:287
LLVM_ABI void setSection(StringRef S)
Change the section for this global.
Definition Globals.cpp:348
const Comdat * getComdat() const
LLVM_ABI bool eraseMetadata(unsigned KindID)
Erase all metadata attachments with the given kind.
MDNode * getMetadata(unsigned KindID) const
Get the metadata of given kind attached to this GlobalObject.
bool hasSection() const
Check if this global has a custom object file section.
static LLVM_ABI GUID getGUIDAssumingExternalLinkage(StringRef GlobalName)
Return a 64-bit global unique ID constructed from the name of a global symbol.
Definition Globals.cpp:80
bool isDSOLocal() const
bool isThreadLocal() const
If the value is "Thread Local", its value isn't shared by the threads.
VisibilityTypes getVisibility() const
static bool isLocalLinkage(LinkageTypes Linkage)
LinkageTypes getLinkage() const
uint64_t GUID
Declare a type to represent a global unique identifier for a global value.
bool isDeclarationForLinker() const
void setDSOLocal(bool Local)
PointerType * getType() const
Global values are always pointers.
VisibilityTypes
An enumeration for the kinds of visibility of global values.
Definition GlobalValue.h:67
@ HiddenVisibility
The GV is hidden.
Definition GlobalValue.h:69
void setVisibility(VisibilityTypes V)
LinkageTypes
An enumeration for the kinds of linkage for global values.
Definition GlobalValue.h:52
@ PrivateLinkage
Like Internal, but omit from symbol table.
Definition GlobalValue.h:61
@ InternalLinkage
Rename collisions when linking (static functions).
Definition GlobalValue.h:60
@ ExternalLinkage
Externally visible function.
Definition GlobalValue.h:53
@ ExternalWeakLinkage
ExternalWeak linkage description.
Definition GlobalValue.h:62
Type * getValueType() const
const Constant * getInitializer() const
getInitializer - Return the initializer for this global variable.
LLVM_ABI void setInitializer(Constant *InitVal)
setInitializer - Sets the initializer for this global variable, removing any existing initializer if ...
Definition Globals.cpp:613
bool hasInitializer() const
Definitions have initializers, declarations don't.
MaybeAlign getAlign() const
Returns the alignment of the given variable.
void setConstant(bool Val)
LLVM_ABI void setCodeModel(CodeModel::Model CM)
Change the code model for this global.
Definition Globals.cpp:663
LLVM_ABI void eraseFromParent()
eraseFromParent - This method unlinks 'this' from the containing module and deletes it.
Definition Globals.cpp:609
LLVM_ABI CallInst * CreateIntrinsicWithoutFolding(Intrinsic::ID ID, ArrayRef< Type * > OverloadTypes, ArrayRef< Value * > Args, FMFSource FMFSource={}, const Twine &Name="", ArrayRef< OperandBundleDef > OpBundles={})
Create a call to intrinsic ID with Args, mangled using OverloadTypes.
Value * CreateInsertValue(Value *Agg, Value *Val, ArrayRef< unsigned > Idxs, const Twine &Name="")
Definition IRBuilder.h:2802
Value * CreatePtrAddWithSExtOrTrunc(Value *Ptr, Value *Offset, const Twine &Name="", GEPNoWrapFlags NW=GEPNoWrapFlags::none())
Create a ptradd where the offset is sign-extended or truncated to the index type.
Definition IRBuilder.h:2133
LoadInst * CreateLoad(Type *Ty, Value *Ptr, const char *Name)
Provided to resolve 'CreateLoad(Ty, Ptr, "...")' correctly, instead of converting the string to 'bool...
Definition IRBuilder.h:1913
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition IRBuilder.h:2990
static LLVM_ABI InlineAsm * get(FunctionType *Ty, StringRef AsmString, StringRef Constraints, bool hasSideEffects, bool isAlignStack=false, AsmDialect asmDialect=AD_ATT, bool canThrow=false)
InlineAsm::get - Return the specified uniqued inline asm string.
Definition InlineAsm.cpp:43
LLVM_ABI InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
LLVM_ABI const Function * getFunction() const
Return the function this instruction belongs to.
iterator_range< user_iterator > users()
LLVM_ABI void setMetadata(unsigned KindID, MDNode *Node)
Set the metadata of the specified kind to the specified node.
user_iterator user_begin()
LLVM_ABI PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM)
Metadata node.
Definition Metadata.h:1087
const MDOperand & getOperand(unsigned I) const
Definition Metadata.h:1443
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1588
unsigned getNumOperands() const
Return number of MDNode operands.
Definition Metadata.h:1449
Metadata * get() const
Definition Metadata.h:937
static LLVM_ABI MDString * get(LLVMContext &Context, StringRef Str)
Definition Metadata.cpp:595
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1534
This class implements a map that also provides access to all stored values in a deterministic order.
Definition MapVector.h:39
bool empty() const
Definition MapVector.h:80
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition MapVector.h:127
static ErrorOr< std::unique_ptr< MemoryBuffer > > getFile(const Twine &Filename, bool IsText=false, bool RequiresNullTerminator=true, bool IsVolatile=false, std::optional< Align > Alignment=std::nullopt)
Open the specified file as a MemoryBuffer, returning a new MemoryBuffer if successful,...
Root of the metadata hierarchy.
Definition Metadata.h:65
TypeIdSummary & getOrInsertTypeIdSummary(StringRef TypeId)
Return an existing or new TypeIdSummary entry for TypeId.
const TypeIdSummary * getTypeIdSummary(StringRef TypeId) const
This returns either a pointer to the type id summary (if present in the summary map) or null (if not ...
CfiFunctionIndex & cfiFunctionDecls()
CfiFunctionIndex & cfiFunctionDefs()
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:68
LLVMContext & getContext() const
Get the global data context.
Definition Module.h:332
Function * getFunction(StringRef Name) const
Look up the specified function in the module symbol table.
Definition Module.cpp:254
iterator_range< alias_iterator > aliases()
Definition Module.h:861
NamedMDNode * getOrInsertNamedMetadata(StringRef Name)
Return the named MDNode in the module with the specified name.
Definition Module.cpp:327
A tuple of MDNodes.
Definition Metadata.h:1806
iterator_range< op_iterator > operands()
Definition Metadata.h:1902
LLVM_ABI void addOperand(MDNode *M)
static PointerType * getUnqual(LLVMContext &C)
This constructs an opaque pointer to an object in the default address space (address space zero).
unsigned getAddressSpace() const
Return the address space of the Pointer type.
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
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
PreservedAnalyses & preserveSet()
Mark an analysis set as preserved.
Definition Analysis.h:151
PreservedAnalyses & preserve()
Mark an analysis as preserved.
Definition Analysis.h:132
Analysis providing profile information.
bool isFunctionColdInCallGraph(const FuncT *F, BFIT &BFI) const
Returns true if F contains only cold code.
LLVM_ABI bool isFunctionHotnessUnknown(const Function &F) const
Returns true if the hotness of F is unknown.
bool isFunctionHotInCallGraph(const FuncT *F, BFIT &BFI) const
Returns true if F contains hot code.
LLVM_ABI bool hasPartialSampleProfile() const
Returns true if module M has partial-profile sample profile.
static ReturnInst * Create(LLVMContext &C, Value *retVal=nullptr, InsertPosition InsertBefore=nullptr)
LLVM_ABI void print(const char *ProgName, raw_ostream &S, bool ShowColors=true, bool ShowKindLabel=true, bool ShowLocation=true) const
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
LLVM_ABI PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM)
A SetVector that performs no allocations if smaller than a certain size.
Definition SetVector.h:346
reference emplace_back(ArgTypes &&... Args)
void reserve(size_type N)
iterator erase(const_iterator CI)
void resize(size_type N)
void push_back(const T &Elt)
LLVM_NO_SANITIZE_CFI_UNRELATED_CAST iterator begin()
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
std::pair< StringRef, StringRef > split(char Separator) const
Split into two substrings around the first occurrence of a separator character.
Definition StringRef.h:728
bool consume_back(StringRef Suffix)
Returns true if this StringRef has the given suffix and removes that suffix.
Definition StringRef.h:683
std::string str() const
Get the contents as an std::string.
Definition StringRef.h:222
constexpr StringRef substr(size_t Start, size_t N=npos) const
Return a reference to the substring from [Start, Start + N).
Definition StringRef.h:589
bool starts_with(StringRef Prefix) const
Check if this string starts with the given Prefix.
Definition StringRef.h:258
constexpr bool empty() const
Check if the string is empty.
Definition StringRef.h:141
constexpr size_t size() const
Get the string size.
Definition StringRef.h:144
bool ends_with(StringRef Suffix) const
Check if this string ends with the given Suffix.
Definition StringRef.h:270
Type * getElementType(unsigned N) const
Analysis pass providing the TargetTransformInfo.
See the file comment for details on the usage of the TrailingObjects type.
Triple - Helper class for working with autoconf configuration names.
Definition Triple.h:48
@ loongarch64
Definition Triple.h:66
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
static LLVM_ABI IntegerType * getInt64Ty(LLVMContext &C)
Definition Type.cpp:295
static LLVM_ABI Type * getVoidTy(LLVMContext &C)
Definition Type.cpp:267
static LLVM_ABI IntegerType * getInt8Ty(LLVMContext &C)
Definition Type.cpp:292
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
op_range operands()
Definition User.h:267
Value * getOperand(unsigned i) const
Definition User.h:207
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
bool hasOneUse() const
Return true if there is exactly one use of this value.
Definition Value.h:441
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition Value.cpp:548
iterator_range< user_iterator > users()
Definition Value.h:428
use_iterator use_begin()
Definition Value.h:366
bool use_empty() const
Definition Value.h:348
LLVM_ABI bool replaceUsesWithIf(Value *New, llvm::function_ref< bool(Use &U)> ShouldReplace)
Go through the uses list for this definition and make each use point to "V" if the callback ShouldRep...
Definition Value.cpp:556
iterator_range< use_iterator > uses()
Definition Value.h:382
bool hasName() const
Definition Value.h:263
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:314
LLVM_ABI void takeName(Value *V)
Transfer the name from V to this value.
Definition Value.cpp:395
std::pair< iterator, bool > insert(const ValueT &V)
Definition DenseSet.h:210
bool contains(const_arg_type_t< ValueT > V) const
Check if the set contains the given element.
Definition DenseSet.h:183
void insert_range(Range &&R)
Definition DenseSet.h:236
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:188
An efficient, type-erasing, non-owning reference to a callable.
const ParentTy * getParent() const
Definition ilist_node.h:34
self_iterator getIterator()
Definition ilist_node.h:123
NodeTy * getNextNode()
Get the next node, or nullptr for the list tail.
Definition ilist_node.h:348
This class implements a layout algorithm for globals referenced by bit sets that tries to keep member...
LLVM_ABI const std::vector< uint64_t > & build()
Flatten fragments into a single layout and return it.
LLVM_ABI void addFragment(const std::set< uint64_t > &F)
Add F to the layout while trying to keep its indices contiguous.
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
CallInst * Call
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
constexpr char SymbolName[]
Key for Kernel::Metadata::mSymbolName.
constexpr std::underlying_type_t< E > Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:83
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 SetVector< uint64_t > findCfiTypeIds(const Module &M)
Finds all 64-bit numeric type identifiers in M used for cross-DSO CFI.
LLVM_ABI void createCfiMetadata(Module &DestM, const Module &SrcM, ArrayRef< GlobalValue * > CfiFunctions, ProfileSummaryInfo &PSI, function_ref< const BlockFrequencyInfo &(Function &)> BFIGetter)
Creates cfi.functions, aliases, and symvers named metadata in DestM for CFI functions in CfiFunctions...
LLVM_ABI bool isJumpTableCanonical(Function *F)
LLVM_ABI bool cleanUpTypeCheckedLoad(Module &M, Function &CheckedLoadFn, bool IsRelative, SmallSetVector< Function *, 8 > *ModifiedFunctions=nullptr)
Lower @llvm.type.checked.load[.relative] calls to the guarded load with the check assumed true,...
LLVM_ABI bool hasTypeMetadata(const GlobalObject &GO)
Returns whether a global or its associated global has attached type metadata.
LLVM_ABI SetVector< GlobalValue * > findCfiFunctions(Module &M)
Finds all functions and aliases in M that may need CFI jump table entries.
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:695
SmallVector< unsigned char, 0 > ByteArray
Definition PropertySet.h:25
NodeAddr< PhiNode * > Phi
Definition RDFGraph.h:390
NodeAddr< UseNode * > Use
Definition RDFGraph.h:385
NodeAddr< FuncNode * > Func
Definition RDFGraph.h:393
@ OF_TextWithCRLF
The file should be opened in text mode and use a carriage linefeed '\r '.
Definition FileSystem.h:802
This is an optimization pass for GlobalISel generic memory operations.
LLVM_ABI void ReplaceInstWithInst(BasicBlock *BB, BasicBlock::iterator &BI, Instruction *I)
Replace the instruction specified by BI with the instruction specified by I.
@ Offset
Definition DWP.cpp:577
bool operator<(int64_t V1, const APSInt &V2)
Definition APSInt.h:360
void stable_sort(R &&Range)
Definition STLExtras.h:2132
LLVM_ABI cl::opt< bool > ProfcheckDisableMetadataFixes
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1755
detail::zip_longest_range< T, U, Args... > zip_longest(T &&t, U &&u, Args &&... args)
Iterate over two or more iterators at the same time.
Definition STLExtras.h:997
@ Unknown
Not known to have no common set bits.
LLVM_ABI void setExplicitlyUnknownBranchWeightsIfProfiled(Instruction &I, StringRef PassName, const Function *F=nullptr)
Like setExplicitlyUnknownBranchWeights(...), but only sets unknown branch weights in the new instruct...
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
@ Load
The value being inserted comes from a load (InsertElement only).
PassSummaryAction
What to do with the summary when running passes that operate on it.
Definition IPO.h:35
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition STLExtras.h:2229
Value * GetPointerBaseWithConstantOffset(Value *Ptr, int64_t &Offset, const DataLayout &DL, bool AllowNonInbounds=true)
Analyze the specified pointer to see if it can be expressed as a base pointer plus a constant offset.
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:649
InnerAnalysisManagerProxy< FunctionAnalysisManager, Module > FunctionAnalysisManagerModuleProxy
Provide the FunctionAnalysisManager to Module proxy.
@ O1
Optimize quickly without destroying debuggability.
@ O2
Optimize for fast execution as much as possible without triggering significant incremental compile ti...
bool operator==(const AddressRangeValuePair &LHS, const AddressRangeValuePair &RHS)
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
int countr_zero(T Val)
Count number of 0's from the least significant bit to the most stopping at the first 1.
Definition bit.h:204
unsigned M1(unsigned Val)
Definition VE.h:394
auto make_isa_range(RangeT &&Range)
Return a range over Range containing only elements for which isa<T> holds, casting each of them to T.
Definition STLExtras.h:567
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
LLVM_ABI bool convertUsersOfConstantsToInstructions(ArrayRef< Constant * > Consts, Function *RestrictToFunc=nullptr, bool RemoveDeadConstants=true, bool IncludeSelf=false)
Replace constant expressions users of the given constants with instructions.
const IPOOptions & getIPOOptions(const LLVMContext &C)
Definition IPOOptions.h:44
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1652
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
IRBuilder(LLVMContext &, FolderTy, InserterTy) -> IRBuilder< FolderTy, InserterTy >
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
Definition Error.cpp:163
constexpr uint64_t alignTo(uint64_t Size, Align A)
Returns a multiple of A needed to store Size bytes.
Definition Alignment.h:149
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
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 raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
@ Ref
The access may reference the value stored in memory.
Definition ModRef.h:32
@ Other
Any other memory.
Definition ModRef.h:68
TargetTransformInfo TTI
LLVM_ABI void appendToCompilerUsed(Module &M, ArrayRef< GlobalValue * > Values)
Adds global values to the llvm.compiler.used list.
IntPtrTy
Definition InstrProf.h:82
DWARFExpression::Operation Op
bool isMemProfClone(const GlobalValue &GV)
Returns true if GV is a MemProf context-disambiguated clone.
Expected< T > errorOrToExpected(ErrorOr< T > &&EO)
Convert an ErrorOr<T> to an Expected<T>.
Definition Error.h:1261
ArrayRef(const T &OneElt) -> ArrayRef< T >
OutputIt copy(R &&Range, OutputIt Out)
Definition STLExtras.h:1901
constexpr unsigned BitWidth
LLVM_ABI void appendToGlobalCtors(Module &M, Function *F, int Priority, Constant *Data=nullptr)
Append F to the list of global ctors of module M with the given Priority.
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
void erase_if(Container &C, UnaryPredicate P)
Provide a container algorithm similar to C++ Library Fundamentals v2's erase_if which is equivalent t...
Definition STLExtras.h:2210
LLVM_ABI Error errorCodeToError(std::error_code EC)
Helper for converting an std::error_code to a Error.
Definition Error.cpp:107
LLVM_ABI Instruction * SplitBlockAndInsertIfThen(Value *Cond, BasicBlock::iterator SplitBefore, bool Unreachable, MDNode *BranchWeights=nullptr, DomTreeUpdater *DTU=nullptr, LoopInfo *LI=nullptr, BasicBlock *ThenBlock=nullptr)
Split the containing block at the specified instruction - everything before SplitBefore stays in the ...
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
BumpPtrAllocatorImpl<> BumpPtrAllocator
The standard BumpPtrAllocator which just uses the default template parameters.
Definition Allocator.h:391
LLVM_ABI void appendToUsed(Module &M, ArrayRef< GlobalValue * > Values)
Adds global values to the llvm.used list.
LLVM_ABI std::unique_ptr< ModuleSummaryIndex > parseSummaryIndexAssembly(MemoryBufferRef F, SMDiagnostic &Err)
Parse LLVM Assembly for summary index from a MemoryBuffer.
Definition Parser.cpp:168
AnalysisManager< Module > ModuleAnalysisManager
Convenience typedef for the Module analysis manager.
Definition MIRParser.h:39
constexpr uint64_t NextPowerOf2(uint64_t A)
Returns the next power of two (in 64-bits) that is strictly greater than A.
Definition MathExtras.h:368
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:991
LLVM_ABI void reportFatalUsageError(Error Err)
Report a fatal error that does not indicate a bug in LLVM.
Definition Error.cpp:177
TypeTestResolution TTRes
Kind
Specifies which kind of type check we should emit for this byte array.
@ Unknown
Unknown (analysis not performed, don't lower)
@ Single
Single element (last example in "Short Inline Bit Vectors")
@ Inline
Inlined bit vector ("Short Inline Bit Vectors")
@ Unsat
Unsatisfiable type (i.e. no global has this type metadata)
@ AllOnes
All-ones bit vector ("Eliminating Bit Vector Checks for All-Ones Bit Vectors")
@ ByteArray
Test a byte array (first example)
unsigned SizeM1BitWidth
Range of size-1 expressed as a bit width.
enum llvm::TypeTestResolution::Kind TheKind
SmallVector< uint64_t, 16 > Offsets
LLVM_ABI bool containsGlobalOffset(uint64_t Offset) const
LLVM_ABI void print(raw_ostream &OS) const
This class is used to build a byte array containing overlapping bit sets.
uint64_t BitAllocs[BitsPerByte]
The number of bytes allocated so far for each of the bits.
std::vector< uint8_t > Bytes
The byte array built so far.
LLVM_ABI void allocate(const std::set< uint64_t > &Bits, uint64_t BitSize, uint64_t &AllocByteOffset, uint8_t &AllocMask)
Allocate BitSize bits in the byte array where Bits contains the bits to set.