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