LLVM  5.0.0
LowerTypeTests.cpp
Go to the documentation of this file.
1 //===-- LowerTypeTests.cpp - type metadata lowering pass ------------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This pass lowers type metadata and calls to the llvm.type.test intrinsic.
11 // See http://llvm.org/docs/TypeMetadata.html for more information.
12 //
13 //===----------------------------------------------------------------------===//
14 
17 #include "llvm/ADT/SetVector.h"
18 #include "llvm/ADT/Statistic.h"
19 #include "llvm/ADT/Triple.h"
21 #include "llvm/IR/Constant.h"
22 #include "llvm/IR/Constants.h"
23 #include "llvm/IR/Function.h"
24 #include "llvm/IR/GlobalObject.h"
25 #include "llvm/IR/GlobalVariable.h"
26 #include "llvm/IR/IRBuilder.h"
27 #include "llvm/IR/InlineAsm.h"
28 #include "llvm/IR/Instructions.h"
29 #include "llvm/IR/Intrinsics.h"
30 #include "llvm/IR/Module.h"
32 #include "llvm/IR/Operator.h"
33 #include "llvm/Pass.h"
34 #include "llvm/Support/Debug.h"
35 #include "llvm/Support/Error.h"
39 #include "llvm/Transforms/IPO.h"
42 
43 using namespace llvm;
44 using namespace lowertypetests;
45 
46 #define DEBUG_TYPE "lowertypetests"
47 
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");
53 
55  "lowertypetests-avoid-reuse",
56  cl::desc("Try to avoid reuse of byte array addresses using aliases"),
57  cl::Hidden, cl::init(true));
58 
60  "lowertypetests-summary-action",
61  cl::desc("What to do with the summary when running this pass"),
62  cl::values(clEnumValN(PassSummaryAction::None, "none", "Do nothing"),
64  "Import typeid resolutions from summary and globals"),
66  "Export typeid resolutions to summary and globals")),
67  cl::Hidden);
68 
70  "lowertypetests-read-summary",
71  cl::desc("Read summary from given YAML file before running pass"),
72  cl::Hidden);
73 
75  "lowertypetests-write-summary",
76  cl::desc("Write summary to given YAML file after running pass"),
77  cl::Hidden);
78 
80  if (Offset < ByteOffset)
81  return false;
82 
83  if ((Offset - ByteOffset) % (uint64_t(1) << AlignLog2) != 0)
84  return false;
85 
86  uint64_t BitOffset = (Offset - ByteOffset) >> AlignLog2;
87  if (BitOffset >= BitSize)
88  return false;
89 
90  return Bits.count(BitOffset);
91 }
92 
93 void BitSetInfo::print(raw_ostream &OS) const {
94  OS << "offset " << ByteOffset << " size " << BitSize << " align "
95  << (1 << AlignLog2);
96 
97  if (isAllOnes()) {
98  OS << " all-ones\n";
99  return;
100  }
101 
102  OS << " { ";
103  for (uint64_t B : Bits)
104  OS << B << ' ';
105  OS << "}\n";
106 }
107 
109  if (Min > Max)
110  Min = 0;
111 
112  // Normalize each offset against the minimum observed offset, and compute
113  // the bitwise OR of each of the offsets. The number of trailing zeros
114  // in the mask gives us the log2 of the alignment of all offsets, which
115  // allows us to compress the bitset by only storing one bit per aligned
116  // address.
117  uint64_t Mask = 0;
118  for (uint64_t &Offset : Offsets) {
119  Offset -= Min;
120  Mask |= Offset;
121  }
122 
123  BitSetInfo BSI;
124  BSI.ByteOffset = Min;
125 
126  BSI.AlignLog2 = 0;
127  if (Mask != 0)
129 
130  // Build the compressed bitset while normalizing the offsets against the
131  // computed alignment.
132  BSI.BitSize = ((Max - Min) >> BSI.AlignLog2) + 1;
133  for (uint64_t Offset : Offsets) {
134  Offset >>= BSI.AlignLog2;
135  BSI.Bits.insert(Offset);
136  }
137 
138  return BSI;
139 }
140 
141 void GlobalLayoutBuilder::addFragment(const std::set<uint64_t> &F) {
142  // Create a new fragment to hold the layout for F.
143  Fragments.emplace_back();
144  std::vector<uint64_t> &Fragment = Fragments.back();
145  uint64_t FragmentIndex = Fragments.size() - 1;
146 
147  for (auto ObjIndex : F) {
148  uint64_t OldFragmentIndex = FragmentMap[ObjIndex];
149  if (OldFragmentIndex == 0) {
150  // We haven't seen this object index before, so just add it to the current
151  // fragment.
152  Fragment.push_back(ObjIndex);
153  } else {
154  // This index belongs to an existing fragment. Copy the elements of the
155  // old fragment into this one and clear the old fragment. We don't update
156  // the fragment map just yet, this ensures that any further references to
157  // indices from the old fragment in this fragment do not insert any more
158  // indices.
159  std::vector<uint64_t> &OldFragment = Fragments[OldFragmentIndex];
160  Fragment.insert(Fragment.end(), OldFragment.begin(), OldFragment.end());
161  OldFragment.clear();
162  }
163  }
164 
165  // Update the fragment map to point our object indices to this fragment.
166  for (uint64_t ObjIndex : Fragment)
167  FragmentMap[ObjIndex] = FragmentIndex;
168 }
169 
170 void ByteArrayBuilder::allocate(const std::set<uint64_t> &Bits,
171  uint64_t BitSize, uint64_t &AllocByteOffset,
172  uint8_t &AllocMask) {
173  // Find the smallest current allocation.
174  unsigned Bit = 0;
175  for (unsigned I = 1; I != BitsPerByte; ++I)
176  if (BitAllocs[I] < BitAllocs[Bit])
177  Bit = I;
178 
179  AllocByteOffset = BitAllocs[Bit];
180 
181  // Add our size to it.
182  unsigned ReqSize = AllocByteOffset + BitSize;
183  BitAllocs[Bit] = ReqSize;
184  if (Bytes.size() < ReqSize)
185  Bytes.resize(ReqSize);
186 
187  // Set our bits.
188  AllocMask = 1 << Bit;
189  for (uint64_t B : Bits)
190  Bytes[AllocByteOffset + B] |= AllocMask;
191 }
192 
193 namespace {
194 
195 struct ByteArrayInfo {
196  std::set<uint64_t> Bits;
197  uint64_t BitSize;
198  GlobalVariable *ByteArray;
199  GlobalVariable *MaskGlobal;
200 };
201 
202 /// A POD-like structure that we use to store a global reference together with
203 /// its metadata types. In this pass we frequently need to query the set of
204 /// metadata types referenced by a global, which at the IR level is an expensive
205 /// operation involving a map lookup; this data structure helps to reduce the
206 /// number of times we need to do this lookup.
207 class GlobalTypeMember final : TrailingObjects<GlobalTypeMember, MDNode *> {
208  GlobalObject *GO;
209  size_t NTypes;
210  // For functions: true if this is a definition (either in the merged module or
211  // in one of the thinlto modules).
212  bool IsDefinition;
213  // For functions: true if this function is either defined or used in a thinlto
214  // module and its jumptable entry needs to be exported to thinlto backends.
215  bool IsExported;
216 
217  friend TrailingObjects;
218  size_t numTrailingObjects(OverloadToken<MDNode *>) const { return NTypes; }
219 
220 public:
221  static GlobalTypeMember *create(BumpPtrAllocator &Alloc, GlobalObject *GO,
222  bool IsDefinition, bool IsExported,
223  ArrayRef<MDNode *> Types) {
224  auto *GTM = static_cast<GlobalTypeMember *>(Alloc.Allocate(
225  totalSizeToAlloc<MDNode *>(Types.size()), alignof(GlobalTypeMember)));
226  GTM->GO = GO;
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 *>());
232  return GTM;
233  }
234  GlobalObject *getGlobal() const {
235  return GO;
236  }
237  bool isDefinition() const {
238  return IsDefinition;
239  }
240  bool isExported() const {
241  return IsExported;
242  }
243  ArrayRef<MDNode *> types() const {
244  return makeArrayRef(getTrailingObjects<MDNode *>(), NTypes);
245  }
246 };
247 
248 class LowerTypeTestsModule {
249  Module &M;
250 
251  ModuleSummaryIndex *ExportSummary;
252  const ModuleSummaryIndex *ImportSummary;
253 
254  Triple::ArchType Arch;
255  Triple::OSType OS;
256  Triple::ObjectFormatType ObjectFormat;
257 
258  IntegerType *Int1Ty = Type::getInt1Ty(M.getContext());
259  IntegerType *Int8Ty = Type::getInt8Ty(M.getContext());
260  PointerType *Int8PtrTy = Type::getInt8PtrTy(M.getContext());
261  IntegerType *Int32Ty = Type::getInt32Ty(M.getContext());
263  IntegerType *Int64Ty = Type::getInt64Ty(M.getContext());
264  IntegerType *IntPtrTy = M.getDataLayout().getIntPtrType(M.getContext(), 0);
265 
266  // Indirect function call index assignment counter for WebAssembly
267  uint64_t IndirectIndex = 1;
268 
269  // Mapping from type identifiers to the call sites that test them, as well as
270  // whether the type identifier needs to be exported to ThinLTO backends as
271  // part of the regular LTO phase of the ThinLTO pipeline (see exportTypeId).
272  struct TypeIdUserInfo {
273  std::vector<CallInst *> CallSites;
274  bool IsExported = false;
275  };
277 
278  /// This structure describes how to lower type tests for a particular type
279  /// identifier. It is either built directly from the global analysis (during
280  /// regular LTO or the regular LTO phase of ThinLTO), or indirectly using type
281  /// identifier summaries and external symbol references (in ThinLTO backends).
282  struct TypeIdLowering {
284 
285  /// All except Unsat: the start address within the combined global.
286  Constant *OffsetedGlobal;
287 
288  /// ByteArray, Inline, AllOnes: log2 of the required global alignment
289  /// relative to the start address.
290  Constant *AlignLog2;
291 
292  /// ByteArray, Inline, AllOnes: one less than the size of the memory region
293  /// covering members of this type identifier as a multiple of 2^AlignLog2.
294  Constant *SizeM1;
295 
296  /// ByteArray: the byte array to test the address against.
297  Constant *TheByteArray;
298 
299  /// ByteArray: the bit mask to apply to bytes loaded from the byte array.
300  Constant *BitMask;
301 
302  /// Inline: the bit mask to test the address against.
303  Constant *InlineBits;
304  };
305 
306  std::vector<ByteArrayInfo> ByteArrayInfos;
307 
308  Function *WeakInitializerFn = nullptr;
309 
310  void exportTypeId(StringRef TypeId, const TypeIdLowering &TIL);
311  TypeIdLowering importTypeId(StringRef TypeId);
312  void importTypeTest(CallInst *CI);
313  void importFunction(Function *F, bool isDefinition);
314 
315  BitSetInfo
316  buildBitSet(Metadata *TypeId,
317  const DenseMap<GlobalTypeMember *, uint64_t> &GlobalLayout);
318  ByteArrayInfo *createByteArray(BitSetInfo &BSI);
319  void allocateByteArrays();
320  Value *createBitSetTest(IRBuilder<> &B, const TypeIdLowering &TIL,
321  Value *BitOffset);
322  void lowerTypeTestCalls(
323  ArrayRef<Metadata *> TypeIds, Constant *CombinedGlobalAddr,
324  const DenseMap<GlobalTypeMember *, uint64_t> &GlobalLayout);
325  Value *lowerTypeTestCall(Metadata *TypeId, CallInst *CI,
326  const TypeIdLowering &TIL);
327  void buildBitSetsFromGlobalVariables(ArrayRef<Metadata *> TypeIds,
329  unsigned getJumpTableEntrySize();
330  Type *getJumpTableEntryType();
331  void createJumpTableEntry(raw_ostream &AsmOS, raw_ostream &ConstraintOS,
332  SmallVectorImpl<Value *> &AsmArgs, Function *Dest);
333  void verifyTypeMDNode(GlobalObject *GO, MDNode *Type);
334  void buildBitSetsFromFunctions(ArrayRef<Metadata *> TypeIds,
335  ArrayRef<GlobalTypeMember *> Functions);
336  void buildBitSetsFromFunctionsNative(ArrayRef<Metadata *> TypeIds,
337  ArrayRef<GlobalTypeMember *> Functions);
338  void buildBitSetsFromFunctionsWASM(ArrayRef<Metadata *> TypeIds,
339  ArrayRef<GlobalTypeMember *> Functions);
340  void buildBitSetsFromDisjointSet(ArrayRef<Metadata *> TypeIds,
342 
343  void replaceWeakDeclarationWithJumpTablePtr(Function *F, Constant *JT);
344  void moveInitializerToModuleConstructor(GlobalVariable *GV);
345  void findGlobalVariableUsersOf(Constant *C,
347 
348  void createJumpTable(Function *F, ArrayRef<GlobalTypeMember *> Functions);
349 
350 public:
351  LowerTypeTestsModule(Module &M, ModuleSummaryIndex *ExportSummary,
352  const ModuleSummaryIndex *ImportSummary);
353  bool lower();
354 
355  // Lower the module using the action and summary passed as command line
356  // arguments. For testing purposes only.
357  static bool runForTesting(Module &M);
358 };
359 
360 struct LowerTypeTests : public ModulePass {
361  static char ID;
362 
363  bool UseCommandLine = false;
364 
365  ModuleSummaryIndex *ExportSummary;
366  const ModuleSummaryIndex *ImportSummary;
367 
368  LowerTypeTests() : ModulePass(ID), UseCommandLine(true) {
370  }
371 
372  LowerTypeTests(ModuleSummaryIndex *ExportSummary,
373  const ModuleSummaryIndex *ImportSummary)
374  : ModulePass(ID), ExportSummary(ExportSummary),
375  ImportSummary(ImportSummary) {
377  }
378 
379  bool runOnModule(Module &M) override {
380  if (skipModule(M))
381  return false;
382  if (UseCommandLine)
383  return LowerTypeTestsModule::runForTesting(M);
384  return LowerTypeTestsModule(M, ExportSummary, ImportSummary).lower();
385  }
386 };
387 
388 } // anonymous namespace
389 
390 INITIALIZE_PASS(LowerTypeTests, "lowertypetests", "Lower type metadata", false,
391  false)
392 char LowerTypeTests::ID = 0;
393 
394 ModulePass *
395 llvm::createLowerTypeTestsPass(ModuleSummaryIndex *ExportSummary,
396  const ModuleSummaryIndex *ImportSummary) {
397  return new LowerTypeTests(ExportSummary, ImportSummary);
398 }
399 
400 /// Build a bit set for TypeId using the object layouts in
401 /// GlobalLayout.
402 BitSetInfo LowerTypeTestsModule::buildBitSet(
403  Metadata *TypeId,
404  const DenseMap<GlobalTypeMember *, uint64_t> &GlobalLayout) {
405  BitSetBuilder BSB;
406 
407  // Compute the byte offset of each address associated with this type
408  // identifier.
409  for (auto &GlobalAndOffset : GlobalLayout) {
410  for (MDNode *Type : GlobalAndOffset.first->types()) {
411  if (Type->getOperand(1) != TypeId)
412  continue;
413  uint64_t Offset =
414  cast<ConstantInt>(
415  cast<ConstantAsMetadata>(Type->getOperand(0))->getValue())
416  ->getZExtValue();
417  BSB.addOffset(GlobalAndOffset.second + Offset);
418  }
419  }
420 
421  return BSB.build();
422 }
423 
424 /// Build a test that bit BitOffset mod sizeof(Bits)*8 is set in
425 /// Bits. This pattern matches to the bt instruction on x86.
427  Value *BitOffset) {
428  auto BitsType = cast<IntegerType>(Bits->getType());
429  unsigned BitWidth = BitsType->getBitWidth();
430 
431  BitOffset = B.CreateZExtOrTrunc(BitOffset, BitsType);
432  Value *BitIndex =
433  B.CreateAnd(BitOffset, ConstantInt::get(BitsType, BitWidth - 1));
434  Value *BitMask = B.CreateShl(ConstantInt::get(BitsType, 1), BitIndex);
435  Value *MaskedBits = B.CreateAnd(Bits, BitMask);
436  return B.CreateICmpNE(MaskedBits, ConstantInt::get(BitsType, 0));
437 }
438 
439 ByteArrayInfo *LowerTypeTestsModule::createByteArray(BitSetInfo &BSI) {
440  // Create globals to stand in for byte arrays and masks. These never actually
441  // get initialized, we RAUW and erase them later in allocateByteArrays() once
442  // we know the offset and mask to use.
443  auto ByteArrayGlobal = new GlobalVariable(
444  M, Int8Ty, /*isConstant=*/true, GlobalValue::PrivateLinkage, nullptr);
445  auto MaskGlobal = new GlobalVariable(M, Int8Ty, /*isConstant=*/true,
446  GlobalValue::PrivateLinkage, nullptr);
447 
448  ByteArrayInfos.emplace_back();
449  ByteArrayInfo *BAI = &ByteArrayInfos.back();
450 
451  BAI->Bits = BSI.Bits;
452  BAI->BitSize = BSI.BitSize;
453  BAI->ByteArray = ByteArrayGlobal;
454  BAI->MaskGlobal = MaskGlobal;
455  return BAI;
456 }
457 
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;
462  });
463 
464  std::vector<uint64_t> ByteArrayOffsets(ByteArrayInfos.size());
465 
466  ByteArrayBuilder BAB;
467  for (unsigned I = 0; I != ByteArrayInfos.size(); ++I) {
468  ByteArrayInfo *BAI = &ByteArrayInfos[I];
469 
470  uint8_t Mask;
471  BAB.allocate(BAI->Bits, BAI->BitSize, ByteArrayOffsets[I], Mask);
472 
473  BAI->MaskGlobal->replaceAllUsesWith(
474  ConstantExpr::getIntToPtr(ConstantInt::get(Int8Ty, Mask), Int8PtrTy));
475  BAI->MaskGlobal->eraseFromParent();
476  }
477 
478  Constant *ByteArrayConst = ConstantDataArray::get(M.getContext(), BAB.Bytes);
479  auto ByteArray =
480  new GlobalVariable(M, ByteArrayConst->getType(), /*isConstant=*/true,
481  GlobalValue::PrivateLinkage, ByteArrayConst);
482 
483  for (unsigned I = 0; I != ByteArrayInfos.size(); ++I) {
484  ByteArrayInfo *BAI = &ByteArrayInfos[I];
485 
486  Constant *Idxs[] = {ConstantInt::get(IntPtrTy, 0),
487  ConstantInt::get(IntPtrTy, ByteArrayOffsets[I])};
489  ByteArrayConst->getType(), ByteArray, Idxs);
490 
491  // Create an alias instead of RAUW'ing the gep directly. On x86 this ensures
492  // that the pc-relative displacement is folded into the lea instead of the
493  // test instruction getting another displacement.
495  Int8Ty, 0, GlobalValue::PrivateLinkage, "bits", GEP, &M);
496  BAI->ByteArray->replaceAllUsesWith(Alias);
497  BAI->ByteArray->eraseFromParent();
498  }
499 
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();
504 }
505 
506 /// Build a test that bit BitOffset is set in the type identifier that was
507 /// lowered to TIL, which must be either an Inline or a ByteArray.
508 Value *LowerTypeTestsModule::createBitSetTest(IRBuilder<> &B,
509  const TypeIdLowering &TIL,
510  Value *BitOffset) {
511  if (TIL.TheKind == TypeTestResolution::Inline) {
512  // If the bit set is sufficiently small, we can avoid a load by bit testing
513  // a constant.
514  return createMaskedBitTest(B, TIL.InlineBits, BitOffset);
515  } else {
516  Constant *ByteArray = TIL.TheByteArray;
517  if (AvoidReuse && !ImportSummary) {
518  // Each use of the byte array uses a different alias. This makes the
519  // backend less likely to reuse previously computed byte array addresses,
520  // improving the security of the CFI mechanism based on this pass.
521  // This won't work when importing because TheByteArray is external.
522  ByteArray = GlobalAlias::create(Int8Ty, 0, GlobalValue::PrivateLinkage,
523  "bits_use", ByteArray, &M);
524  }
525 
526  Value *ByteAddr = B.CreateGEP(Int8Ty, ByteArray, BitOffset);
527  Value *Byte = B.CreateLoad(ByteAddr);
528 
529  Value *ByteAndMask =
530  B.CreateAnd(Byte, ConstantExpr::getPtrToInt(TIL.BitMask, Int8Ty));
531  return B.CreateICmpNE(ByteAndMask, ConstantInt::get(Int8Ty, 0));
532  }
533 }
534 
535 static bool isKnownTypeIdMember(Metadata *TypeId, const DataLayout &DL,
536  Value *V, uint64_t COffset) {
537  if (auto GV = dyn_cast<GlobalObject>(V)) {
539  GV->getMetadata(LLVMContext::MD_type, Types);
540  for (MDNode *Type : Types) {
541  if (Type->getOperand(1) != TypeId)
542  continue;
543  uint64_t Offset =
544  cast<ConstantInt>(
545  cast<ConstantAsMetadata>(Type->getOperand(0))->getValue())
546  ->getZExtValue();
547  if (COffset == Offset)
548  return true;
549  }
550  return false;
551  }
552 
553  if (auto GEP = dyn_cast<GEPOperator>(V)) {
554  APInt APOffset(DL.getPointerSizeInBits(0), 0);
555  bool Result = GEP->accumulateConstantOffset(DL, APOffset);
556  if (!Result)
557  return false;
558  COffset += APOffset.getZExtValue();
559  return isKnownTypeIdMember(TypeId, DL, GEP->getPointerOperand(), COffset);
560  }
561 
562  if (auto Op = dyn_cast<Operator>(V)) {
563  if (Op->getOpcode() == Instruction::BitCast)
564  return isKnownTypeIdMember(TypeId, DL, Op->getOperand(0), COffset);
565 
566  if (Op->getOpcode() == Instruction::Select)
567  return isKnownTypeIdMember(TypeId, DL, Op->getOperand(1), COffset) &&
568  isKnownTypeIdMember(TypeId, DL, Op->getOperand(2), COffset);
569  }
570 
571  return false;
572 }
573 
574 /// Lower a llvm.type.test call to its implementation. Returns the value to
575 /// replace the call with.
576 Value *LowerTypeTestsModule::lowerTypeTestCall(Metadata *TypeId, CallInst *CI,
577  const TypeIdLowering &TIL) {
578  if (TIL.TheKind == TypeTestResolution::Unsat)
579  return ConstantInt::getFalse(M.getContext());
580 
581  Value *Ptr = CI->getArgOperand(0);
582  const DataLayout &DL = M.getDataLayout();
583  if (isKnownTypeIdMember(TypeId, DL, Ptr, 0))
584  return ConstantInt::getTrue(M.getContext());
585 
586  BasicBlock *InitialBB = CI->getParent();
587 
588  IRBuilder<> B(CI);
589 
590  Value *PtrAsInt = B.CreatePtrToInt(Ptr, IntPtrTy);
591 
592  Constant *OffsetedGlobalAsInt =
593  ConstantExpr::getPtrToInt(TIL.OffsetedGlobal, IntPtrTy);
594  if (TIL.TheKind == TypeTestResolution::Single)
595  return B.CreateICmpEQ(PtrAsInt, OffsetedGlobalAsInt);
596 
597  Value *PtrOffset = B.CreateSub(PtrAsInt, OffsetedGlobalAsInt);
598 
599  // We need to check that the offset both falls within our range and is
600  // suitably aligned. We can check both properties at the same time by
601  // performing a right rotate by log2(alignment) followed by an integer
602  // comparison against the bitset size. The rotate will move the lower
603  // order bits that need to be zero into the higher order bits of the
604  // result, causing the comparison to fail if they are nonzero. The rotate
605  // also conveniently gives us a bit offset to use during the load from
606  // the bitset.
607  Value *OffsetSHR =
608  B.CreateLShr(PtrOffset, ConstantExpr::getZExt(TIL.AlignLog2, IntPtrTy));
609  Value *OffsetSHL = B.CreateShl(
610  PtrOffset, ConstantExpr::getZExt(
612  ConstantInt::get(Int8Ty, DL.getPointerSizeInBits(0)),
613  TIL.AlignLog2),
614  IntPtrTy));
615  Value *BitOffset = B.CreateOr(OffsetSHR, OffsetSHL);
616 
617  Value *OffsetInRange = B.CreateICmpULE(BitOffset, TIL.SizeM1);
618 
619  // If the bit set is all ones, testing against it is unnecessary.
620  if (TIL.TheKind == TypeTestResolution::AllOnes)
621  return OffsetInRange;
622 
623  // See if the intrinsic is used in the following common pattern:
624  // br(llvm.type.test(...), thenbb, elsebb)
625  // where nothing happens between the type test and the br.
626  // If so, create slightly simpler IR.
627  if (CI->hasOneUse())
628  if (auto *Br = dyn_cast<BranchInst>(*CI->user_begin()))
629  if (CI->getNextNode() == Br) {
630  BasicBlock *Then = InitialBB->splitBasicBlock(CI->getIterator());
631  BasicBlock *Else = Br->getSuccessor(1);
632  BranchInst *NewBr = BranchInst::Create(Then, Else, OffsetInRange);
634  Br->getMetadata(LLVMContext::MD_prof));
635  ReplaceInstWithInst(InitialBB->getTerminator(), NewBr);
636 
637  IRBuilder<> ThenB(CI);
638  return createBitSetTest(ThenB, TIL, BitOffset);
639  }
640 
641  IRBuilder<> ThenB(SplitBlockAndInsertIfThen(OffsetInRange, CI, false));
642 
643  // Now that we know that the offset is in range and aligned, load the
644  // appropriate bit from the bitset.
645  Value *Bit = createBitSetTest(ThenB, TIL, BitOffset);
646 
647  // The value we want is 0 if we came directly from the initial block
648  // (having failed the range or alignment checks), or the loaded bit if
649  // we came from the block in which we loaded it.
650  B.SetInsertPoint(CI);
651  PHINode *P = B.CreatePHI(Int1Ty, 2);
652  P->addIncoming(ConstantInt::get(Int1Ty, 0), InitialBB);
653  P->addIncoming(Bit, ThenB.GetInsertBlock());
654  return P;
655 }
656 
657 /// Given a disjoint set of type identifiers and globals, lay out the globals,
658 /// build the bit sets and lower the llvm.type.test calls.
659 void LowerTypeTestsModule::buildBitSetsFromGlobalVariables(
661  // Build a new global with the combined contents of the referenced globals.
662  // This global is a struct whose even-indexed elements contain the original
663  // contents of the referenced globals and whose odd-indexed elements contain
664  // any padding required to align the next element to the next power of 2.
665  std::vector<Constant *> GlobalInits;
666  const DataLayout &DL = M.getDataLayout();
667  for (GlobalTypeMember *G : Globals) {
668  GlobalVariable *GV = cast<GlobalVariable>(G->getGlobal());
669  GlobalInits.push_back(GV->getInitializer());
670  uint64_t InitSize = DL.getTypeAllocSize(GV->getValueType());
671 
672  // Compute the amount of padding required.
673  uint64_t Padding = NextPowerOf2(InitSize - 1) - InitSize;
674 
675  // Cap at 128 was found experimentally to have a good data/instruction
676  // overhead tradeoff.
677  if (Padding > 128)
678  Padding = alignTo(InitSize, 128) - InitSize;
679 
680  GlobalInits.push_back(
681  ConstantAggregateZero::get(ArrayType::get(Int8Ty, Padding)));
682  }
683  if (!GlobalInits.empty())
684  GlobalInits.pop_back();
685  Constant *NewInit = ConstantStruct::getAnon(M.getContext(), GlobalInits);
686  auto *CombinedGlobal =
687  new GlobalVariable(M, NewInit->getType(), /*isConstant=*/true,
688  GlobalValue::PrivateLinkage, NewInit);
689 
690  StructType *NewTy = cast<StructType>(NewInit->getType());
691  const StructLayout *CombinedGlobalLayout = DL.getStructLayout(NewTy);
692 
693  // Compute the offsets of the original globals within the new global.
695  for (unsigned I = 0; I != Globals.size(); ++I)
696  // Multiply by 2 to account for padding elements.
697  GlobalLayout[Globals[I]] = CombinedGlobalLayout->getElementOffset(I * 2);
698 
699  lowerTypeTestCalls(TypeIds, CombinedGlobal, GlobalLayout);
700 
701  // Build aliases pointing to offsets into the combined global for each
702  // global from which we built the combined global, and replace references
703  // to the original globals with references to the aliases.
704  for (unsigned I = 0; I != Globals.size(); ++I) {
705  GlobalVariable *GV = cast<GlobalVariable>(Globals[I]->getGlobal());
706 
707  // Multiply by 2 to account for padding elements.
708  Constant *CombinedGlobalIdxs[] = {ConstantInt::get(Int32Ty, 0),
709  ConstantInt::get(Int32Ty, I * 2)};
710  Constant *CombinedGlobalElemPtr = ConstantExpr::getGetElementPtr(
711  NewInit->getType(), CombinedGlobal, CombinedGlobalIdxs);
712  assert(GV->getType()->getAddressSpace() == 0);
713  GlobalAlias *GAlias =
714  GlobalAlias::create(NewTy->getElementType(I * 2), 0, GV->getLinkage(),
715  "", CombinedGlobalElemPtr, &M);
716  GAlias->setVisibility(GV->getVisibility());
717  GAlias->takeName(GV);
718  GV->replaceAllUsesWith(GAlias);
719  GV->eraseFromParent();
720  }
721 }
722 
723 /// Export the given type identifier so that ThinLTO backends may import it.
724 /// Type identifiers are exported by adding coarse-grained information about how
725 /// to test the type identifier to the summary, and creating symbols in the
726 /// object file (aliases and absolute symbols) containing fine-grained
727 /// information about the type identifier.
728 void LowerTypeTestsModule::exportTypeId(StringRef TypeId,
729  const TypeIdLowering &TIL) {
730  TypeTestResolution &TTRes =
731  ExportSummary->getOrInsertTypeIdSummary(TypeId).TTRes;
732  TTRes.TheKind = TIL.TheKind;
733 
734  auto ExportGlobal = [&](StringRef Name, Constant *C) {
735  GlobalAlias *GA =
737  "__typeid_" + TypeId + "_" + Name, C, &M);
739  };
740 
741  if (TIL.TheKind != TypeTestResolution::Unsat)
742  ExportGlobal("global_addr", TIL.OffsetedGlobal);
743 
744  if (TIL.TheKind == TypeTestResolution::ByteArray ||
745  TIL.TheKind == TypeTestResolution::Inline ||
746  TIL.TheKind == TypeTestResolution::AllOnes) {
747  ExportGlobal("align", ConstantExpr::getIntToPtr(TIL.AlignLog2, Int8PtrTy));
748  ExportGlobal("size_m1", ConstantExpr::getIntToPtr(TIL.SizeM1, Int8PtrTy));
749 
750  uint64_t BitSize = cast<ConstantInt>(TIL.SizeM1)->getZExtValue() + 1;
751  if (TIL.TheKind == TypeTestResolution::Inline)
752  TTRes.SizeM1BitWidth = (BitSize <= 32) ? 5 : 6;
753  else
754  TTRes.SizeM1BitWidth = (BitSize <= 128) ? 7 : 32;
755  }
756 
757  if (TIL.TheKind == TypeTestResolution::ByteArray) {
758  ExportGlobal("byte_array", TIL.TheByteArray);
759  ExportGlobal("bit_mask", TIL.BitMask);
760  }
761 
762  if (TIL.TheKind == TypeTestResolution::Inline)
763  ExportGlobal("inline_bits",
764  ConstantExpr::getIntToPtr(TIL.InlineBits, Int8PtrTy));
765 }
766 
767 LowerTypeTestsModule::TypeIdLowering
768 LowerTypeTestsModule::importTypeId(StringRef TypeId) {
769  const TypeIdSummary *TidSummary = ImportSummary->getTypeIdSummary(TypeId);
770  if (!TidSummary)
771  return {}; // Unsat: no globals match this type id.
772  const TypeTestResolution &TTRes = TidSummary->TTRes;
773 
774  TypeIdLowering TIL;
775  TIL.TheKind = TTRes.TheKind;
776 
777  auto ImportGlobal = [&](StringRef Name, unsigned AbsWidth) {
778  Constant *C =
779  M.getOrInsertGlobal(("__typeid_" + TypeId + "_" + Name).str(), Int8Ty);
780  auto *GV = dyn_cast<GlobalVariable>(C);
781  // We only need to set metadata if the global is newly created, in which
782  // case it would not have hidden visibility.
783  if (!GV || GV->getVisibility() == GlobalValue::HiddenVisibility)
784  return C;
785 
787  auto SetAbsRange = [&](uint64_t Min, uint64_t Max) {
788  auto *MinC = ConstantAsMetadata::get(ConstantInt::get(IntPtrTy, Min));
789  auto *MaxC = ConstantAsMetadata::get(ConstantInt::get(IntPtrTy, Max));
791  MDNode::get(M.getContext(), {MinC, MaxC}));
792  };
793  if (AbsWidth == IntPtrTy->getBitWidth())
794  SetAbsRange(~0ull, ~0ull); // Full set.
795  else if (AbsWidth)
796  SetAbsRange(0, 1ull << AbsWidth);
797  return C;
798  };
799 
800  if (TIL.TheKind != TypeTestResolution::Unsat)
801  TIL.OffsetedGlobal = ImportGlobal("global_addr", 0);
802 
803  if (TIL.TheKind == TypeTestResolution::ByteArray ||
804  TIL.TheKind == TypeTestResolution::Inline ||
805  TIL.TheKind == TypeTestResolution::AllOnes) {
806  TIL.AlignLog2 = ConstantExpr::getPtrToInt(ImportGlobal("align", 8), Int8Ty);
807  TIL.SizeM1 = ConstantExpr::getPtrToInt(
808  ImportGlobal("size_m1", TTRes.SizeM1BitWidth), IntPtrTy);
809  }
810 
811  if (TIL.TheKind == TypeTestResolution::ByteArray) {
812  TIL.TheByteArray = ImportGlobal("byte_array", 0);
813  TIL.BitMask = ImportGlobal("bit_mask", 8);
814  }
815 
816  if (TIL.TheKind == TypeTestResolution::Inline)
817  TIL.InlineBits = ConstantExpr::getPtrToInt(
818  ImportGlobal("inline_bits", 1 << TTRes.SizeM1BitWidth),
819  TTRes.SizeM1BitWidth <= 5 ? Int32Ty : Int64Ty);
820 
821  return TIL;
822 }
823 
824 void LowerTypeTestsModule::importTypeTest(CallInst *CI) {
825  auto TypeIdMDVal = dyn_cast<MetadataAsValue>(CI->getArgOperand(1));
826  if (!TypeIdMDVal)
827  report_fatal_error("Second argument of llvm.type.test must be metadata");
828 
829  auto TypeIdStr = dyn_cast<MDString>(TypeIdMDVal->getMetadata());
830  if (!TypeIdStr)
832  "Second argument of llvm.type.test must be a metadata string");
833 
834  TypeIdLowering TIL = importTypeId(TypeIdStr->getString());
835  Value *Lowered = lowerTypeTestCall(TypeIdStr, CI, TIL);
836  CI->replaceAllUsesWith(Lowered);
837  CI->eraseFromParent();
838 }
839 
840 // ThinLTO backend: the function F has a jump table entry; update this module
841 // accordingly. isDefinition describes the type of the jump table entry.
842 void LowerTypeTestsModule::importFunction(Function *F, bool isDefinition) {
843  assert(F->getType()->getAddressSpace() == 0);
844 
845  // Declaration of a local function - nothing to do.
846  if (F->isDeclarationForLinker() && isDefinition)
847  return;
848 
850  std::string Name = F->getName();
851  Function *FDecl;
852 
853  if (F->isDeclarationForLinker() && !isDefinition) {
854  // Declaration of an external function.
856  Name + ".cfi_jt", &M);
858  } else if (isDefinition) {
859  F->setName(Name + ".cfi");
863  Name, &M);
864  FDecl->setVisibility(Visibility);
865  } else {
866  // Function definition without type metadata, where some other translation
867  // unit contained a declaration with type metadata. This normally happens
868  // during mixed CFI + non-CFI compilation. We do nothing with the function
869  // so that it is treated the same way as a function defined outside of the
870  // LTO unit.
871  return;
872  }
873 
874  if (F->isWeakForLinker())
875  replaceWeakDeclarationWithJumpTablePtr(F, FDecl);
876  else
877  F->replaceAllUsesWith(FDecl);
878 }
879 
880 void LowerTypeTestsModule::lowerTypeTestCalls(
881  ArrayRef<Metadata *> TypeIds, Constant *CombinedGlobalAddr,
882  const DenseMap<GlobalTypeMember *, uint64_t> &GlobalLayout) {
883  CombinedGlobalAddr = ConstantExpr::getBitCast(CombinedGlobalAddr, Int8PtrTy);
884 
885  // For each type identifier in this disjoint set...
886  for (Metadata *TypeId : TypeIds) {
887  // Build the bitset.
888  BitSetInfo BSI = buildBitSet(TypeId, GlobalLayout);
889  DEBUG({
890  if (auto MDS = dyn_cast<MDString>(TypeId))
891  dbgs() << MDS->getString() << ": ";
892  else
893  dbgs() << "<unnamed>: ";
894  BSI.print(dbgs());
895  });
896 
897  TypeIdLowering TIL;
898  TIL.OffsetedGlobal = ConstantExpr::getGetElementPtr(
899  Int8Ty, CombinedGlobalAddr, ConstantInt::get(IntPtrTy, BSI.ByteOffset)),
900  TIL.AlignLog2 = ConstantInt::get(Int8Ty, BSI.AlignLog2);
901  TIL.SizeM1 = ConstantInt::get(IntPtrTy, BSI.BitSize - 1);
902  if (BSI.isAllOnes()) {
903  TIL.TheKind = (BSI.BitSize == 1) ? TypeTestResolution::Single
905  } else if (BSI.BitSize <= 64) {
906  TIL.TheKind = TypeTestResolution::Inline;
907  uint64_t InlineBits = 0;
908  for (auto Bit : BSI.Bits)
909  InlineBits |= uint64_t(1) << Bit;
910  if (InlineBits == 0)
911  TIL.TheKind = TypeTestResolution::Unsat;
912  else
913  TIL.InlineBits = ConstantInt::get(
914  (BSI.BitSize <= 32) ? Int32Ty : Int64Ty, InlineBits);
915  } else {
916  TIL.TheKind = TypeTestResolution::ByteArray;
917  ++NumByteArraysCreated;
918  ByteArrayInfo *BAI = createByteArray(BSI);
919  TIL.TheByteArray = BAI->ByteArray;
920  TIL.BitMask = BAI->MaskGlobal;
921  }
922 
923  TypeIdUserInfo &TIUI = TypeIdUsers[TypeId];
924 
925  if (TIUI.IsExported)
926  exportTypeId(cast<MDString>(TypeId)->getString(), TIL);
927 
928  // Lower each call to llvm.type.test for this type identifier.
929  for (CallInst *CI : TIUI.CallSites) {
930  ++NumTypeTestCallsLowered;
931  Value *Lowered = lowerTypeTestCall(TypeId, CI, TIL);
932  CI->replaceAllUsesWith(Lowered);
933  CI->eraseFromParent();
934  }
935  }
936 }
937 
938 void LowerTypeTestsModule::verifyTypeMDNode(GlobalObject *GO, MDNode *Type) {
939  if (Type->getNumOperands() != 2)
940  report_fatal_error("All operands of type metadata must have 2 elements");
941 
942  if (GO->isThreadLocal())
943  report_fatal_error("Bit set element may not be thread-local");
944  if (isa<GlobalVariable>(GO) && GO->hasSection())
946  "A member of a type identifier may not have an explicit section");
947 
948  // FIXME: We previously checked that global var member of a type identifier
949  // must be a definition, but the IR linker may leave type metadata on
950  // declarations. We should restore this check after fixing PR31759.
951 
952  auto OffsetConstMD = dyn_cast<ConstantAsMetadata>(Type->getOperand(0));
953  if (!OffsetConstMD)
954  report_fatal_error("Type offset must be a constant");
955  auto OffsetInt = dyn_cast<ConstantInt>(OffsetConstMD->getValue());
956  if (!OffsetInt)
957  report_fatal_error("Type offset must be an integer constant");
958 }
959 
960 static const unsigned kX86JumpTableEntrySize = 8;
961 static const unsigned kARMJumpTableEntrySize = 4;
962 
963 unsigned LowerTypeTestsModule::getJumpTableEntrySize() {
964  switch (Arch) {
965  case Triple::x86:
966  case Triple::x86_64:
967  return kX86JumpTableEntrySize;
968  case Triple::arm:
969  case Triple::thumb:
970  case Triple::aarch64:
971  return kARMJumpTableEntrySize;
972  default:
973  report_fatal_error("Unsupported architecture for jump tables");
974  }
975 }
976 
977 // Create a jump table entry for the target. This consists of an instruction
978 // sequence containing a relative branch to Dest. Appends inline asm text,
979 // constraints and arguments to AsmOS, ConstraintOS and AsmArgs.
980 void LowerTypeTestsModule::createJumpTableEntry(
981  raw_ostream &AsmOS, raw_ostream &ConstraintOS,
982  SmallVectorImpl<Value *> &AsmArgs, Function *Dest) {
983  unsigned ArgIndex = AsmArgs.size();
984 
985  if (Arch == Triple::x86 || Arch == Triple::x86_64) {
986  AsmOS << "jmp ${" << ArgIndex << ":c}@plt\n";
987  AsmOS << "int3\nint3\nint3\n";
988  } else if (Arch == Triple::arm || Arch == Triple::aarch64) {
989  AsmOS << "b $" << ArgIndex << "\n";
990  } else if (Arch == Triple::thumb) {
991  AsmOS << "b.w $" << ArgIndex << "\n";
992  } else {
993  report_fatal_error("Unsupported architecture for jump tables");
994  }
995 
996  ConstraintOS << (ArgIndex > 0 ? ",s" : "s");
997  AsmArgs.push_back(Dest);
998 }
999 
1000 Type *LowerTypeTestsModule::getJumpTableEntryType() {
1001  return ArrayType::get(Int8Ty, getJumpTableEntrySize());
1002 }
1003 
1004 /// Given a disjoint set of type identifiers and functions, build the bit sets
1005 /// and lower the llvm.type.test calls, architecture dependently.
1006 void LowerTypeTestsModule::buildBitSetsFromFunctions(
1008  if (Arch == Triple::x86 || Arch == Triple::x86_64 || Arch == Triple::arm ||
1009  Arch == Triple::thumb || Arch == Triple::aarch64)
1010  buildBitSetsFromFunctionsNative(TypeIds, Functions);
1011  else if (Arch == Triple::wasm32 || Arch == Triple::wasm64)
1012  buildBitSetsFromFunctionsWASM(TypeIds, Functions);
1013  else
1014  report_fatal_error("Unsupported architecture for jump tables");
1015 }
1016 
1017 void LowerTypeTestsModule::moveInitializerToModuleConstructor(
1018  GlobalVariable *GV) {
1019  if (WeakInitializerFn == nullptr) {
1020  WeakInitializerFn = Function::Create(
1022  /* IsVarArg */ false),
1023  GlobalValue::InternalLinkage, "__cfi_global_var_init", &M);
1024  BasicBlock *BB =
1025  BasicBlock::Create(M.getContext(), "entry", WeakInitializerFn);
1026  ReturnInst::Create(M.getContext(), BB);
1027  WeakInitializerFn->setSection(
1028  ObjectFormat == Triple::MachO
1029  ? "__TEXT,__StaticInit,regular,pure_instructions"
1030  : ".text.startup");
1031  // This code is equivalent to relocation application, and should run at the
1032  // earliest possible time (i.e. with the highest priority).
1033  appendToGlobalCtors(M, WeakInitializerFn, /* Priority */ 0);
1034  }
1035 
1036  IRBuilder<> IRB(WeakInitializerFn->getEntryBlock().getTerminator());
1037  GV->setConstant(false);
1038  IRB.CreateAlignedStore(GV->getInitializer(), GV, GV->getAlignment());
1040 }
1041 
1042 void LowerTypeTestsModule::findGlobalVariableUsersOf(
1044  for (auto *U : C->users()){
1045  if (auto *GV = dyn_cast<GlobalVariable>(U))
1046  Out.insert(GV);
1047  else if (auto *C2 = dyn_cast<Constant>(U))
1048  findGlobalVariableUsersOf(C2, Out);
1049  }
1050 }
1051 
1052 // Replace all uses of F with (F ? JT : 0).
1053 void LowerTypeTestsModule::replaceWeakDeclarationWithJumpTablePtr(
1054  Function *F, Constant *JT) {
1055  // The target expression can not appear in a constant initializer on most
1056  // (all?) targets. Switch to a runtime initializer.
1057  SmallSetVector<GlobalVariable *, 8> GlobalVarUsers;
1058  findGlobalVariableUsersOf(F, GlobalVarUsers);
1059  for (auto GV : GlobalVarUsers)
1060  moveInitializerToModuleConstructor(GV);
1061 
1062  // Can not RAUW F with an expression that uses F. Replace with a temporary
1063  // placeholder first.
1064  Function *PlaceholderFn =
1065  Function::Create(cast<FunctionType>(F->getValueType()),
1067  F->replaceAllUsesWith(PlaceholderFn);
1068 
1073  PlaceholderFn->replaceAllUsesWith(Target);
1074  PlaceholderFn->eraseFromParent();
1075 }
1076 
1077 void LowerTypeTestsModule::createJumpTable(
1078  Function *F, ArrayRef<GlobalTypeMember *> Functions) {
1079  std::string AsmStr, ConstraintStr;
1080  raw_string_ostream AsmOS(AsmStr), ConstraintOS(ConstraintStr);
1081  SmallVector<Value *, 16> AsmArgs;
1082  AsmArgs.reserve(Functions.size() * 2);
1083 
1084  for (unsigned I = 0; I != Functions.size(); ++I)
1085  createJumpTableEntry(AsmOS, ConstraintOS, AsmArgs,
1086  cast<Function>(Functions[I]->getGlobal()));
1087 
1088  // Try to emit the jump table at the end of the text segment.
1089  // Jump table must come after __cfi_check in the cross-dso mode.
1090  // FIXME: this magic section name seems to do the trick.
1091  F->setSection(ObjectFormat == Triple::MachO
1092  ? "__TEXT,__text,regular,pure_instructions"
1093  : ".text.cfi");
1094  // Align the whole table by entry size.
1095  F->setAlignment(getJumpTableEntrySize());
1096  // Skip prologue.
1097  // Disabled on win32 due to https://llvm.org/bugs/show_bug.cgi?id=28641#c3.
1098  // Luckily, this function does not get any prologue even without the
1099  // attribute.
1100  if (OS != Triple::Win32)
1101  F->addFnAttr(llvm::Attribute::Naked);
1102  // Thumb jump table assembly needs Thumb2. The following attribute is added by
1103  // Clang for -march=armv7.
1104  if (Arch == Triple::thumb)
1105  F->addFnAttr("target-cpu", "cortex-a8");
1106 
1107  BasicBlock *BB = BasicBlock::Create(M.getContext(), "entry", F);
1108  IRBuilder<> IRB(BB);
1109 
1110  SmallVector<Type *, 16> ArgTypes;
1111  ArgTypes.reserve(AsmArgs.size());
1112  for (const auto &Arg : AsmArgs)
1113  ArgTypes.push_back(Arg->getType());
1114  InlineAsm *JumpTableAsm =
1115  InlineAsm::get(FunctionType::get(IRB.getVoidTy(), ArgTypes, false),
1116  AsmOS.str(), ConstraintOS.str(),
1117  /*hasSideEffects=*/true);
1118 
1119  IRB.CreateCall(JumpTableAsm, AsmArgs);
1120  IRB.CreateUnreachable();
1121 }
1122 
1123 /// Given a disjoint set of type identifiers and functions, build a jump table
1124 /// for the functions, build the bit sets and lower the llvm.type.test calls.
1125 void LowerTypeTestsModule::buildBitSetsFromFunctionsNative(
1127  // Unlike the global bitset builder, the function bitset builder cannot
1128  // re-arrange functions in a particular order and base its calculations on the
1129  // layout of the functions' entry points, as we have no idea how large a
1130  // particular function will end up being (the size could even depend on what
1131  // this pass does!) Instead, we build a jump table, which is a block of code
1132  // consisting of one branch instruction for each of the functions in the bit
1133  // set that branches to the target function, and redirect any taken function
1134  // addresses to the corresponding jump table entry. In the object file's
1135  // symbol table, the symbols for the target functions also refer to the jump
1136  // table entries, so that addresses taken outside the module will pass any
1137  // verification done inside the module.
1138  //
1139  // In more concrete terms, suppose we have three functions f, g, h which are
1140  // of the same type, and a function foo that returns their addresses:
1141  //
1142  // f:
1143  // mov 0, %eax
1144  // ret
1145  //
1146  // g:
1147  // mov 1, %eax
1148  // ret
1149  //
1150  // h:
1151  // mov 2, %eax
1152  // ret
1153  //
1154  // foo:
1155  // mov f, %eax
1156  // mov g, %edx
1157  // mov h, %ecx
1158  // ret
1159  //
1160  // We output the jump table as module-level inline asm string. The end result
1161  // will (conceptually) look like this:
1162  //
1163  // f = .cfi.jumptable
1164  // g = .cfi.jumptable + 4
1165  // h = .cfi.jumptable + 8
1166  // .cfi.jumptable:
1167  // jmp f.cfi ; 5 bytes
1168  // int3 ; 1 byte
1169  // int3 ; 1 byte
1170  // int3 ; 1 byte
1171  // jmp g.cfi ; 5 bytes
1172  // int3 ; 1 byte
1173  // int3 ; 1 byte
1174  // int3 ; 1 byte
1175  // jmp h.cfi ; 5 bytes
1176  // int3 ; 1 byte
1177  // int3 ; 1 byte
1178  // int3 ; 1 byte
1179  //
1180  // f.cfi:
1181  // mov 0, %eax
1182  // ret
1183  //
1184  // g.cfi:
1185  // mov 1, %eax
1186  // ret
1187  //
1188  // h.cfi:
1189  // mov 2, %eax
1190  // ret
1191  //
1192  // foo:
1193  // mov f, %eax
1194  // mov g, %edx
1195  // mov h, %ecx
1196  // ret
1197  //
1198  // Because the addresses of f, g, h are evenly spaced at a power of 2, in the
1199  // normal case the check can be carried out using the same kind of simple
1200  // arithmetic that we normally use for globals.
1201 
1202  // FIXME: find a better way to represent the jumptable in the IR.
1203  assert(!Functions.empty());
1204 
1205  // Build a simple layout based on the regular layout of jump tables.
1207  unsigned EntrySize = getJumpTableEntrySize();
1208  for (unsigned I = 0; I != Functions.size(); ++I)
1209  GlobalLayout[Functions[I]] = I * EntrySize;
1210 
1211  Function *JumpTableFn =
1213  /* IsVarArg */ false),
1214  GlobalValue::PrivateLinkage, ".cfi.jumptable", &M);
1216  ArrayType::get(getJumpTableEntryType(), Functions.size());
1217  auto JumpTable =
1218  ConstantExpr::getPointerCast(JumpTableFn, JumpTableType->getPointerTo(0));
1219 
1220  lowerTypeTestCalls(TypeIds, JumpTable, GlobalLayout);
1221 
1222  // Build aliases pointing to offsets into the jump table, and replace
1223  // references to the original functions with references to the aliases.
1224  for (unsigned I = 0; I != Functions.size(); ++I) {
1225  Function *F = cast<Function>(Functions[I]->getGlobal());
1226  bool IsDefinition = Functions[I]->isDefinition();
1227 
1228  Constant *CombinedGlobalElemPtr = ConstantExpr::getBitCast(
1230  JumpTableType, JumpTable,
1232  ConstantInt::get(IntPtrTy, I)}),
1233  F->getType());
1234  if (Functions[I]->isExported()) {
1235  if (IsDefinition) {
1236  ExportSummary->cfiFunctionDefs().insert(F->getName());
1237  } else {
1238  GlobalAlias *JtAlias = GlobalAlias::create(
1240  F->getName() + ".cfi_jt", CombinedGlobalElemPtr, &M);
1242  ExportSummary->cfiFunctionDecls().insert(F->getName());
1243  }
1244  }
1245  if (!IsDefinition) {
1246  if (F->isWeakForLinker())
1247  replaceWeakDeclarationWithJumpTablePtr(F, CombinedGlobalElemPtr);
1248  else
1249  F->replaceAllUsesWith(CombinedGlobalElemPtr);
1250  } else {
1251  assert(F->getType()->getAddressSpace() == 0);
1252 
1253  GlobalAlias *FAlias = GlobalAlias::create(
1254  F->getValueType(), 0, F->getLinkage(), "", CombinedGlobalElemPtr, &M);
1255  FAlias->setVisibility(F->getVisibility());
1256  FAlias->takeName(F);
1257  if (FAlias->hasName())
1258  F->setName(FAlias->getName() + ".cfi");
1259  F->replaceAllUsesWith(FAlias);
1260  }
1261  if (!F->isDeclarationForLinker())
1263  }
1264 
1265  createJumpTable(JumpTableFn, Functions);
1266 }
1267 
1268 /// Assign a dummy layout using an incrementing counter, tag each function
1269 /// with its index represented as metadata, and lower each type test to an
1270 /// integer range comparison. During generation of the indirect function call
1271 /// table in the backend, it will assign the given indexes.
1272 /// Note: Dynamic linking is not supported, as the WebAssembly ABI has not yet
1273 /// been finalized.
1274 void LowerTypeTestsModule::buildBitSetsFromFunctionsWASM(
1276  assert(!Functions.empty());
1277 
1278  // Build consecutive monotonic integer ranges for each call target set
1280 
1281  for (GlobalTypeMember *GTM : Functions) {
1282  Function *F = cast<Function>(GTM->getGlobal());
1283 
1284  // Skip functions that are not address taken, to avoid bloating the table
1285  if (!F->hasAddressTaken())
1286  continue;
1287 
1288  // Store metadata with the index for each function
1289  MDNode *MD = MDNode::get(F->getContext(),
1291  ConstantInt::get(Int64Ty, IndirectIndex))));
1292  F->setMetadata("wasm.index", MD);
1293 
1294  // Assign the counter value
1295  GlobalLayout[GTM] = IndirectIndex++;
1296  }
1297 
1298  // The indirect function table index space starts at zero, so pass a NULL
1299  // pointer as the subtracted "jump table" offset.
1300  lowerTypeTestCalls(TypeIds, ConstantPointerNull::get(Int32PtrTy),
1301  GlobalLayout);
1302 }
1303 
1304 void LowerTypeTestsModule::buildBitSetsFromDisjointSet(
1307  for (unsigned I = 0; I != TypeIds.size(); ++I)
1308  TypeIdIndices[TypeIds[I]] = I;
1309 
1310  // For each type identifier, build a set of indices that refer to members of
1311  // the type identifier.
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()) {
1316  // Type = { offset, type identifier }
1317  unsigned TypeIdIndex = TypeIdIndices[Type->getOperand(1)];
1318  TypeMembers[TypeIdIndex].insert(GlobalIndex);
1319  }
1320  GlobalIndex++;
1321  }
1322 
1323  // Order the sets of indices by size. The GlobalLayoutBuilder works best
1324  // when given small index sets first.
1325  std::stable_sort(
1326  TypeMembers.begin(), TypeMembers.end(),
1327  [](const std::set<uint64_t> &O1, const std::set<uint64_t> &O2) {
1328  return O1.size() < O2.size();
1329  });
1330 
1331  // Create a GlobalLayoutBuilder and provide it with index sets as layout
1332  // fragments. The GlobalLayoutBuilder tries to lay out members of fragments as
1333  // close together as possible.
1334  GlobalLayoutBuilder GLB(Globals.size());
1335  for (auto &&MemSet : TypeMembers)
1336  GLB.addFragment(MemSet);
1337 
1338  // Build the bitsets from this disjoint set.
1339  if (Globals.empty() || isa<GlobalVariable>(Globals[0]->getGlobal())) {
1340  // Build a vector of global variables with the computed layout.
1341  std::vector<GlobalTypeMember *> OrderedGVs(Globals.size());
1342  auto OGI = OrderedGVs.begin();
1343  for (auto &&F : GLB.Fragments) {
1344  for (auto &&Offset : F) {
1345  auto GV = dyn_cast<GlobalVariable>(Globals[Offset]->getGlobal());
1346  if (!GV)
1347  report_fatal_error("Type identifier may not contain both global "
1348  "variables and functions");
1349  *OGI++ = Globals[Offset];
1350  }
1351  }
1352 
1353  buildBitSetsFromGlobalVariables(TypeIds, OrderedGVs);
1354  } else {
1355  // Build a vector of functions with the computed layout.
1356  std::vector<GlobalTypeMember *> OrderedFns(Globals.size());
1357  auto OFI = OrderedFns.begin();
1358  for (auto &&F : GLB.Fragments) {
1359  for (auto &&Offset : F) {
1360  auto Fn = dyn_cast<Function>(Globals[Offset]->getGlobal());
1361  if (!Fn)
1362  report_fatal_error("Type identifier may not contain both global "
1363  "variables and functions");
1364  *OFI++ = Globals[Offset];
1365  }
1366  }
1367 
1368  buildBitSetsFromFunctions(TypeIds, OrderedFns);
1369  }
1370 }
1371 
1372 /// Lower all type tests in this module.
1373 LowerTypeTestsModule::LowerTypeTestsModule(
1374  Module &M, ModuleSummaryIndex *ExportSummary,
1375  const ModuleSummaryIndex *ImportSummary)
1376  : M(M), ExportSummary(ExportSummary), ImportSummary(ImportSummary) {
1377  assert(!(ExportSummary && ImportSummary));
1378  Triple TargetTriple(M.getTargetTriple());
1379  Arch = TargetTriple.getArch();
1380  OS = TargetTriple.getOS();
1381  ObjectFormat = TargetTriple.getObjectFormat();
1382 }
1383 
1384 bool LowerTypeTestsModule::runForTesting(Module &M) {
1385  ModuleSummaryIndex Summary;
1386 
1387  // Handle the command-line summary arguments. This code is for testing
1388  // purposes only, so we handle errors directly.
1389  if (!ClReadSummary.empty()) {
1390  ExitOnError ExitOnErr("-lowertypetests-read-summary: " + ClReadSummary +
1391  ": ");
1392  auto ReadSummaryFile =
1393  ExitOnErr(errorOrToExpected(MemoryBuffer::getFile(ClReadSummary)));
1394 
1395  yaml::Input In(ReadSummaryFile->getBuffer());
1396  In >> Summary;
1397  ExitOnErr(errorCodeToError(In.error()));
1398  }
1399 
1400  bool Changed =
1401  LowerTypeTestsModule(
1402  M, ClSummaryAction == PassSummaryAction::Export ? &Summary : nullptr,
1403  ClSummaryAction == PassSummaryAction::Import ? &Summary : nullptr)
1404  .lower();
1405 
1406  if (!ClWriteSummary.empty()) {
1407  ExitOnError ExitOnErr("-lowertypetests-write-summary: " + ClWriteSummary +
1408  ": ");
1409  std::error_code EC;
1411  ExitOnErr(errorCodeToError(EC));
1412 
1413  yaml::Output Out(OS);
1414  Out << Summary;
1415  }
1416 
1417  return Changed;
1418 }
1419 
1420 bool LowerTypeTestsModule::lower() {
1421  Function *TypeTestFunc =
1422  M.getFunction(Intrinsic::getName(Intrinsic::type_test));
1423  if ((!TypeTestFunc || TypeTestFunc->use_empty()) && !ExportSummary &&
1424  !ImportSummary)
1425  return false;
1426 
1427  if (ImportSummary) {
1428  if (TypeTestFunc) {
1429  for (auto UI = TypeTestFunc->use_begin(), UE = TypeTestFunc->use_end();
1430  UI != UE;) {
1431  auto *CI = cast<CallInst>((*UI++).getUser());
1432  importTypeTest(CI);
1433  }
1434  }
1435 
1438  for (auto &F : M) {
1439  // CFI functions are either external, or promoted. A local function may
1440  // have the same name, but it's not the one we are looking for.
1441  if (F.hasLocalLinkage())
1442  continue;
1443  if (ImportSummary->cfiFunctionDefs().count(F.getName()))
1444  Defs.push_back(&F);
1445  else if (ImportSummary->cfiFunctionDecls().count(F.getName()))
1446  Decls.push_back(&F);
1447  }
1448 
1449  for (auto F : Defs)
1450  importFunction(F, /*isDefinition*/ true);
1451  for (auto F : Decls)
1452  importFunction(F, /*isDefinition*/ false);
1453 
1454  return true;
1455  }
1456 
1457  // Equivalence class set containing type identifiers and the globals that
1458  // reference them. This is used to partition the set of type identifiers in
1459  // the module into disjoint sets.
1461  GlobalClassesTy;
1462  GlobalClassesTy GlobalClasses;
1463 
1464  // Verify the type metadata and build a few data structures to let us
1465  // efficiently enumerate the type identifiers associated with a global:
1466  // a list of GlobalTypeMembers (a GlobalObject stored alongside a vector
1467  // of associated type metadata) and a mapping from type identifiers to their
1468  // list of GlobalTypeMembers and last observed index in the list of globals.
1469  // The indices will be used later to deterministically order the list of type
1470  // identifiers.
1472  struct TIInfo {
1473  unsigned Index;
1474  std::vector<GlobalTypeMember *> RefGlobals;
1475  };
1477  unsigned I = 0;
1479 
1480  struct ExportedFunctionInfo {
1481  CfiFunctionLinkage Linkage;
1482  MDNode *FuncMD; // {name, linkage, type[, type...]}
1483  };
1485  if (ExportSummary) {
1486  NamedMDNode *CfiFunctionsMD = M.getNamedMetadata("cfi.functions");
1487  if (CfiFunctionsMD) {
1488  for (auto FuncMD : CfiFunctionsMD->operands()) {
1489  assert(FuncMD->getNumOperands() >= 2);
1490  StringRef FunctionName =
1491  cast<MDString>(FuncMD->getOperand(0))->getString();
1492  if (!ExportSummary->isGUIDLive(GlobalValue::getGUID(
1493  GlobalValue::dropLLVMManglingEscape(FunctionName))))
1494  continue;
1495  CfiFunctionLinkage Linkage = static_cast<CfiFunctionLinkage>(
1496  cast<ConstantAsMetadata>(FuncMD->getOperand(1))
1497  ->getValue()
1498  ->getUniqueInteger()
1499  .getZExtValue());
1500  auto P = ExportedFunctions.insert({FunctionName, {Linkage, FuncMD}});
1501  if (!P.second && P.first->second.Linkage != CFL_Definition)
1502  P.first->second = {Linkage, FuncMD};
1503  }
1504 
1505  for (const auto &P : ExportedFunctions) {
1506  StringRef FunctionName = P.first;
1507  CfiFunctionLinkage Linkage = P.second.Linkage;
1508  MDNode *FuncMD = P.second.FuncMD;
1509  Function *F = M.getFunction(FunctionName);
1510  if (!F)
1511  F = Function::Create(
1512  FunctionType::get(Type::getVoidTy(M.getContext()), false),
1513  GlobalVariable::ExternalLinkage, FunctionName, &M);
1514 
1515  if (Linkage == CFL_Definition)
1516  F->eraseMetadata(LLVMContext::MD_type);
1517 
1518  if (F->isDeclaration()) {
1519  if (Linkage == CFL_WeakDeclaration)
1520  F->setLinkage(GlobalValue::ExternalWeakLinkage);
1521 
1523  for (unsigned I = 2; I < FuncMD->getNumOperands(); ++I)
1524  F->addMetadata(LLVMContext::MD_type,
1525  *cast<MDNode>(FuncMD->getOperand(I).get()));
1526  }
1527  }
1528  }
1529  }
1530 
1531  for (GlobalObject &GO : M.global_objects()) {
1532  if (isa<GlobalVariable>(GO) && GO.isDeclarationForLinker())
1533  continue;
1534 
1535  Types.clear();
1536  GO.getMetadata(LLVMContext::MD_type, Types);
1537  if (Types.empty())
1538  continue;
1539 
1540  bool IsDefinition = !GO.isDeclarationForLinker();
1541  bool IsExported = false;
1542  if (isa<Function>(GO) && ExportedFunctions.count(GO.getName())) {
1543  IsDefinition |= ExportedFunctions[GO.getName()].Linkage == CFL_Definition;
1544  IsExported = true;
1545  }
1546 
1547  auto *GTM =
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)];
1552  Info.Index = ++I;
1553  Info.RefGlobals.push_back(GTM);
1554  }
1555  }
1556 
1557  auto AddTypeIdUse = [&](Metadata *TypeId) -> TypeIdUserInfo & {
1558  // Add the call site to the list of call sites for this type identifier. We
1559  // also use TypeIdUsers to keep track of whether we have seen this type
1560  // identifier before. If we have, we don't need to re-add the referenced
1561  // globals to the equivalence class.
1562  auto Ins = TypeIdUsers.insert({TypeId, {}});
1563  if (Ins.second) {
1564  // Add the type identifier to the equivalence class.
1565  GlobalClassesTy::iterator GCI = GlobalClasses.insert(TypeId);
1566  GlobalClassesTy::member_iterator CurSet = GlobalClasses.findLeader(GCI);
1567 
1568  // Add the referenced globals to the type identifier's equivalence class.
1569  for (GlobalTypeMember *GTM : TypeIdInfo[TypeId].RefGlobals)
1570  CurSet = GlobalClasses.unionSets(
1571  CurSet, GlobalClasses.findLeader(GlobalClasses.insert(GTM)));
1572  }
1573 
1574  return Ins.first->second;
1575  };
1576 
1577  if (TypeTestFunc) {
1578  for (const Use &U : TypeTestFunc->uses()) {
1579  auto CI = cast<CallInst>(U.getUser());
1580 
1581  auto TypeIdMDVal = dyn_cast<MetadataAsValue>(CI->getArgOperand(1));
1582  if (!TypeIdMDVal)
1583  report_fatal_error("Second argument of llvm.type.test must be metadata");
1584  auto TypeId = TypeIdMDVal->getMetadata();
1585  AddTypeIdUse(TypeId).CallSites.push_back(CI);
1586  }
1587  }
1588 
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(
1594  TypeId);
1595  }
1596 
1597  for (auto &P : *ExportSummary) {
1598  for (auto &S : P.second.SummaryList) {
1599  auto *FS = dyn_cast<FunctionSummary>(S.get());
1600  if (!FS || !ExportSummary->isGlobalValueLive(FS))
1601  continue;
1602  for (GlobalValue::GUID G : FS->type_tests())
1603  for (Metadata *MD : MetadataByGUID[G])
1604  AddTypeIdUse(MD).IsExported = true;
1605  }
1606  }
1607  }
1608 
1609  if (GlobalClasses.empty())
1610  return false;
1611 
1612  // Build a list of disjoint sets ordered by their maximum global index for
1613  // determinism.
1614  std::vector<std::pair<GlobalClassesTy::iterator, unsigned>> Sets;
1615  for (GlobalClassesTy::iterator I = GlobalClasses.begin(),
1616  E = GlobalClasses.end();
1617  I != E; ++I) {
1618  if (!I->isLeader())
1619  continue;
1620  ++NumTypeIdDisjointSets;
1621 
1622  unsigned MaxIndex = 0;
1623  for (GlobalClassesTy::member_iterator MI = GlobalClasses.member_begin(I);
1624  MI != GlobalClasses.member_end(); ++MI) {
1625  if ((*MI).is<Metadata *>())
1626  MaxIndex = std::max(MaxIndex, TypeIdInfo[MI->get<Metadata *>()].Index);
1627  }
1628  Sets.emplace_back(I, MaxIndex);
1629  }
1630  std::sort(Sets.begin(), Sets.end(),
1631  [](const std::pair<GlobalClassesTy::iterator, unsigned> &S1,
1632  const std::pair<GlobalClassesTy::iterator, unsigned> &S2) {
1633  return S1.second < S2.second;
1634  });
1635 
1636  // For each disjoint set we found...
1637  for (const auto &S : Sets) {
1638  // Build the list of type identifiers in this disjoint set.
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) {
1644  if ((*MI).is<Metadata *>())
1645  TypeIds.push_back(MI->get<Metadata *>());
1646  else
1647  Globals.push_back(MI->get<GlobalTypeMember *>());
1648  }
1649 
1650  // Order type identifiers by global index for determinism. This ordering is
1651  // stable as there is a one-to-one mapping between metadata and indices.
1652  std::sort(TypeIds.begin(), TypeIds.end(), [&](Metadata *M1, Metadata *M2) {
1653  return TypeIdInfo[M1].Index < TypeIdInfo[M2].Index;
1654  });
1655 
1656  // Build bitsets for this disjoint set.
1657  buildBitSetsFromDisjointSet(TypeIds, Globals);
1658  }
1659 
1660  allocateByteArrays();
1661 
1662  return true;
1663 }
1664 
1665 PreservedAnalyses LowerTypeTestsPass::run(Module &M,
1666  ModuleAnalysisManager &AM) {
1667  bool Changed = LowerTypeTestsModule(M, /*ExportSummary=*/nullptr,
1668  /*ImportSummary=*/nullptr)
1669  .lower();
1670  if (!Changed)
1671  return PreservedAnalyses::all();
1672  return PreservedAnalyses::none();
1673 }
void setVisibility(VisibilityTypes V)
Definition: GlobalValue.h:226
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.
Definition: Instruction.cpp:69
void push_back(const T &Elt)
Definition: SmallVector.h:211
use_iterator use_end()
Definition: Value.h:342
A parsed version of the target data layout string in and methods for querying it. ...
Definition: DataLayout.h:109
LinkageTypes getLinkage() const
Definition: GlobalValue.h:430
static ConstantInt * getFalse(LLVMContext &Context)
Definition: Constants.cpp:523
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()
Definition: Value.h:350
This class is used to build a byte array containing overlapping bit sets.
static IntegerType * getInt1Ty(LLVMContext &C)
Definition: Type.cpp:173
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. ...
Definition: Function.cpp:194
VisibilityTypes getVisibility() const
Definition: GlobalValue.h:220
GCNRegPressure max(const GCNRegPressure &P1, const GCNRegPressure &P2)
Value * CreateICmpNE(Value *LHS, Value *RHS, const Twine &Name="")
Definition: IRBuilder.h:1549
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.
Definition: IRBuilder.h:1391
NodeTy * getNextNode()
Get the next node, or nullptr for the list tail.
Definition: ilist_node.h:289
STATISTIC(NumFunctions,"Total number of functions")
uint64_t GUID
Declare a type to represent a global unique identifier for a global value.
Definition: GlobalValue.h:472
LLVM_ATTRIBUTE_NORETURN void report_fatal_error(Error Err, bool gen_crash_diag=true)
Report a serious error, calling any installed error handler.
Definition: Error.cpp:103
A Module instance is used to store all the information related to an LLVM module. ...
Definition: Module.h:63
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.
Definition: Constants.h:460
Unsatisfiable type (i.e. no global has this type metadata)
unsigned getNumOperands() const
Return number of MDNode operands.
Definition: Metadata.h:1073
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)
Definition: Constants.cpp:1237
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.
iterator end() const
Definition: ArrayRef.h:138
DataLayout DL
Helper for check-and-exit error handling.
Definition: Error.h:990
Type * getValueType() const
Definition: GlobalValue.h:262
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.
Definition: Constants.h:1115
static Constant * getIntToPtr(Constant *C, Type *Ty, bool OnlyIfReduced=false)
Definition: Constants.cpp:1665
CfiFunctionLinkage
The type of CFI jumptable needed for a function.
Like Internal, but omit from symbol table.
Definition: GlobalValue.h:57
Externally visible function.
Definition: GlobalValue.h:49
Metadata node.
Definition: Metadata.h:862
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...
Definition: MathExtras.h:677
unsigned getAddressSpace() const
Return the address space of the Pointer type.
Definition: DerivedTypes.h:495
ELFYAML::ELF_STV Visibility
Definition: ELFYAML.cpp:662
static IntegerType * getInt64Ty(LLVMContext &C)
Definition: Type.cpp:177
Hexagon Common GEP
static Constant * getSub(Constant *C1, Constant *C2, bool HasNUW=false, bool HasNSW=false)
Definition: Constants.cpp:2126
Kind
Specifies which kind of type check we should emit for this byte array.
Value * CreateICmpULE(Value *LHS, Value *RHS, const Twine &Name="")
Definition: IRBuilder.h:1561
void reserve(size_type N)
Definition: SmallVector.h:377
void setAlignment(unsigned Align)
Definition: Globals.cpp:110
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.
Definition: Module.h:233
std::vector< uint64_t > FragmentMap
Mapping from object index to fragment index.
TypeTestResolution TTRes
static Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
Definition: Constants.cpp:207
StringRef getName() const
Return a constant reference to the value's name.
Definition: Value.cpp:218
Export information to summary.
Metadata * get() const
Definition: Metadata.h:720
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)
Definition: DenseMap.h:176
Used to lazily calculate structure layout information for a target machine, based on the DataLayout s...
Definition: DataLayout.h:493
A tuple of MDNodes.
Definition: Metadata.h:1316
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...
Definition: DataLayout.cpp:562
ArrayRef< T > makeArrayRef(const T &OneElt)
Construct an ArrayRef from a single element.
Definition: ArrayRef.h:451
void setInitializer(Constant *InitVal)
setInitializer - Sets the initializer for this global variable, removing any existing initializer if ...
Definition: Globals.cpp:339
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...
Definition: Constants.cpp:2396
Class to represent struct types.
Definition: DerivedTypes.h:201
A Use represents the edge between a Value definition and its users.
Definition: Use.h:56
static const unsigned kX86JumpTableEntrySize
The returned value is undefined.
Definition: MathExtras.h:38
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition: IRBuilder.h:664
static StringRef getName(Value *V)
void setName(const Twine &Name)
Change the name of the value.
Definition: Value.cpp:284
LLVM_NODISCARD bool empty() const
Definition: SmallVector.h:60
The Input class is used to parse a yaml document into in-memory structs and vectors.
Definition: YAMLTraits.h:1108
static Constant * getZExt(Constant *C, Type *Ty, bool OnlyIfReduced=false)
Definition: Constants.cpp:1570
#define F(x, y, z)
Definition: MD5.cpp:55
bool insert(const value_type &X)
Insert a new element into the SetVector.
Definition: SetVector.h:142
unsigned getAlignment() const
Definition: GlobalObject.h:59
Class to represent array types.
Definition: DerivedTypes.h:369
VisibilityTypes
An enumeration for the kinds of visibility of global values.
Definition: GlobalValue.h:63
static Constant * getSelect(Constant *C, Constant *V1, Constant *V2, Type *OnlyIfReducedTy=nullptr)
Select constant expr.
Definition: Constants.cpp:1854
static FunctionType * get(Type *Result, ArrayRef< Type * > Params, bool isVarArg)
This static method is the primary way of constructing a FunctionType.
Definition: Type.cpp:297
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
Definition: APInt.h:33
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)
Definition: IRBuilder.h:911
ArchType getArch() const
getArch - Get the parsed architecture type of this triple.
Definition: Triple.h:281
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition: Value.cpp:428
Class to hold module path string table and global value map, and encapsulate methods for operating on...
static ConstantAsMetadata * get(Constant *C)
Definition: Metadata.h:408
iterator_range< op_iterator > operands()
Definition: Metadata.h:1408
size_t size() const
size - Get the array size.
Definition: ArrayRef.h:149
const char * Name
void SetInsertPoint(BasicBlock *TheBB)
This specifies that created instructions should be appended to the end of the specified block...
Definition: IRBuilder.h:128
Class to represent pointers.
Definition: DerivedTypes.h:467
static PreservedAnalyses none()
Convenience factory function for the empty preserved set.
Definition: PassManager.h:156
Value * CreateOr(Value *LHS, Value *RHS, const Twine &Name="")
Definition: IRBuilder.h:1079
Function * getFunction(StringRef Name) const
Look up the specified function in the module symbol table.
Definition: Module.cpp:172
static bool isWeakForLinker(LinkageTypes Linkage)
Whether the definition of this global may be replaced at link time.
Definition: GlobalValue.h:350
static Constant * getBitCast(Constant *C, Type *Ty, bool OnlyIfReduced=false)
Definition: Constants.cpp:1678
bool hasSection() const
Check if this global has a custom object file section.
Definition: GlobalObject.h:82
ValuesClass values(OptsTy...Options)
Helper to build a ValuesClass by forwarding a variable number of arguments as an initializer list to ...
Definition: CommandLine.h:621
ExternalWeak linkage description.
Definition: GlobalValue.h:58
T Min(T a, T b)
Definition: FuzzerDefs.h:90
LoadInst * CreateLoad(Value *Ptr, const char *Name)
Definition: IRBuilder.h:1164
#define P(N)
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:401
static Constant * getInBoundsGetElementPtr(Type *Ty, Constant *C, ArrayRef< Constant * > IdxList)
Create an "inbounds" getelementptr.
Definition: Constants.h:1142
A set of analyses that are preserved following a run of a transformation pass.
Definition: PassManager.h:153
static ConstantPointerNull * get(PointerType *T)
Static factory methods - Return objects of the specified value.
Definition: Constants.cpp:1306
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...
Definition: MathExtras.h:112
Import information from summary.
LLVM Basic Block Representation.
Definition: BasicBlock.h:59
The instances of the Type class are immutable: once they are created, they are never changed...
Definition: Type.h:46
FunctionType * getFunctionType() const
Returns the FunctionType for me.
Definition: Function.h:137
Allocate memory in an ever growing pool, as if by bump-pointer.
Definition: Allocator.h:138
Constant * getOrInsertGlobal(StringRef Name, Type *Ty)
Look up the specified global in the module symbol table.
Definition: Module.cpp:202
Conditional or Unconditional Branch instruction.
static ManagedStatic< std::map< const Function *, ExFunc > > ExportedFunctions
This is an important base class in LLVM.
Definition: Constant.h:42
Error errorCodeToError(std::error_code EC)
Helper for converting an std::error_code to a Error.
Definition: Error.cpp:78
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.
Definition: Allocator.h:212
void eraseFromParent()
eraseFromParent - This method unlinks 'this' from the containing module and deletes it...
Definition: Globals.cpp:335
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>.
Definition: Error.h:952
static Type * getVoidTy(LLVMContext &C)
Definition: Type.cpp:161
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.
iterator begin() const
Definition: ArrayRef.h:137
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
Definition: BasicBlock.h:101
Value * CreateICmpEQ(Value *LHS, Value *RHS, const Twine &Name="")
Definition: IRBuilder.h:1546
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...
Definition: Constants.cpp:1930
self_iterator getIterator()
Definition: ilist_node.h:82
Class to represent integer types.
Definition: DerivedTypes.h:40
bool empty() const
empty - Check if the array is empty.
Definition: ArrayRef.h:144
Metadata wrapper in the Value hierarchy.
Definition: Metadata.h:172
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.
Definition: GlobalValue.h:233
The Output class is used to generate a yaml document from in-memory structs and vectors.
Definition: YAMLTraits.h:1260
uint64_t NextPowerOf2(uint64_t A)
Returns the next power of two (in 64-bits) that is strictly greater than A.
Definition: MathExtras.h:632
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition: PassManager.h:159
static PointerType * getInt8PtrTy(LLVMContext &C, unsigned AS=0)
Definition: Type.cpp:220
void setMetadata(unsigned KindID, MDNode *Node)
Set the metadata of the specified kind to the specified node.
Definition: Metadata.cpp:1214
Triple - Helper class for working with autoconf configuration names.
Definition: Triple.h:44
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition: PassSupport.h:34
PHINode * CreatePHI(Type *Ty, unsigned NumReservedValues, const Twine &Name="")
Definition: IRBuilder.h:1654
static Constant * getPointerCast(Constant *C, Type *Ty)
Create a BitCast, AddrSpaceCast, or a PtrToInt cast constant expression.
Definition: Constants.cpp:1492
const MDOperand & getOperand(unsigned I) const
Definition: Metadata.h:1067
A SetVector that performs no allocations if smaller than a certain size.
Definition: SetVector.h:298
#define E
Definition: LargeTest.cpp:27
static PointerType * getUnqual(Type *ElementType)
This constructs a pointer to an object of the specified type in the generic address space (address sp...
Definition: DerivedTypes.h:482
This is the shared class of boolean and integer constants.
Definition: Constants.h:84
#define B
Definition: LargeTest.cpp:24
uint64_t getTypeAllocSize(Type *Ty) const
Returns the offset in bytes between successive objects of the specified type, including alignment pad...
Definition: DataLayout.h:405
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:861
Module.h This file contains the declarations for the Module class.
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:245
void addMetadata(unsigned KindID, MDNode &MD)
Add a metadata attachment.
Definition: Metadata.cpp:1382
const DataFlowGraph & G
Definition: RDFGraph.cpp:206
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.
Definition: Constants.cpp:560
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.
Definition: ModuleUtils.cpp:84
static ConstantInt * getTrue(LLVMContext &Context)
Definition: Constants.cpp:516
void setLinkage(LinkageTypes LT)
Definition: GlobalValue.h:425
enum llvm::TypeTestResolution::Kind TheKind
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:132
Value * getArgOperand(unsigned i) const
getArgOperand/setArgOperand - Return/set the i-th call argument.
Value * CreateGEP(Value *Ptr, ArrayRef< Value * > IdxList, const Twine &Name="")
Definition: IRBuilder.h:1223
Target - Wrapper for Target specific information.
Class for arbitrary precision integers.
Definition: APInt.h:69
iterator_range< user_iterator > users()
Definition: Value.h:395
Value * CreateShl(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition: IRBuilder.h:1008
The file should be opened in text mode on platforms that make this distinction.
Definition: FileSystem.h:708
MDNode * getMetadata(unsigned KindID) const
Get the current metadata attachments for the given kind, if any.
Definition: Metadata.cpp:1431
void setMetadata(unsigned KindID, MDNode *MD)
Set a particular kind of metadata attachment.
Definition: Metadata.cpp:1421
#define clEnumValN(ENUMVAL, FLAGNAME, DESC)
Definition: CommandLine.h:596
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition: Metadata.h:1164
std::set< std::string > & cfiFunctionDefs()
use_iterator use_begin()
Definition: Value.h:334
Test a byte array (first example)
Basic Alias true
PointerType * getType() const
Global values are always pointers.
Definition: GlobalValue.h:260
const DataLayout & getDataLayout() const
Get the data layout for the module's target platform.
Definition: Module.cpp:361
bool hasAddressTaken(const User **=nullptr) const
hasAddressTaken - returns true if there are any uses of this function other than direct calls or invo...
Definition: Function.cpp:1208
A raw_ostream that writes to a file descriptor.
Definition: raw_ostream.h:357
static IntegerType * getInt32Ty(LLVMContext &C)
Definition: Type.cpp:176
bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
Definition: Globals.cpp:200
#define C
Definition: LargeTest.cpp:25
All-ones bit vector ("Eliminating Bit Vector Checks for All-Ones Bit Vectors") ...
static Constant * getPtrToInt(Constant *C, Type *Ty, bool OnlyIfReduced=false)
Definition: Constants.cpp:1652
#define I(x, y, z)
Definition: MD5.cpp:58
bool isGUIDLive(GlobalValue::GUID GUID) const
LLVM_ATTRIBUTE_ALWAYS_INLINE size_type size() const
Definition: SmallVector.h:135
bool hasOneUse() const
Return true if there is exactly one user of this value.
Definition: Value.h:408
ModulePass class - This class is used to implement unstructured interprocedural optimizations and ana...
Definition: Pass.h:235
unsigned getPointerSizeInBits(unsigned AS=0) const
Layout pointer size, in bits FIXME: The defaults need to be removed once all of the backends/clients ...
Definition: DataLayout.h:346
static ArrayType * get(Type *ElementType, uint64_t NumElements)
This static method is the primary way to construct an ArrayType.
Definition: Type.cpp:568
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
Definition: Casting.h:323
Rename collisions when linking (static functions).
Definition: GlobalValue.h:56
void eraseFromParent()
eraseFromParent - This method unlinks 'this' from the containing module and deletes it...
Definition: Function.cpp:202
BasicBlock * splitBasicBlock(iterator I, const Twine &BBName="")
Split the basic block into two basic blocks at the specified instruction.
Definition: BasicBlock.cpp:382
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.
Definition: InlineAsm.cpp:43
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="")
Definition: IRBuilder.h:1063
Value * CreatePtrToInt(Value *V, Type *DestTy, const Twine &Name="")
Definition: IRBuilder.h:1436
bool use_empty() const
Definition: Value.h:322
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()
Definition: Value.h:371
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.
Definition: Metadata.cpp:1393
ObjectFormatType
Definition: Triple.h:207
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.
Definition: raw_ostream.h:463
aarch64 promote const
LLVM Value Representation.
Definition: Value.h:73
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.
Definition: BitmaskEnum.h:81
BumpPtrAllocator Alloc
Value * CreateLShr(Value *LHS, Value *RHS, const Twine &Name="", bool isExact=false)
Definition: IRBuilder.h:1027
This class implements an extremely fast bulk output stream that can only output to a stream...
Definition: raw_ostream.h:44
static const unsigned kARMJumpTableEntrySize
#define DEBUG(X)
Definition: Debug.h:118
void addFnAttr(Attribute::AttrKind Kind)
Add function attributes to this function.
Definition: Function.h:203
IRTranslator LLVM IR MI
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:49
A single uniqued string.
Definition: Metadata.h:602
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)
Definition: Function.h:128
void sort(Policy policy, RandomAccessIterator Start, RandomAccessIterator End, const Comparator &Comp=Comparator())
Definition: Parallel.h:201
int * Ptr
T Max(T a, T b)
Definition: FuzzerDefs.h:91
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.
Root of the metadata hierarchy.
Definition: Metadata.h:58
bool isDeclarationForLinker() const
Definition: GlobalValue.h:503
static IntegerType * getInt8Ty(LLVMContext &C)
Definition: Type.cpp:174
void setSection(StringRef S)
Change the section for this global.
Definition: Globals.cpp:183
const BasicBlock * getParent() const
Definition: Instruction.h:66
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...
Definition: Globals.cpp:399
IntegerType * Int32Ty
bool containsGlobalOffset(uint64_t Offset) const
LLVMContext & getContext() const
Get the global data context.
Definition: Module.h:237