44 using namespace lowertypetests;
46 #define DEBUG_TYPE "lowertypetests"
48 STATISTIC(ByteArraySizeBits,
"Byte array size in bits");
49 STATISTIC(ByteArraySizeBytes,
"Byte array size in bytes");
50 STATISTIC(NumByteArraysCreated,
"Number of byte arrays created");
51 STATISTIC(NumTypeTestCallsLowered,
"Number of type test calls lowered");
52 STATISTIC(NumTypeIdDisjointSets,
"Number of disjoint sets of type identifiers");
55 "lowertypetests-avoid-reuse",
56 cl::desc(
"Try to avoid reuse of byte array addresses using aliases"),
60 "lowertypetests-summary-action",
61 cl::desc(
"What to do with the summary when running this pass"),
64 "Import typeid resolutions from summary and globals"),
66 "Export typeid resolutions to summary and globals")),
70 "lowertypetests-read-summary",
71 cl::desc(
"Read summary from given YAML file before running pass"),
75 "lowertypetests-write-summary",
76 cl::desc(
"Write summary to given YAML file after running pass"),
90 return Bits.count(BitOffset);
103 for (uint64_t
B :
Bits)
133 for (uint64_t
Offset : Offsets) {
144 std::vector<uint64_t> &Fragment =
Fragments.back();
145 uint64_t FragmentIndex =
Fragments.size() - 1;
147 for (
auto ObjIndex : F) {
149 if (OldFragmentIndex == 0) {
152 Fragment.push_back(ObjIndex);
159 std::vector<uint64_t> &OldFragment =
Fragments[OldFragmentIndex];
160 Fragment.insert(Fragment.end(), OldFragment.begin(), OldFragment.end());
166 for (uint64_t ObjIndex : Fragment)
171 uint64_t BitSize, uint64_t &AllocByteOffset,
172 uint8_t &AllocMask) {
182 unsigned ReqSize = AllocByteOffset + BitSize;
184 if (
Bytes.size() < ReqSize)
185 Bytes.resize(ReqSize);
188 AllocMask = 1 <<
Bit;
189 for (uint64_t
B : Bits)
190 Bytes[AllocByteOffset +
B] |= AllocMask;
195 struct ByteArrayInfo {
196 std::set<uint64_t>
Bits;
207 class GlobalTypeMember final :
TrailingObjects<GlobalTypeMember, MDNode *> {
218 size_t numTrailingObjects(OverloadToken<MDNode *>)
const {
return NTypes; }
222 bool IsDefinition,
bool IsExported,
224 auto *GTM =
static_cast<GlobalTypeMember *
>(Alloc.
Allocate(
225 totalSizeToAlloc<MDNode *>(Types.
size()),
alignof(GlobalTypeMember)));
227 GTM->NTypes = Types.
size();
228 GTM->IsDefinition = IsDefinition;
229 GTM->IsExported = IsExported;
230 std::uninitialized_copy(Types.
begin(), Types.
end(),
231 GTM->getTrailingObjects<
MDNode *>());
237 bool isDefinition()
const {
240 bool isExported()
const {
244 return makeArrayRef(getTrailingObjects<MDNode *>(), NTypes);
248 class LowerTypeTestsModule {
264 IntegerType *IntPtrTy = M.getDataLayout().getIntPtrType(M.getContext(), 0);
267 uint64_t IndirectIndex = 1;
272 struct TypeIdUserInfo {
273 std::vector<CallInst *> CallSites;
274 bool IsExported =
false;
282 struct TypeIdLowering {
306 std::vector<ByteArrayInfo> ByteArrayInfos;
308 Function *WeakInitializerFn =
nullptr;
310 void exportTypeId(
StringRef TypeId,
const TypeIdLowering &TIL);
311 TypeIdLowering importTypeId(
StringRef TypeId);
313 void importFunction(
Function *
F,
bool isDefinition);
318 ByteArrayInfo *createByteArray(
BitSetInfo &BSI);
319 void allocateByteArrays();
322 void lowerTypeTestCalls(
326 const TypeIdLowering &TIL);
329 unsigned getJumpTableEntrySize();
330 Type *getJumpTableEntryType();
345 void findGlobalVariableUsersOf(
Constant *
C,
357 static bool runForTesting(
Module &M);
363 bool UseCommandLine =
false;
375 ImportSummary(ImportSummary) {
379 bool runOnModule(
Module &M)
override {
383 return LowerTypeTestsModule::runForTesting(M);
384 return LowerTypeTestsModule(M, ExportSummary, ImportSummary).lower();
390 INITIALIZE_PASS(LowerTypeTests,
"lowertypetests",
"Lower type metadata",
false,
392 char LowerTypeTests::
ID = 0;
397 return new LowerTypeTests(ExportSummary, ImportSummary);
409 for (
auto &GlobalAndOffset : GlobalLayout) {
410 for (
MDNode *
Type : GlobalAndOffset.first->types()) {
411 if (
Type->getOperand(1) != TypeId)
415 cast<ConstantAsMetadata>(
Type->getOperand(0))->getValue())
417 BSB.
addOffset(GlobalAndOffset.second + Offset);
428 auto BitsType = cast<IntegerType>(Bits->
getType());
429 unsigned BitWidth = BitsType->getBitWidth();
439 ByteArrayInfo *LowerTypeTestsModule::createByteArray(
BitSetInfo &BSI) {
448 ByteArrayInfos.emplace_back();
449 ByteArrayInfo *BAI = &ByteArrayInfos.back();
451 BAI->Bits = BSI.
Bits;
453 BAI->ByteArray = ByteArrayGlobal;
454 BAI->MaskGlobal = MaskGlobal;
458 void LowerTypeTestsModule::allocateByteArrays() {
459 std::stable_sort(ByteArrayInfos.begin(), ByteArrayInfos.end(),
460 [](
const ByteArrayInfo &BAI1,
const ByteArrayInfo &BAI2) {
461 return BAI1.BitSize > BAI2.BitSize;
464 std::vector<uint64_t> ByteArrayOffsets(ByteArrayInfos.size());
467 for (
unsigned I = 0;
I != ByteArrayInfos.size(); ++
I) {
468 ByteArrayInfo *BAI = &ByteArrayInfos[
I];
471 BAB.allocate(BAI->Bits, BAI->BitSize, ByteArrayOffsets[
I], Mask);
473 BAI->MaskGlobal->replaceAllUsesWith(
475 BAI->MaskGlobal->eraseFromParent();
483 for (
unsigned I = 0; I != ByteArrayInfos.size(); ++
I) {
484 ByteArrayInfo *BAI = &ByteArrayInfos[
I];
489 ByteArrayConst->
getType(), ByteArray, Idxs);
496 BAI->ByteArray->replaceAllUsesWith(Alias);
497 BAI->ByteArray->eraseFromParent();
500 ByteArraySizeBits = BAB.BitAllocs[0] + BAB.BitAllocs[1] + BAB.BitAllocs[2] +
501 BAB.BitAllocs[3] + BAB.BitAllocs[4] + BAB.BitAllocs[5] +
502 BAB.BitAllocs[6] + BAB.BitAllocs[7];
503 ByteArraySizeBytes = BAB.Bytes.size();
509 const TypeIdLowering &TIL,
516 Constant *ByteArray = TIL.TheByteArray;
523 "bits_use", ByteArray, &M);
536 Value *V, uint64_t COffset) {
537 if (
auto GV = dyn_cast<GlobalObject>(V)) {
541 if (
Type->getOperand(1) != TypeId)
545 cast<ConstantAsMetadata>(
Type->getOperand(0))->getValue())
547 if (COffset == Offset)
553 if (
auto GEP = dyn_cast<GEPOperator>(V)) {
555 bool Result = GEP->accumulateConstantOffset(DL, APOffset);
558 COffset += APOffset.getZExtValue();
562 if (
auto Op = dyn_cast<Operator>(V)) {
563 if (
Op->getOpcode() == Instruction::BitCast)
577 const TypeIdLowering &TIL) {
621 return OffsetInRange;
628 if (
auto *Br = dyn_cast<BranchInst>(*CI->
user_begin()))
638 return createBitSetTest(ThenB, TIL, BitOffset);
645 Value *
Bit = createBitSetTest(ThenB, TIL, BitOffset);
659 void LowerTypeTestsModule::buildBitSetsFromGlobalVariables(
665 std::vector<Constant *> GlobalInits;
667 for (GlobalTypeMember *
G : Globals) {
673 uint64_t Padding =
NextPowerOf2(InitSize - 1) - InitSize;
678 Padding =
alignTo(InitSize, 128) - InitSize;
680 GlobalInits.push_back(
683 if (!GlobalInits.empty())
684 GlobalInits.pop_back();
686 auto *CombinedGlobal =
695 for (
unsigned I = 0; I != Globals.size(); ++
I)
697 GlobalLayout[Globals[I]] = CombinedGlobalLayout->getElementOffset(I * 2);
699 lowerTypeTestCalls(TypeIds, CombinedGlobal, GlobalLayout);
704 for (
unsigned I = 0; I != Globals.size(); ++
I) {
711 NewInit->
getType(), CombinedGlobal, CombinedGlobalIdxs);
715 "", CombinedGlobalElemPtr, &M);
717 GAlias->takeName(GV);
728 void LowerTypeTestsModule::exportTypeId(
StringRef TypeId,
729 const TypeIdLowering &TIL) {
737 "__typeid_" + TypeId +
"_" + Name,
C, &M);
742 ExportGlobal(
"global_addr", TIL.OffsetedGlobal);
750 uint64_t BitSize = cast<ConstantInt>(TIL.SizeM1)->getZExtValue() + 1;
758 ExportGlobal(
"byte_array", TIL.TheByteArray);
759 ExportGlobal(
"bit_mask", TIL.BitMask);
763 ExportGlobal(
"inline_bits",
767 LowerTypeTestsModule::TypeIdLowering
768 LowerTypeTestsModule::importTypeId(
StringRef TypeId) {
787 auto SetAbsRange = [&](uint64_t
Min, uint64_t
Max) {
793 if (AbsWidth == IntPtrTy->getBitWidth())
794 SetAbsRange(~0ull, ~0ull);
796 SetAbsRange(0, 1ull << AbsWidth);
801 TIL.OffsetedGlobal = ImportGlobal(
"global_addr", 0);
812 TIL.TheByteArray = ImportGlobal(
"byte_array", 0);
813 TIL.BitMask = ImportGlobal(
"bit_mask", 8);
824 void LowerTypeTestsModule::importTypeTest(
CallInst *CI) {
832 "Second argument of llvm.type.test must be a metadata string");
834 TypeIdLowering TIL = importTypeId(TypeIdStr->getString());
835 Value *Lowered = lowerTypeTestCall(TypeIdStr, CI, TIL);
842 void LowerTypeTestsModule::importFunction(
Function *
F,
bool isDefinition) {
850 std::string Name = F->
getName();
856 Name +
".cfi_jt", &M);
858 }
else if (isDefinition) {
875 replaceWeakDeclarationWithJumpTablePtr(F, FDecl);
880 void LowerTypeTestsModule::lowerTypeTestCalls(
888 BitSetInfo BSI = buildBitSet(TypeId, GlobalLayout);
890 if (
auto MDS = dyn_cast<MDString>(TypeId))
891 dbgs() << MDS->getString() <<
": ";
893 dbgs() <<
"<unnamed>: ";
905 }
else if (BSI.
BitSize <= 64) {
907 uint64_t InlineBits = 0;
908 for (
auto Bit : BSI.
Bits)
909 InlineBits |= uint64_t(1) <<
Bit;
917 ++NumByteArraysCreated;
918 ByteArrayInfo *BAI = createByteArray(BSI);
919 TIL.TheByteArray = BAI->ByteArray;
920 TIL.BitMask = BAI->MaskGlobal;
923 TypeIdUserInfo &TIUI = TypeIdUsers[TypeId];
926 exportTypeId(cast<MDString>(TypeId)->getString(), TIL);
929 for (
CallInst *CI : TIUI.CallSites) {
930 ++NumTypeTestCallsLowered;
931 Value *Lowered = lowerTypeTestCall(TypeId, CI, TIL);
944 if (isa<GlobalVariable>(GO) && GO->
hasSection())
946 "A member of a type identifier may not have an explicit section");
963 unsigned LowerTypeTestsModule::getJumpTableEntrySize() {
980 void LowerTypeTestsModule::createJumpTableEntry(
983 unsigned ArgIndex = AsmArgs.
size();
986 AsmOS <<
"jmp ${" << ArgIndex <<
":c}@plt\n";
987 AsmOS <<
"int3\nint3\nint3\n";
989 AsmOS <<
"b $" << ArgIndex <<
"\n";
991 AsmOS <<
"b.w $" << ArgIndex <<
"\n";
996 ConstraintOS << (ArgIndex > 0 ?
",s" :
"s");
1000 Type *LowerTypeTestsModule::getJumpTableEntryType() {
1006 void LowerTypeTestsModule::buildBitSetsFromFunctions(
1010 buildBitSetsFromFunctionsNative(TypeIds, Functions);
1012 buildBitSetsFromFunctionsWASM(TypeIds, Functions);
1017 void LowerTypeTestsModule::moveInitializerToModuleConstructor(
1019 if (WeakInitializerFn ==
nullptr) {
1027 WeakInitializerFn->setSection(
1029 ?
"__TEXT,__StaticInit,regular,pure_instructions"
1036 IRBuilder<> IRB(WeakInitializerFn->getEntryBlock().getTerminator());
1042 void LowerTypeTestsModule::findGlobalVariableUsersOf(
1044 for (
auto *U : C->
users()){
1045 if (
auto *GV = dyn_cast<GlobalVariable>(U))
1047 else if (
auto *C2 = dyn_cast<Constant>(U))
1048 findGlobalVariableUsersOf(C2, Out);
1053 void LowerTypeTestsModule::replaceWeakDeclarationWithJumpTablePtr(
1058 findGlobalVariableUsersOf(F, GlobalVarUsers);
1059 for (
auto GV : GlobalVarUsers)
1060 moveInitializerToModuleConstructor(GV);
1077 void LowerTypeTestsModule::createJumpTable(
1079 std::string AsmStr, ConstraintStr;
1084 for (
unsigned I = 0; I != Functions.
size(); ++
I)
1085 createJumpTableEntry(AsmOS, ConstraintOS, AsmArgs,
1086 cast<Function>(Functions[I]->getGlobal()));
1092 ?
"__TEXT,__text,regular,pure_instructions"
1105 F->
addFnAttr(
"target-cpu",
"cortex-a8");
1112 for (
const auto &Arg : AsmArgs)
1116 AsmOS.str(), ConstraintOS.str(),
1119 IRB.CreateCall(JumpTableAsm, AsmArgs);
1120 IRB.CreateUnreachable();
1125 void LowerTypeTestsModule::buildBitSetsFromFunctionsNative(
1207 unsigned EntrySize = getJumpTableEntrySize();
1208 for (
unsigned I = 0; I != Functions.
size(); ++
I)
1209 GlobalLayout[Functions[I]] = I * EntrySize;
1220 lowerTypeTestCalls(TypeIds, JumpTable, GlobalLayout);
1224 for (
unsigned I = 0; I != Functions.
size(); ++
I) {
1225 Function *F = cast<Function>(Functions[
I]->getGlobal());
1226 bool IsDefinition = Functions[
I]->isDefinition();
1230 JumpTableType, JumpTable,
1234 if (Functions[I]->isExported()) {
1240 F->
getName() +
".cfi_jt", CombinedGlobalElemPtr, &M);
1245 if (!IsDefinition) {
1247 replaceWeakDeclarationWithJumpTablePtr(F, CombinedGlobalElemPtr);
1256 FAlias->takeName(F);
1257 if (FAlias->hasName())
1258 F->
setName(FAlias->getName() +
".cfi");
1265 createJumpTable(JumpTableFn, Functions);
1274 void LowerTypeTestsModule::buildBitSetsFromFunctionsWASM(
1281 for (GlobalTypeMember *GTM : Functions) {
1282 Function *F = cast<Function>(GTM->getGlobal());
1295 GlobalLayout[GTM] = IndirectIndex++;
1304 void LowerTypeTestsModule::buildBitSetsFromDisjointSet(
1307 for (
unsigned I = 0; I != TypeIds.
size(); ++
I)
1308 TypeIdIndices[TypeIds[I]] = I;
1312 std::vector<std::set<uint64_t>> TypeMembers(TypeIds.
size());
1313 unsigned GlobalIndex = 0;
1314 for (GlobalTypeMember *GTM : Globals) {
1315 for (
MDNode *Type : GTM->types()) {
1317 unsigned TypeIdIndex = TypeIdIndices[Type->
getOperand(1)];
1318 TypeMembers[TypeIdIndex].
insert(GlobalIndex);
1326 TypeMembers.begin(), TypeMembers.end(),
1327 [](
const std::set<uint64_t> &O1,
const std::set<uint64_t> &O2) {
1328 return O1.size() < O2.size();
1335 for (
auto &&MemSet : TypeMembers)
1339 if (Globals.empty() || isa<GlobalVariable>(Globals[0]->getGlobal())) {
1341 std::vector<GlobalTypeMember *> OrderedGVs(Globals.size());
1342 auto OGI = OrderedGVs.begin();
1343 for (
auto &&F : GLB.Fragments) {
1344 for (
auto &&Offset : F) {
1348 "variables and functions");
1349 *OGI++ = Globals[
Offset];
1353 buildBitSetsFromGlobalVariables(TypeIds, OrderedGVs);
1356 std::vector<GlobalTypeMember *> OrderedFns(Globals.size());
1357 auto OFI = OrderedFns.begin();
1358 for (
auto &&F : GLB.Fragments) {
1359 for (
auto &&Offset : F) {
1363 "variables and functions");
1364 *OFI++ = Globals[
Offset];
1368 buildBitSetsFromFunctions(TypeIds, OrderedFns);
1373 LowerTypeTestsModule::LowerTypeTestsModule(
1376 : M(M), ExportSummary(ExportSummary), ImportSummary(ImportSummary) {
1377 assert(!(ExportSummary && ImportSummary));
1379 Arch = TargetTriple.
getArch();
1380 OS = TargetTriple.getOS();
1381 ObjectFormat = TargetTriple.getObjectFormat();
1384 bool LowerTypeTestsModule::runForTesting(
Module &M) {
1392 auto ReadSummaryFile =
1401 LowerTypeTestsModule(
1420 bool LowerTypeTestsModule::lower() {
1423 if ((!TypeTestFunc || TypeTestFunc->
use_empty()) && !ExportSummary &&
1427 if (ImportSummary) {
1431 auto *CI = cast<CallInst>((*UI++).getUser());
1441 if (F.hasLocalLinkage())
1450 importFunction(F,
true);
1451 for (
auto F : Decls)
1452 importFunction(F,
false);
1462 GlobalClassesTy GlobalClasses;
1474 std::vector<GlobalTypeMember *> RefGlobals;
1480 struct ExportedFunctionInfo {
1485 if (ExportSummary) {
1486 NamedMDNode *CfiFunctionsMD = M.getNamedMetadata(
"cfi.functions");
1487 if (CfiFunctionsMD) {
1488 for (
auto FuncMD : CfiFunctionsMD->
operands()) {
1489 assert(FuncMD->getNumOperands() >= 2);
1491 cast<MDString>(FuncMD->getOperand(0))->getString();
1492 if (!ExportSummary->
isGUIDLive(GlobalValue::getGUID(
1493 GlobalValue::dropLLVMManglingEscape(FunctionName))))
1496 cast<ConstantAsMetadata>(FuncMD->getOperand(1))
1498 ->getUniqueInteger()
1500 auto P = ExportedFunctions.
insert({FunctionName, {Linkage, FuncMD}});
1502 P.first->second = {Linkage, FuncMD};
1505 for (
const auto &P : ExportedFunctions) {
1508 MDNode *FuncMD = P.second.FuncMD;
1509 Function *F = M.getFunction(FunctionName);
1511 F = Function::Create(
1512 FunctionType::get(Type::getVoidTy(M.getContext()),
false),
1513 GlobalVariable::ExternalLinkage, FunctionName, &M);
1520 F->
setLinkage(GlobalValue::ExternalWeakLinkage);
1541 bool IsExported =
false;
1542 if (isa<Function>(GO) && ExportedFunctions.count(GO.
getName())) {
1548 GlobalTypeMember::create(Alloc, &GO, IsDefinition, IsExported, Types);
1549 for (
MDNode *Type : Types) {
1550 verifyTypeMDNode(&GO, Type);
1551 auto &Info = TypeIdInfo[cast<MDNode>(
Type)->getOperand(1)];
1553 Info.RefGlobals.push_back(GTM);
1557 auto AddTypeIdUse = [&](
Metadata *TypeId) -> TypeIdUserInfo & {
1562 auto Ins = TypeIdUsers.insert({TypeId, {}});
1565 GlobalClassesTy::iterator GCI = GlobalClasses.insert(TypeId);
1566 GlobalClassesTy::member_iterator CurSet = GlobalClasses.findLeader(GCI);
1569 for (GlobalTypeMember *GTM : TypeIdInfo[TypeId].RefGlobals)
1570 CurSet = GlobalClasses.unionSets(
1571 CurSet, GlobalClasses.findLeader(GlobalClasses.insert(GTM)));
1574 return Ins.first->second;
1578 for (
const Use &U : TypeTestFunc->
uses()) {
1579 auto CI = cast<CallInst>(U.getUser());
1584 auto TypeId = TypeIdMDVal->getMetadata();
1585 AddTypeIdUse(TypeId).CallSites.push_back(CI);
1589 if (ExportSummary) {
1591 for (
auto &P : TypeIdInfo) {
1592 if (
auto *TypeId = dyn_cast<MDString>(P.first))
1593 MetadataByGUID[GlobalValue::getGUID(TypeId->getString())].push_back(
1597 for (
auto &P : *ExportSummary) {
1598 for (
auto &S : P.second.SummaryList) {
1600 if (!FS || !ExportSummary->isGlobalValueLive(FS))
1604 AddTypeIdUse(MD).IsExported =
true;
1609 if (GlobalClasses.empty())
1614 std::vector<std::pair<GlobalClassesTy::iterator, unsigned>> Sets;
1615 for (GlobalClassesTy::iterator I = GlobalClasses.begin(),
1616 E = GlobalClasses.end();
1620 ++NumTypeIdDisjointSets;
1622 unsigned MaxIndex = 0;
1623 for (GlobalClassesTy::member_iterator
MI = GlobalClasses.member_begin(I);
1624 MI != GlobalClasses.member_end(); ++
MI) {
1628 Sets.emplace_back(I, MaxIndex);
1631 [](
const std::pair<GlobalClassesTy::iterator, unsigned> &S1,
1632 const std::pair<GlobalClassesTy::iterator, unsigned> &S2) {
1633 return S1.second < S2.second;
1637 for (
const auto &S : Sets) {
1639 std::vector<Metadata *> TypeIds;
1640 std::vector<GlobalTypeMember *> Globals;
1641 for (GlobalClassesTy::member_iterator
MI =
1642 GlobalClasses.member_begin(S.first);
1643 MI != GlobalClasses.member_end(); ++
MI) {
1647 Globals.push_back(
MI->get<GlobalTypeMember *>());
1653 return TypeIdInfo[M1].Index < TypeIdInfo[M2].Index;
1657 buildBitSetsFromDisjointSet(TypeIds, Globals);
1660 allocateByteArrays();
1667 bool Changed = LowerTypeTestsModule(M,
nullptr,
void setVisibility(VisibilityTypes V)
This class implements a layout algorithm for globals referenced by bit sets that tries to keep member...
SymbolTableList< Instruction >::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
void push_back(const T &Elt)
A parsed version of the target data layout string in and methods for querying it. ...
LinkageTypes getLinkage() const
static ConstantInt * getFalse(LLVMContext &Context)
void ReplaceInstWithInst(BasicBlock::InstListType &BIL, BasicBlock::iterator &BI, Instruction *I)
Replace the instruction specified by BI with the instruction specified by I.
iterator_range< use_iterator > uses()
This class is used to build a byte array containing overlapping bit sets.
static IntegerType * getInt1Ty(LLVMContext &C)
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function. ...
VisibilityTypes getVisibility() const
GCNRegPressure max(const GCNRegPressure &P1, const GCNRegPressure &P2)
Value * CreateICmpNE(Value *LHS, Value *RHS, const Twine &Name="")
void print(raw_ostream &OS) const
Value * CreateZExtOrTrunc(Value *V, Type *DestTy, const Twine &Name="")
Create a ZExt or Trunc from the integer value V to DestTy.
NodeTy * getNextNode()
Get the next node, or nullptr for the list tail.
STATISTIC(NumFunctions,"Total number of functions")
uint64_t GUID
Declare a type to represent a global unique identifier for a global value.
LLVM_ATTRIBUTE_NORETURN void report_fatal_error(Error Err, bool gen_crash_diag=true)
Report a serious error, calling any installed error handler.
A Module instance is used to store all the information related to an LLVM module. ...
static cl::opt< bool > AvoidReuse("lowertypetests-avoid-reuse", cl::desc("Try to avoid reuse of byte array addresses using aliases"), cl::Hidden, cl::init(true))
static Constant * getAnon(ArrayRef< Constant * > V, bool Packed=false)
Return an anonymous struct that has the specified elements.
Unsatisfiable type (i.e. no global has this type metadata)
unsigned getNumOperands() const
Return number of MDNode operands.
static cl::opt< PassSummaryAction > ClSummaryAction("lowertypetests-summary-action", cl::desc("What to do with the summary when running this pass"), cl::values(clEnumValN(PassSummaryAction::None,"none","Do nothing"), clEnumValN(PassSummaryAction::Import,"import","Import typeid resolutions from summary and globals"), clEnumValN(PassSummaryAction::Export,"export","Export typeid resolutions to summary and globals")), cl::Hidden)
static ConstantAggregateZero * get(Type *Ty)
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.
Helper for check-and-exit error handling.
Type * getValueType() const
This class represents a function call, abstracting a target machine's calling convention.
static Constant * getGetElementPtr(Type *Ty, Constant *C, ArrayRef< Constant * > IdxList, bool InBounds=false, Optional< unsigned > InRangeIndex=None, Type *OnlyIfReducedTy=nullptr)
Getelementptr form.
static Constant * getIntToPtr(Constant *C, Type *Ty, bool OnlyIfReduced=false)
CfiFunctionLinkage
The type of CFI jumptable needed for a function.
Like Internal, but omit from symbol table.
Externally visible function.
void addOffset(uint64_t Offset)
uint64_t alignTo(uint64_t Value, uint64_t Align, uint64_t Skew=0)
Returns the next integer (mod 2**64) that is greater than or equal to Value and is a multiple of Alig...
unsigned getAddressSpace() const
Return the address space of the Pointer type.
ELFYAML::ELF_STV Visibility
static IntegerType * getInt64Ty(LLVMContext &C)
static Constant * getSub(Constant *C1, Constant *C2, bool HasNUW=false, bool HasNSW=false)
Kind
Specifies which kind of type check we should emit for this byte array.
Value * CreateICmpULE(Value *LHS, Value *RHS, const Twine &Name="")
void reserve(size_type N)
void setAlignment(unsigned Align)
const Constant * getInitializer() const
getInitializer - Return the initializer for this global variable.
std::vector< uint8_t > Bytes
The byte array built so far.
const std::string & getTargetTriple() const
Get the target triple which is a string describing the target host.
std::vector< uint64_t > FragmentMap
Mapping from object index to fragment index.
static Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
StringRef getName() const
Return a constant reference to the value's name.
Export information to summary.
static ReturnInst * Create(LLVMContext &C, Value *retVal=nullptr, Instruction *InsertBefore=nullptr)
static bool isKnownTypeIdMember(Metadata *TypeId, const DataLayout &DL, Value *V, uint64_t COffset)
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Used to lazily calculate structure layout information for a target machine, based on the DataLayout s...
void initializeLowerTypeTestsPass(PassRegistry &)
const StructLayout * getStructLayout(StructType *Ty) const
Returns a StructLayout object, indicating the alignment of the struct, its size, and the offsets of i...
ArrayRef< T > makeArrayRef(const T &OneElt)
Construct an ArrayRef from a single element.
void setInitializer(Constant *InitVal)
setInitializer - Sets the initializer for this global variable, removing any existing initializer if ...
static Constant * get(LLVMContext &Context, ArrayRef< uint8_t > Elts)
get() constructors - Return a constant with array type with an element count and element type matchin...
Class to represent struct types.
A Use represents the edge between a Value definition and its users.
static const unsigned kX86JumpTableEntrySize
The returned value is undefined.
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
static StringRef getName(Value *V)
void setName(const Twine &Name)
Change the name of the value.
LLVM_NODISCARD bool empty() const
static Constant * getZExt(Constant *C, Type *Ty, bool OnlyIfReduced=false)
bool insert(const value_type &X)
Insert a new element into the SetVector.
unsigned getAlignment() const
Class to represent array types.
VisibilityTypes
An enumeration for the kinds of visibility of global values.
static Constant * getSelect(Constant *C, Constant *V1, Constant *V2, Type *OnlyIfReducedTy=nullptr)
Select constant expr.
static FunctionType * get(Type *Result, ArrayRef< Type * > Params, bool isVarArg)
This static method is the primary way of constructing a FunctionType.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
TypeIdSummary & getOrInsertTypeIdSummary(StringRef TypeId)
This accessor should only be used when exporting because it can mutate the map.
Value * CreateSub(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
ArchType getArch() const
getArch - Get the parsed architecture type of this triple.
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Class to hold module path string table and global value map, and encapsulate methods for operating on...
iterator_range< op_iterator > operands()
size_t size() const
size - Get the array size.
void SetInsertPoint(BasicBlock *TheBB)
This specifies that created instructions should be appended to the end of the specified block...
Class to represent pointers.
static PreservedAnalyses none()
Convenience factory function for the empty preserved set.
Value * CreateOr(Value *LHS, Value *RHS, const Twine &Name="")
Function * getFunction(StringRef Name) const
Look up the specified function in the module symbol table.
static bool isWeakForLinker(LinkageTypes Linkage)
Whether the definition of this global may be replaced at link time.
static Constant * getBitCast(Constant *C, Type *Ty, bool OnlyIfReduced=false)
bool hasSection() const
Check if this global has a custom object file section.
ValuesClass values(OptsTy...Options)
Helper to build a ValuesClass by forwarding a variable number of arguments as an initializer list to ...
ExternalWeak linkage description.
LoadInst * CreateLoad(Value *Ptr, const char *Name)
initializer< Ty > init(const Ty &Val)
static Constant * getInBoundsGetElementPtr(Type *Ty, Constant *C, ArrayRef< Constant * > IdxList)
Create an "inbounds" getelementptr.
A set of analyses that are preserved following a run of a transformation pass.
static ConstantPointerNull * get(PointerType *T)
Static factory methods - Return objects of the specified value.
std::size_t countTrailingZeros(T Val, ZeroBehavior ZB=ZB_Width)
Count number of 0's from the least significant bit to the most stopping at the first 1...
Import information from summary.
LLVM Basic Block Representation.
The instances of the Type class are immutable: once they are created, they are never changed...
FunctionType * getFunctionType() const
Returns the FunctionType for me.
Allocate memory in an ever growing pool, as if by bump-pointer.
Constant * getOrInsertGlobal(StringRef Name, Type *Ty)
Look up the specified global in the module symbol table.
Conditional or Unconditional Branch instruction.
static ManagedStatic< std::map< const Function *, ExFunc > > ExportedFunctions
This is an important base class in LLVM.
Error errorCodeToError(std::error_code EC)
Helper for converting an std::error_code to a Error.
This file contains the declarations for the subclasses of Constant, which represent the different fla...
LLVM_ATTRIBUTE_RETURNS_NONNULL LLVM_ATTRIBUTE_RETURNS_NOALIAS void * Allocate(size_t Size, size_t Alignment)
Allocate space at the specified alignment.
void eraseFromParent()
eraseFromParent - This method unlinks 'this' from the containing module and deletes it...
EquivalenceClasses - This represents a collection of equivalence classes and supports three efficient...
Expected< T > errorOrToExpected(ErrorOr< T > &&EO)
Convert an ErrorOr<T> to an Expected<T>.
static Type * getVoidTy(LLVMContext &C)
Single element (last example in "Short Inline Bit Vectors")
ModulePass * createLowerTypeTestsPass(ModuleSummaryIndex *ExportSummary, const ModuleSummaryIndex *ImportSummary)
This pass lowers type metadata and the llvm.type.test intrinsic to bitsets.
See the file comment for details on the usage of the TrailingObjects type.
uint64_t BitAllocs[BitsPerByte]
The number of bytes allocated so far for each of the bits.
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
Value * CreateICmpEQ(Value *LHS, Value *RHS, const Twine &Name="")
static Constant * getICmp(unsigned short pred, Constant *LHS, Constant *RHS, bool OnlyIfReduced=false)
get* - Return some common constants without having to specify the full Instruction::OPCODE identifier...
self_iterator getIterator()
Class to represent integer types.
bool empty() const
empty - Check if the array is empty.
SmallVector< uint64_t, 16 > Offsets
void setConstant(bool Val)
bool isThreadLocal() const
If the value is "Thread Local", its value isn't shared by the threads.
The Output class is used to generate a yaml document from in-memory structs and vectors.
uint64_t NextPowerOf2(uint64_t A)
Returns the next power of two (in 64-bits) that is strictly greater than A.
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
static PointerType * getInt8PtrTy(LLVMContext &C, unsigned AS=0)
void setMetadata(unsigned KindID, MDNode *Node)
Set the metadata of the specified kind to the specified node.
Triple - Helper class for working with autoconf configuration names.
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
PHINode * CreatePHI(Type *Ty, unsigned NumReservedValues, const Twine &Name="")
static Constant * getPointerCast(Constant *C, Type *Ty)
Create a BitCast, AddrSpaceCast, or a PtrToInt cast constant expression.
const MDOperand & getOperand(unsigned I) const
A SetVector that performs no allocations if smaller than a certain size.
static PointerType * getUnqual(Type *ElementType)
This constructs a pointer to an object of the specified type in the generic address space (address sp...
This is the shared class of boolean and integer constants.
uint64_t getTypeAllocSize(Type *Ty) const
Returns the offset in bytes between successive objects of the specified type, including alignment pad...
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
Module.h This file contains the declarations for the Module class.
Type * getType() const
All values are typed, get the type of this value.
void addMetadata(unsigned KindID, MDNode &MD)
Add a metadata attachment.
TerminatorInst * SplitBlockAndInsertIfThen(Value *Cond, Instruction *SplitBefore, bool Unreachable, MDNode *BranchWeights=nullptr, DominatorTree *DT=nullptr, LoopInfo *LI=nullptr)
Split the containing block at the specified instruction - everything before SplitBefore stays in the ...
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 ...
static Constant * get(Type *Ty, uint64_t V, bool isSigned=false)
If Ty is a vector type, return a Constant with a splat of the given value.
static BranchInst * Create(BasicBlock *IfTrue, Instruction *InsertBefore=nullptr)
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.
static ConstantInt * getTrue(LLVMContext &Context)
void setLinkage(LinkageTypes LT)
enum llvm::TypeTestResolution::Kind TheKind
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Value * getArgOperand(unsigned i) const
getArgOperand/setArgOperand - Return/set the i-th call argument.
Value * CreateGEP(Value *Ptr, ArrayRef< Value * > IdxList, const Twine &Name="")
Target - Wrapper for Target specific information.
Class for arbitrary precision integers.
iterator_range< user_iterator > users()
Value * CreateShl(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
The file should be opened in text mode on platforms that make this distinction.
MDNode * getMetadata(unsigned KindID) const
Get the current metadata attachments for the given kind, if any.
void setMetadata(unsigned KindID, MDNode *MD)
Set a particular kind of metadata attachment.
#define clEnumValN(ENUMVAL, FLAGNAME, DESC)
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
std::set< std::string > & cfiFunctionDefs()
Test a byte array (first example)
PointerType * getType() const
Global values are always pointers.
const DataLayout & getDataLayout() const
Get the data layout for the module's target platform.
bool hasAddressTaken(const User **=nullptr) const
hasAddressTaken - returns true if there are any uses of this function other than direct calls or invo...
A raw_ostream that writes to a file descriptor.
static IntegerType * getInt32Ty(LLVMContext &C)
bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
All-ones bit vector ("Eliminating Bit Vector Checks for All-Ones Bit Vectors") ...
static Constant * getPtrToInt(Constant *C, Type *Ty, bool OnlyIfReduced=false)
bool isGUIDLive(GlobalValue::GUID GUID) const
LLVM_ATTRIBUTE_ALWAYS_INLINE size_type size() const
bool hasOneUse() const
Return true if there is exactly one user of this value.
ModulePass class - This class is used to implement unstructured interprocedural optimizations and ana...
unsigned getPointerSizeInBits(unsigned AS=0) const
Layout pointer size, in bits FIXME: The defaults need to be removed once all of the backends/clients ...
static ArrayType * get(Type *ElementType, uint64_t NumElements)
This static method is the primary way to construct an ArrayType.
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
Rename collisions when linking (static functions).
void eraseFromParent()
eraseFromParent - This method unlinks 'this' from the containing module and deletes it...
BasicBlock * splitBasicBlock(iterator I, const Twine &BBName="")
Split the basic block into two basic blocks at the specified instruction.
static InlineAsm * get(FunctionType *Ty, StringRef AsmString, StringRef Constraints, bool hasSideEffects, bool isAlignStack=false, AsmDialect asmDialect=AD_ATT)
InlineAsm::get - Return the specified uniqued inline asm string.
Inlined bit vector ("Short Inline Bit Vectors")
unsigned SizeM1BitWidth
Range of size-1 expressed as a bit width.
Function summary information to aid decisions and implementation of importing.
Value * CreateAnd(Value *LHS, Value *RHS, const Twine &Name="")
Value * CreatePtrToInt(Value *V, Type *DestTy, const Twine &Name="")
static cl::opt< std::string > ClReadSummary("lowertypetests-read-summary", cl::desc("Read summary from given YAML file before running pass"), cl::Hidden)
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
std::set< std::string > & cfiFunctionDecls()
user_iterator user_begin()
static Value * createMaskedBitTest(IRBuilder<> &B, Value *Bits, Value *BitOffset)
Build a test that bit BitOffset mod sizeof(Bits)*8 is set in Bits.
void eraseMetadata(unsigned KindID)
Erase all metadata attachments with the given kind.
void addFragment(const std::set< uint64_t > &F)
Add F to the layout while trying to keep its indices contiguous.
A raw_ostream that writes to an std::string.
LLVM Value Representation.
This header defines support for implementing classes that have some trailing object (or arrays of obj...
std::underlying_type< E >::type Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
Value * CreateLShr(Value *LHS, Value *RHS, const Twine &Name="", bool isExact=false)
This class implements an extremely fast bulk output stream that can only output to a stream...
static const unsigned kARMJumpTableEntrySize
void addFnAttr(Attribute::AttrKind Kind)
Add function attributes to this function.
StringRef - Represent a constant reference to a string, i.e.
A container for analyses that lazily runs them and caches their results.
static Function * Create(FunctionType *Ty, LinkageTypes Linkage, const Twine &N="", Module *M=nullptr)
void sort(Policy policy, RandomAccessIterator Start, RandomAccessIterator End, const Comparator &Comp=Comparator())
std::set< uint64_t > Bits
static cl::opt< std::string > ClWriteSummary("lowertypetests-write-summary", cl::desc("Write summary to given YAML file after running pass"), cl::Hidden)
std::vector< std::vector< uint64_t > > Fragments
The computed layout.
bool isDeclarationForLinker() const
static IntegerType * getInt8Ty(LLVMContext &C)
void setSection(StringRef S)
Change the section for this global.
const BasicBlock * getParent() const
static 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...
bool containsGlobalOffset(uint64_t Offset) const
LLVMContext & getContext() const
Get the global data context.