106 using namespace llvm;
120 "dfsan-preserve-alignment",
133 cl::desc(
"File listing native ABI functions and how the pass treats them"),
140 cl::desc(
"Use the argument ABI rather than the TLS ABI"),
146 "dfsan-combine-pointer-labels-on-load",
147 cl::desc(
"Combine the label of the pointer with the label of the data when " 148 "loading from memory."),
154 "dfsan-combine-pointer-labels-on-store",
155 cl::desc(
"Combine the label of the pointer with the label of the data when " 156 "storing in memory."),
160 "dfsan-debug-nonzero-labels",
161 cl::desc(
"Insert calls to __dfsan_nonzero_label on observing a parameter, " 162 "load or return with a nonzero label"),
169 if (
StructType *SGType = dyn_cast<StructType>(GType)) {
170 if (!SGType->isLiteral())
171 return SGType->getName();
173 return "<unknown type>";
179 std::unique_ptr<SpecialCaseList> SCL;
182 DFSanABIList() =
default;
184 void set(std::unique_ptr<SpecialCaseList>
List) { SCL = std::move(
List); }
190 SCL->inSection(
"dataflow",
"fun", F.
getName(), Category);
202 return SCL->inSection(
"dataflow",
"fun", GA.
getName(), Category);
204 return SCL->inSection(
"dataflow",
"global", GA.
getName(), Category) ||
218 struct TransformedFunction {
221 std::vector<unsigned> ArgumentIndexMapping)
222 : OriginalType(OriginalType),
223 TransformedType(TransformedType),
224 ArgumentIndexMapping(ArgumentIndexMapping) {}
227 TransformedFunction(
const TransformedFunction&) =
delete;
228 TransformedFunction& operator=(
const TransformedFunction&) =
delete;
231 TransformedFunction(TransformedFunction&&) =
default;
232 TransformedFunction& operator=(TransformedFunction&&) =
default;
245 std::vector<unsigned> ArgumentIndexMapping;
252 const TransformedFunction& TransformedFunction,
256 std::vector<llvm::AttributeSet> ArgumentAttributes(
257 TransformedFunction.TransformedType->getNumParams());
262 for (
unsigned i=0, ie = TransformedFunction.ArgumentIndexMapping.size();
264 unsigned TransformedIndex = TransformedFunction.ArgumentIndexMapping[i];
269 for (
unsigned i = TransformedFunction.OriginalType->getNumParams(),
282 friend struct DFSanFunction;
283 friend class DFSanVisitor;
290 enum InstrumentedABI {
335 void *(*GetArgTLSPtr)();
336 void *(*GetRetvalTLSPtr)();
356 DFSanABIList ABIList;
359 bool DFSanRuntimeShadowMask =
false;
366 TransformedFunction getCustomFunctionType(
FunctionType *T);
367 InstrumentedABI getInstrumentedABI();
368 WrapperKind getWrapperKind(
Function *F);
379 const std::vector<std::string> &ABIListFiles = std::vector<std::string>(),
380 void *(*getArgTLS)() =
nullptr,
void *(*getRetValTLS)() =
nullptr);
382 bool doInitialization(
Module &M)
override;
383 bool runOnModule(
Module &M)
override;
386 struct DFSanFunction {
387 DataFlowSanitizer &
DFS;
390 DataFlowSanitizer::InstrumentedABI IA;
392 Value *ArgTLSPtr =
nullptr;
393 Value *RetvalTLSPtr =
nullptr;
397 std::vector<std::pair<PHINode *, PHINode *>> PHIFixups;
399 std::vector<Value *> NonZeroChecks;
402 struct CachedCombinedShadow {
407 CachedCombinedShadows;
410 DFSanFunction(DataFlowSanitizer &DFS,
Function *F,
bool IsNativeABI)
411 :
DFS(DFS),
F(F), IA(DFS.getInstrumentedABI()), IsNativeABI(IsNativeABI) {
415 AvoidNewBlocks = F->
size() > 1000;
418 Value *getArgTLSPtr();
420 Value *getRetvalTLS();
427 void storeShadow(
Value *Addr, uint64_t Size, uint64_t Align,
Value *Shadow,
431 class DFSanVisitor :
public InstVisitor<DFSanVisitor> {
435 DFSanVisitor(DFSanFunction &DFSF) : DFSF(DFSF) {}
438 return DFSF.F->getParent()->getDataLayout();
445 void visitCmpInst(
CmpInst &CI);
451 void visitPHINode(
PHINode &PN);
468 "DataFlowSanitizer: dynamic data flow analysis.",
false,
false)
472 void *(*getArgTLS)(),
473 void *(*getRetValTLS)()) {
474 return new DataFlowSanitizer(ABIListFiles, getArgTLS, getRetValTLS);
477 DataFlowSanitizer::DataFlowSanitizer(
478 const std::vector<std::string> &ABIListFiles,
void *(*getArgTLS)(),
479 void *(*getRetValTLS)())
480 :
ModulePass(
ID), GetArgTLSPtr(getArgTLS), GetRetvalTLSPtr(getRetValTLS) {
481 std::vector<std::string> AllABIListFiles(std::move(ABIListFiles));
482 AllABIListFiles.insert(AllABIListFiles.end(),
ClABIListFiles.begin(),
493 ArgTypes.push_back(ShadowPtrTy);
508 ArgTypes.push_back(ShadowPtrTy);
512 TransformedFunction DataFlowSanitizer::getCustomFunctionType(
FunctionType *T) {
519 std::vector<unsigned> ArgumentIndexMapping;
520 for (
unsigned i = 0, ie = T->
getNumParams(); i != ie; ++i) {
523 if (isa<PointerType>(param_type) && (FT = dyn_cast<FunctionType>(
524 cast<PointerType>(param_type)->getElementType()))) {
525 ArgumentIndexMapping.push_back(ArgTypes.
size());
526 ArgTypes.
push_back(getTrampolineFunctionType(FT)->getPointerTo());
529 ArgumentIndexMapping.push_back(ArgTypes.
size());
540 return TransformedFunction(
542 ArgumentIndexMapping);
545 bool DataFlowSanitizer::doInitialization(
Module &M) {
548 bool IsMIPS64 = TargetTriple.isMIPS64();
567 DFSanRuntimeShadowMask =
true;
571 Type *DFSanUnionArgs[2] = { ShadowTy, ShadowTy };
574 Type *DFSanUnionLoadArgs[2] = { ShadowPtrTy, IntptrTy };
581 DFSanSetLabelArgs,
false);
595 if (GetRetvalTLSPtr) {
607 bool DataFlowSanitizer::isInstrumented(
const Function *
F) {
608 return !ABIList.isIn(*F,
"uninstrumented");
611 bool DataFlowSanitizer::isInstrumented(
const GlobalAlias *GA) {
612 return !ABIList.isIn(*GA,
"uninstrumented");
615 DataFlowSanitizer::InstrumentedABI DataFlowSanitizer::getInstrumentedABI() {
619 DataFlowSanitizer::WrapperKind DataFlowSanitizer::getWrapperKind(
Function *F) {
620 if (ABIList.isIn(*F,
"functional"))
621 return WK_Functional;
622 if (ABIList.isIn(*F,
"discard"))
624 if (ABIList.isIn(*F,
"custom"))
630 void DataFlowSanitizer::addGlobalNamePrefix(
GlobalValue *GV) {
640 std::string SearchStr =
".symver " + GVName +
",";
641 size_t Pos = Asm.find(SearchStr);
642 if (Pos != std::string::npos) {
643 Asm.replace(Pos, SearchStr.size(),
670 std::vector<Value *>
Args;
673 Args.push_back(&*ai);
692 std::vector<Value *>
Args;
695 Args.push_back(&*AI);
703 DFSanFunction DFSF(*
this, F,
true);
705 for (
unsigned N = FT->
getNumParams();
N != 0; ++ValAI, ++ShadowAI, --
N)
706 DFSF.ValShadowMap[&*ValAI] = &*ShadowAI;
707 DFSanVisitor(DFSF).visitCallInst(*CI);
709 new StoreInst(DFSF.getShadow(RI->getReturnValue()),
710 &*std::prev(F->
arg_end()), RI);
716 bool DataFlowSanitizer::runOnModule(
Module &M) {
717 if (ABIList.isIn(M,
"skip"))
722 ArgTLS =
Mod->getOrInsertGlobal(
"__dfsan_arg_tls", ArgTLSTy);
726 if (!GetRetvalTLSPtr) {
727 RetvalTLS =
Mod->getOrInsertGlobal(
"__dfsan_retval_tls", ShadowTy);
733 Mod->getOrInsertGlobal(kDFSanExternShadowPtrMask, IntptrTy);
738 Attribute::NoUnwind);
740 Attribute::ReadNone);
746 Mod->getOrInsertFunction(
"__dfsan_union", DFSanUnionFnTy, AL);
752 Attribute::NoUnwind);
754 Attribute::ReadNone);
759 DFSanCheckedUnionFn =
760 Mod->getOrInsertFunction(
"dfsan_union", DFSanUnionFnTy, AL);
765 Attribute::NoUnwind);
767 Attribute::ReadOnly);
771 Mod->getOrInsertFunction(
"__dfsan_union_load", DFSanUnionLoadFnTy, AL);
773 DFSanUnimplementedFn =
774 Mod->getOrInsertFunction(
"__dfsan_unimplemented", DFSanUnimplementedFnTy);
779 Mod->getOrInsertFunction(
"__dfsan_set_label", DFSanSetLabelFnTy, AL);
781 DFSanNonzeroLabelFn =
782 Mod->getOrInsertFunction(
"__dfsan_nonzero_label", DFSanNonzeroLabelFnTy);
783 DFSanVarargWrapperFn =
Mod->getOrInsertFunction(
"__dfsan_vararg_wrapper",
784 DFSanVarargWrapperFnTy);
786 std::vector<Function *> FnsToInstrument;
789 if (!i.isIntrinsic() &&
790 &i != DFSanUnionFn.getCallee()->stripPointerCasts() &&
791 &i != DFSanCheckedUnionFn.getCallee()->stripPointerCasts() &&
792 &i != DFSanUnionLoadFn.getCallee()->stripPointerCasts() &&
793 &i != DFSanUnimplementedFn.getCallee()->stripPointerCasts() &&
794 &i != DFSanSetLabelFn.getCallee()->stripPointerCasts() &&
795 &i != DFSanNonzeroLabelFn.getCallee()->stripPointerCasts() &&
796 &i != DFSanVarargWrapperFn.getCallee()->stripPointerCasts())
797 FnsToInstrument.push_back(&i);
808 bool GAInst = isInstrumented(GA), FInst = isInstrumented(F);
809 if (GAInst && FInst) {
810 addGlobalNamePrefix(GA);
811 }
else if (GAInst != FInst) {
820 FnsToInstrument.push_back(NewF);
825 ReadOnlyNoneAttrs.addAttribute(Attribute::ReadOnly)
826 .addAttribute(Attribute::ReadNone);
830 for (std::vector<Function *>::iterator i = FnsToInstrument.begin(),
831 e = FnsToInstrument.end();
839 if (isInstrumented(&F)) {
842 if (getInstrumentedABI() == IA_Args && !IsZeroArgsVoidRet) {
853 FArg != FArgEnd; ++FArg, ++NewFArg) {
854 FArg->replaceAllUsesWith(&*NewFArg);
873 addGlobalNamePrefix(NewF);
875 addGlobalNamePrefix(&F);
877 }
else if (!IsZeroArgsVoidRet || getWrapperKind(&F) == WK_Custom) {
882 ? getArgsFunctionType(FT)
892 Function *NewF = buildWrapperFunction(
893 &F, std::string(
"dfsw$") + std::string(F.
getName()),
894 wrapperLinkage, NewFT);
895 if (getInstrumentedABI() == IA_TLS)
898 Value *WrappedFnCst =
902 UnwrappedFnMap[WrappedFnCst] = &
F;
910 FnsWithNativeABI.
insert(&F);
915 size_t N = i - FnsToInstrument.begin(),
916 Count =
e - FnsToInstrument.begin();
917 FnsToInstrument.push_back(&F);
918 i = FnsToInstrument.begin() +
N;
919 e = FnsToInstrument.begin() + Count;
924 UnwrappedFnMap[&
F] = &
F;
929 for (
Function *i : FnsToInstrument) {
930 if (!i || i->isDeclaration())
935 DFSanFunction DFSF(*
this, i, FnsWithNativeABI.
count(i));
951 if (!DFSF.SkipInsts.count(Inst))
952 DFSanVisitor(DFSF).visit(Inst);
963 for (std::vector<std::pair<PHINode *, PHINode *>>::iterator
964 i = DFSF.PHIFixups.begin(),
965 e = DFSF.PHIFixups.end();
967 for (
unsigned val = 0, n = i->first->getNumIncomingValues(); val != n;
969 i->second->setIncomingValue(
970 val, DFSF.getShadow(i->first->getIncomingValue(val)));
979 for (
Value *V : DFSF.NonZeroChecks) {
982 Pos =
I->getNextNode();
984 Pos = &DFSF.F->getEntryBlock().front();
985 while (isa<PHINode>(Pos) || isa<AllocaInst>(Pos))
990 Ne, Pos,
false, ColdCallWeights));
992 ThenIRB.CreateCall(DFSF.DFS.DFSanNonzeroLabelFn, {});
1000 Value *DFSanFunction::getArgTLSPtr() {
1004 return ArgTLSPtr =
DFS.ArgTLS;
1010 Value *DFSanFunction::getRetvalTLS() {
1012 return RetvalTLSPtr;
1014 return RetvalTLSPtr =
DFS.RetvalTLS;
1017 return RetvalTLSPtr =
1024 getArgTLSPtr(), 0, Idx);
1028 if (!isa<Argument>(V) && !isa<Instruction>(V))
1029 return DFS.ZeroShadow;
1030 Value *&Shadow = ValShadowMap[V];
1032 if (
Argument *A = dyn_cast<Argument>(V)) {
1034 return DFS.ZeroShadow;
1036 case DataFlowSanitizer::IA_TLS: {
1037 Value *ArgTLSPtr = getArgTLSPtr();
1040 : cast<Instruction>(ArgTLSPtr)->getNextNode();
1043 IRB.
CreateLoad(
DFS.ShadowTy, getArgTLS(A->getArgNo(), ArgTLSPos));
1046 case DataFlowSanitizer::IA_Args: {
1047 unsigned ArgIdx = A->getArgNo() + F->
arg_size() / 2;
1056 NonZeroChecks.push_back(Shadow);
1058 Shadow =
DFS.ZeroShadow;
1065 assert(!ValShadowMap.count(I));
1067 ValShadowMap[
I] = Shadow;
1071 assert(Addr != RetvalTLS &&
"Reinstrumenting?");
1073 Value *ShadowPtrMaskValue;
1074 if (DFSanRuntimeShadowMask)
1075 ShadowPtrMaskValue = IRB.
CreateLoad(IntptrTy, ExternalShadowMask);
1077 ShadowPtrMaskValue = ShadowPtrMask;
1089 if (V1 ==
DFS.ZeroShadow)
1091 if (V2 ==
DFS.ZeroShadow)
1096 auto V1Elems = ShadowElements.find(V1);
1097 auto V2Elems = ShadowElements.find(V2);
1098 if (V1Elems != ShadowElements.end() && V2Elems != ShadowElements.end()) {
1099 if (std::includes(V1Elems->second.begin(), V1Elems->second.end(),
1100 V2Elems->second.begin(), V2Elems->second.end())) {
1102 }
else if (std::includes(V2Elems->second.begin(), V2Elems->second.end(),
1103 V1Elems->second.begin(), V1Elems->second.end())) {
1106 }
else if (V1Elems != ShadowElements.end()) {
1107 if (V1Elems->second.count(V2))
1109 }
else if (V2Elems != ShadowElements.end()) {
1110 if (V2Elems->second.count(V1))
1114 auto Key = std::make_pair(V1, V2);
1117 CachedCombinedShadow &CCS = CachedCombinedShadows[
Key];
1118 if (CCS.Block && DT.dominates(CCS.Block, Pos->
getParent()))
1122 if (AvoidNewBlocks) {
1134 Ne, Pos,
false,
DFS.ColdCallWeights, &DT));
1136 CallInst *Call = ThenIRB.CreateCall(
DFS.DFSanUnionFn, {V1, V2});
1150 std::set<Value *> UnionElems;
1151 if (V1Elems != ShadowElements.end()) {
1152 UnionElems = V1Elems->second;
1154 UnionElems.insert(V1);
1156 if (V2Elems != ShadowElements.end()) {
1157 UnionElems.insert(V2Elems->second.begin(), V2Elems->second.end());
1159 UnionElems.insert(V2);
1161 ShadowElements[CCS.Shadow] = std::move(UnionElems);
1171 return DFS.ZeroShadow;
1175 Shadow = combineShadows(Shadow, getShadow(Inst->
getOperand(i)), Inst);
1180 void DFSanVisitor::visitOperandShadowInst(
Instruction &I) {
1181 Value *CombinedShadow = DFSF.combineOperandShadows(&I);
1182 DFSF.setShadow(&I, CombinedShadow);
1189 if (
AllocaInst *AI = dyn_cast<AllocaInst>(Addr)) {
1190 const auto i = AllocaShadowMap.find(AI);
1191 if (i != AllocaShadowMap.end()) {
1197 uint64_t ShadowAlign = Align *
DFS.ShadowWidth / 8;
1200 bool AllConstants =
true;
1201 for (
const Value *Obj : Objs) {
1202 if (isa<Function>(Obj) || isa<BlockAddress>(Obj))
1204 if (isa<GlobalVariable>(Obj) && cast<GlobalVariable>(Obj)->
isConstant())
1207 AllConstants =
false;
1211 return DFS.ZeroShadow;
1213 Value *ShadowAddr =
DFS.getShadowAddress(Addr, Pos);
1216 return DFS.ZeroShadow;
1226 return combineShadows(
1231 if (!AvoidNewBlocks && Size % (64 /
DFS.ShadowWidth) == 0) {
1238 DFS.DFSanUnionLoadFn,
1239 {ShadowAddr, ConstantInt::get(DFS.IntptrTy, Size)});
1259 std::vector<DomTreeNode *> Children(OldNode->begin(), OldNode->end());
1261 DomTreeNode *NewNode = DT.addNewBlock(Tail, Head);
1262 for (
auto Child : Children)
1263 DT.changeImmediateDominator(Child, NewNode);
1272 DT.addNewBlock(FallbackBB, Head);
1274 for (uint64_t Ofs = 64 /
DFS.ShadowWidth; Ofs != Size;
1275 Ofs += 64 /
DFS.ShadowWidth) {
1277 DT.addNewBlock(NextBB, LastBr->
getParent());
1282 WideAddr, ShadowAlign);
1283 ShadowsEq = NextIRB.
CreateICmpEQ(WideShadow, NextWideShadow);
1285 LastBr = NextIRB.
CreateCondBr(ShadowsEq, FallbackBB, FallbackBB);
1298 DFS.DFSanUnionLoadFn, {ShadowAddr, ConstantInt::get(DFS.IntptrTy, Size)});
1300 return FallbackCall;
1303 void DFSanVisitor::visitLoadInst(
LoadInst &LI) {
1307 DFSF.setShadow(&LI, DFSF.DFS.ZeroShadow);
1315 Align = DL.getABITypeAlignment(LI.
getType());
1323 Shadow = DFSF.combineShadows(Shadow, PtrShadow, &LI);
1325 if (Shadow != DFSF.DFS.ZeroShadow)
1326 DFSF.NonZeroChecks.push_back(Shadow);
1328 DFSF.setShadow(&LI, Shadow);
1331 void DFSanFunction::storeShadow(
Value *Addr, uint64_t Size, uint64_t Align,
1333 if (
AllocaInst *AI = dyn_cast<AllocaInst>(Addr)) {
1334 const auto i = AllocaShadowMap.find(AI);
1335 if (i != AllocaShadowMap.end()) {
1342 uint64_t ShadowAlign = Align *
DFS.ShadowWidth / 8;
1344 Value *ShadowAddr =
DFS.getShadowAddress(Addr, Pos);
1345 if (Shadow ==
DFS.ZeroShadow) {
1348 Value *ExtShadowAddr =
1354 const unsigned ShadowVecSize = 128 /
DFS.ShadowWidth;
1356 if (Size >= ShadowVecSize) {
1359 for (
unsigned i = 0; i != ShadowVecSize; ++i) {
1363 Value *ShadowVecAddr =
1366 Value *CurShadowVecAddr =
1369 Size -= ShadowVecSize;
1371 }
while (Size >= ShadowVecSize);
1372 Offset *= ShadowVecSize;
1375 Value *CurShadowAddr =
1383 void DFSanVisitor::visitStoreInst(
StoreInst &
SI) {
1401 Shadow = DFSF.combineShadows(Shadow, PtrShadow, &SI);
1407 visitOperandShadowInst(UO);
1411 visitOperandShadowInst(BO);
1414 void DFSanVisitor::visitCastInst(
CastInst &CI) { visitOperandShadowInst(CI); }
1416 void DFSanVisitor::visitCmpInst(
CmpInst &CI) { visitOperandShadowInst(CI); }
1419 visitOperandShadowInst(GEPI);
1423 visitOperandShadowInst(I);
1427 visitOperandShadowInst(I);
1431 visitOperandShadowInst(I);
1435 visitOperandShadowInst(I);
1439 visitOperandShadowInst(I);
1442 void DFSanVisitor::visitAllocaInst(
AllocaInst &I) {
1443 bool AllLoadsStores =
true;
1445 if (isa<LoadInst>(U))
1448 if (
StoreInst *SI = dyn_cast<StoreInst>(U)) {
1453 AllLoadsStores =
false;
1456 if (AllLoadsStores) {
1458 DFSF.AllocaShadowMap[&
I] = IRB.
CreateAlloca(DFSF.DFS.ShadowTy);
1460 DFSF.setShadow(&I, DFSF.DFS.ZeroShadow);
1463 void DFSanVisitor::visitSelectInst(
SelectInst &I) {
1471 DFSF.combineShadows(
1472 CondShadow, DFSF.combineShadows(TrueShadow, FalseShadow, &I), &
I));
1475 if (TrueShadow == FalseShadow) {
1476 ShadowSel = TrueShadow;
1481 DFSF.setShadow(&I, DFSF.combineShadows(CondShadow, ShadowSel, &I));
1485 void DFSanVisitor::visitMemSetInst(
MemSetInst &I) {
1489 {ValShadow, IRB.CreateBitCast(I.getDest(), Type::getInt8PtrTy(
1491 IRB.CreateZExtOrTrunc(I.getLength(), DFSF.DFS.IntptrTy)});
1496 Value *DestShadow = DFSF.DFS.getShadowAddress(I.
getDest(), &
I);
1504 auto *MTI = cast<MemTransferInst>(
1511 MTI->setDestAlignment(DFSF.DFS.ShadowWidth / 8);
1512 MTI->setSourceAlignment(DFSF.DFS.ShadowWidth / 8);
1516 void DFSanVisitor::visitReturnInst(
ReturnInst &RI) {
1519 case DataFlowSanitizer::IA_TLS: {
1525 case DataFlowSanitizer::IA_Args: {
1527 Type *RT = DFSF.F->getFunctionType()->getReturnType();
1539 void DFSanVisitor::visitCallSite(
CallSite CS) {
1555 if (i != DFSF.DFS.UnwrappedFnMap.end()) {
1557 switch (DFSF.DFS.getWrapperKind(F)) {
1558 case DataFlowSanitizer::WK_Warning:
1560 IRB.CreateCall(DFSF.DFS.DFSanUnimplementedFn,
1561 IRB.CreateGlobalStringPtr(F->
getName()));
1564 case DataFlowSanitizer::WK_Discard:
1568 case DataFlowSanitizer::WK_Functional:
1572 case DataFlowSanitizer::WK_Custom:
1578 TransformedFunction CustomFn = DFSF.DFS.getCustomFunctionType(FT);
1579 std::string CustomFName =
"__dfsw_";
1582 CustomFName, CustomFn.TransformedType);
1584 CustomFn->copyAttributesFrom(F);
1589 DFSF.DFS.ReadOnlyNoneAttrs);
1593 std::vector<Value *>
Args;
1596 for (
unsigned n = FT->
getNumParams(); n != 0; ++i, --n) {
1597 Type *T = (*i)->getType();
1599 if (isa<PointerType>(T) &&
1600 (ParamFT = dyn_cast<FunctionType>(
1601 cast<PointerType>(T)->getElementType()))) {
1602 std::string TName =
"dfst";
1606 Constant *T = DFSF.DFS.getOrBuildTrampolineFunction(ParamFT, TName);
1616 const unsigned ShadowArgStart = Args.size();
1617 for (
unsigned n = FT->
getNumParams(); n != 0; ++i, --n)
1618 Args.push_back(DFSF.getShadow(*i));
1624 LabelVATy, getDataLayout().getAllocaAddrSpace(),
1625 "labelva", &DFSF.F->getEntryBlock().front());
1627 for (
unsigned n = 0; i != CS.
arg_end(); ++i, ++n) {
1628 auto LabelVAPtr = IRB.CreateStructGEP(LabelVATy, LabelVAAlloca, n);
1629 IRB.CreateStore(DFSF.getShadow(*i), LabelVAPtr);
1632 Args.push_back(IRB.CreateStructGEP(LabelVATy, LabelVAAlloca, 0));
1636 if (!DFSF.LabelReturnAlloca) {
1637 DFSF.LabelReturnAlloca =
1639 getDataLayout().getAllocaAddrSpace(),
1640 "labelreturn", &DFSF.F->getEntryBlock().front());
1642 Args.push_back(DFSF.LabelReturnAlloca);
1648 CallInst *CustomCI = IRB.CreateCall(CustomF, Args);
1650 CustomCI->
setAttributes(TransformFunctionAttributes(CustomFn,
1657 const unsigned ArgNo = ShadowArgStart + n;
1664 IRB.CreateLoad(DFSF.DFS.ShadowTy, DFSF.LabelReturnAlloca);
1665 DFSF.setShadow(CustomCI, LabelLoad);
1678 if (DFSF.DFS.getInstrumentedABI() == DataFlowSanitizer::IA_TLS) {
1679 for (
unsigned i = 0, n = FT->
getNumParams(); i != n; ++i) {
1680 IRB.CreateStore(DFSF.getShadow(CS.
getArgument(i)),
1688 if (II->getNormalDest()->getSinglePredecessor()) {
1689 Next = &II->getNormalDest()->front();
1692 SplitEdge(II->getParent(), II->getNormalDest(), &DFSF.DT);
1693 Next = &NewBB->
front();
1697 Next = CS->getNextNode();
1700 if (DFSF.DFS.getInstrumentedABI() == DataFlowSanitizer::IA_TLS) {
1703 DFSF.SkipInsts.insert(LI);
1705 DFSF.NonZeroChecks.push_back(LI);
1711 if (DFSF.DFS.getInstrumentedABI() == DataFlowSanitizer::IA_Args) {
1712 FunctionType *NewFT = DFSF.DFS.getArgsFunctionType(FT);
1715 std::vector<Value *>
Args;
1718 for (
unsigned n = FT->
getNumParams(); n != 0; ++i, --n)
1722 for (
unsigned n = FT->
getNumParams(); n != 0; ++i, --n)
1723 Args.push_back(DFSF.getShadow(*i));
1729 new AllocaInst(VarArgArrayTy, getDataLayout().getAllocaAddrSpace(),
1730 "", &DFSF.F->getEntryBlock().front());
1731 Args.push_back(IRB.CreateConstGEP2_32(VarArgArrayTy, VarArgShadow, 0, 0));
1732 for (
unsigned n = 0; i !=
e; ++i, ++n) {
1735 IRB.CreateConstGEP2_32(VarArgArrayTy, VarArgShadow, 0, n));
1742 NewCS = IRB.CreateInvoke(NewFT, Func, II->getNormalDest(),
1743 II->getUnwindDest(),
Args);
1745 NewCS = IRB.CreateCall(NewFT, Func, Args);
1755 DFSF.SkipInsts.insert(ExVal);
1758 DFSF.SkipInsts.insert(ExShadow);
1759 DFSF.setShadow(ExVal, ExShadow);
1760 DFSF.NonZeroChecks.push_back(ExShadow);
1769 void DFSanVisitor::visitPHINode(
PHINode &PN) {
1780 DFSF.PHIFixups.push_back(std::make_pair(&PN, ShadowPN));
1781 DFSF.setShadow(&PN, ShadowPN);
bool isVarArg() const
isVarArg - Return true if this function takes a variable number of arguments.
Return a value (possibly void), from a function.
Value * getValueOperand()
bool isIntrinsic() const
isIntrinsic - Returns true if the function's name starts with "llvm.".
SymbolTableList< Instruction >::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
static cl::list< std::string > ClABIListFiles("dfsan-abilist", cl::desc("File listing native ABI functions and how the pass treats them"), cl::Hidden)
A parsed version of the target data layout string in and methods for querying it. ...
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
const std::string & getTargetTriple() const
Get the target triple which is a string describing the target host.
BranchInst * CreateCondBr(Value *Cond, BasicBlock *True, BasicBlock *False, MDNode *BranchWeights=nullptr, MDNode *Unpredictable=nullptr)
Create a conditional 'br Cond, TrueDest, FalseDest' instruction.
void ReplaceInstWithInst(BasicBlock::InstListType &BIL, BasicBlock::iterator &BI, Instruction *I)
Replace the instruction specified by BI with the instruction specified by I.
This class is the base class for the comparison instructions.
Value * CreateConstGEP1_32(Value *Ptr, unsigned Idx0, const Twine &Name="")
static bool isConstant(const MachineInstr &MI)
bool hasLocalLinkage() const
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
This class represents an incoming formal argument to a Function.
AllocaInst * CreateAlloca(Type *Ty, unsigned AddrSpace, Value *ArraySize=nullptr, const Twine &Name="")
Base class for instruction visitors.
IntrusiveRefCntPtr< FileSystem > getRealFileSystem()
Gets an vfs::FileSystem for the 'real' file system, as seen by the operating system.
Value * CreateICmpNE(Value *LHS, Value *RHS, const Twine &Name="")
NodeTy * getNextNode()
Get the next node, or nullptr for the list tail.
LLVM_ATTRIBUTE_NORETURN void report_fatal_error(Error Err, bool gen_crash_diag=true)
Report a serious error, calling any installed error handler.
This class represents lattice values for constants.
Type * getParamType(unsigned i) const
Parameter type accessors.
void setAttributes(AttributeList PAL)
Set the parameter attributes of the call.
LoadInst * CreateLoad(Type *Ty, Value *Ptr, const char *Name)
Provided to resolve 'CreateLoad(Ty, Ptr, "...")' correctly, instead of converting the string to 'bool...
A Module instance is used to store all the information related to an LLVM module. ...
LoadInst * CreateAlignedLoad(Type *Ty, Value *Ptr, unsigned Align, const char *Name)
Provided to resolve 'CreateAlignedLoad(Ptr, Align, "...")' correctly, instead of converting the strin...
static CallInst * Create(FunctionType *Ty, Value *F, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
A handy container for a FunctionType+Callee-pointer pair, which can be passed around as a single enti...
Implements a dense probed hash-table based set.
void push_back(const T &Elt)
void recalculate(ParentType &Func)
recalculate - compute a dominator tree for the given function
This class represents a function call, abstracting a target machine's calling convention.
unsigned getSourceAlignment() const
FIXME: Remove this function once transition to Align is over.
const Value * getTrueValue() const
static Constant * getIntToPtr(Constant *C, Type *Ty, bool OnlyIfReduced=false)
void setCallingConv(CallingConv::ID CC)
Set the calling convention of the call.
This instruction constructs a fixed permutation of two input vectors.
static SelectInst * Create(Value *C, Value *S1, Value *S2, const Twine &NameStr="", Instruction *InsertBefore=nullptr, Instruction *MDFrom=nullptr)
LLVMContext & getContext() const
All values hold a context through their type.
bool isTerminator() const
This class wraps the llvm.memset intrinsic.
BasicBlock * getSuccessor(unsigned i) const
static cl::opt< bool > ClCombinePointerLabelsOnStore("dfsan-combine-pointer-labels-on-store", cl::desc("Combine the label of the pointer with the label of the data when " "storing in memory."), cl::Hidden, cl::init(false))
param_iterator param_end() const
An instruction for reading from memory.
FunTy * getCalledFunction() const
Return the function being called if this is a direct call, otherwise return null (if it's an indirect...
static IntegerType * getInt64Ty(LLVMContext &C)
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
void addAttribute(unsigned i, Attribute::AttrKind Kind)
adds the attribute to the list of attributes.
Value * getLength() const
INITIALIZE_PASS(DataFlowSanitizer, "dfsan", "DataFlowSanitizer: dynamic data flow analysis.", false, false) ModulePass *llvm
static PointerType * getInt64PtrTy(LLVMContext &C, unsigned AS=0)
void eraseFromParent()
eraseFromParent - This method unlinks 'this' from the containing module and deletes it...
CallingConv::ID getCallingConv() const
Get the calling convention of the call.
block_iterator block_end()
Value * getDest() const
This is just like getRawDest, but it strips off any cast instructions (including addrspacecast) that ...
StoreInst * CreateAlignedStore(Value *Val, Value *Ptr, unsigned Align, bool isVolatile=false)
iterator begin()
Instruction iterator methods.
BasicBlock * SplitEdge(BasicBlock *From, BasicBlock *To, DominatorTree *DT=nullptr, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr)
Split the edge connecting specified block.
static ReturnInst * Create(LLVMContext &C, Value *retVal=nullptr, Instruction *InsertBefore=nullptr)
Value * getArgOperand(unsigned i) const
static cl::opt< bool > ClArgsABI("dfsan-args-abi", cl::desc("Use the argument ABI rather than the TLS ABI"), cl::Hidden)
The address of a basic block.
This class represents the LLVM 'select' instruction.
Type * getPointerElementType() const
const DataLayout & getDataLayout() const
Get the data layout for the module's target platform.
IntegerType * getInt64Ty()
Fetch the type representing a 64-bit integer.
This is the base class for all instructions that perform data casts.
ArrayRef< T > makeArrayRef(const T &OneElt)
Construct an ArrayRef from a single element.
Class to represent struct types.
LLVMContext & getContext() const
Get the global data context.
ValTy * getCalledValue() const
Return the pointer to function that is being called.
PointerType * getPointerTo(unsigned AddrSpace=0) const
Return a pointer to the current type.
This file contains the simple types necessary to represent the attributes associated with functions a...
AttributeSet getRetAttributes() const
The attributes for the ret value are returned.
void setModuleInlineAsm(StringRef Asm)
Set the module-scope inline assembly blocks.
void setName(const Twine &Name)
Change the name of the value.
unsigned getDestAlignment() const
FIXME: Remove this function once transition to Align is over.
Type * getType() const
Return the type of the instruction that generated this call site.
block_iterator block_begin()
static StructType * get(LLVMContext &Context, ArrayRef< Type *> Elements, bool isPacked=false)
This static method is the primary way to create a literal StructType.
StoreInst * CreateStore(Value *Val, Value *Ptr, bool isVolatile=false)
InstrTy * getInstruction() const
Value * CreateIntToPtr(Value *V, Type *DestTy, const Twine &Name="")
Class to represent function types.
Value * CreateBitCast(Value *V, Type *DestTy, const Twine &Name="")
Type * getType() const
All values are typed, get the type of this value.
LLVM_NODISCARD AttributeList removeAttributes(LLVMContext &C, unsigned Index, const AttrBuilder &AttrsToRemove) const
Remove the specified attributes at the specified index from this attribute list.
TypeSize getTypeStoreSize(Type *Ty) const
Returns the maximum number of bytes that may be overwritten by storing the specified type...
ArchType getArch() const
getArch - Get the parsed architecture type of this triple.
Class to represent array types.
AttributeSet getParamAttributes(unsigned ArgNo) const
The attributes for the argument or parameter at the given index are returned.
BasicBlock * getBasicBlock() const
const GlobalObject * getBaseObject() const
An instruction for storing to memory.
LinkageTypes getLinkage() const
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
void takeName(Value *V)
Transfer the name from V to this value.
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree...
Value * getOperand(unsigned i) const
Class to represent pointers.
Value * CreateOr(Value *LHS, Value *RHS, const Twine &Name="")
iterator find(const_arg_type_t< KeyT > Val)
static Constant * getBitCast(Constant *C, Type *Ty, bool OnlyIfReduced=false)
bool isVoidTy() const
Return true if this is 'void'.
const BasicBlock & getEntryBlock() const
an instruction for type-safe pointer arithmetic to access elements of arrays and structs ...
IntegerType * getIntPtrType(LLVMContext &C, unsigned AddressSpace=0) const
Returns an integer type with size at least as big as that of a pointer in the given address space...
Same, but only replaced by something equivalent.
initializer< Ty > init(const Ty &Val)
This instruction inserts a single (scalar) element into a VectorType value.
static Function * Create(FunctionType *Ty, LinkageTypes Linkage, unsigned AddrSpace, const Twine &N="", Module *M=nullptr)
void GetUnderlyingObjects(const Value *V, SmallVectorImpl< const Value *> &Objects, const DataLayout &DL, LoopInfo *LI=nullptr, unsigned MaxLookup=6)
This method is similar to GetUnderlyingObject except that it can look through phi and select instruct...
void setCalledFunction(Value *V)
Set the callee to the specified value.
Value * getCalledValue() const
LLVM Basic Block Representation.
LLVM_NODISCARD AttributeList addParamAttribute(LLVMContext &C, unsigned ArgNo, Attribute::AttrKind Kind) const
Add an argument attribute to the list.
The instances of the Type class are immutable: once they are created, they are never changed...
This is an important class for using LLVM in a threaded context.
Conditional or Unconditional Branch instruction.
static BlockAddress * get(Function *F, BasicBlock *BB)
Return a BlockAddress for the specified function and basic block.
This function has undefined behavior.
This is an important base class in LLVM.
void copyAttributesFrom(const Function *Src)
copyAttributesFrom - copy all additional attributes (those not needed to create a Function) from the ...
This file contains the declarations for the subclasses of Constant, which represent the different fla...
const Instruction & front() const
AttributeList getAttributes() const
Get the parameter attributes of the call.
FunctionType * getFunctionType() const
static const char *const kDFSanExternShadowPtrMask
ValTy * getArgument(unsigned ArgNo) const
unsigned getNumParams() const
Return the number of fixed parameters this function type requires.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
param_iterator param_begin() const
static Type * getVoidTy(LLVMContext &C)
void splice(iterator where, iplist_impl &L2)
static cl::opt< bool > ClDebugNonzeroLabels("dfsan-debug-nonzero-labels", cl::desc("Insert calls to __dfsan_nonzero_label on observing a parameter, " "load or return with a nonzero label"), cl::Hidden)
unsigned getAddressSpace() const
void setCallingConv(CallingConv::ID CC)
static FunctionType * get(Type *Result, ArrayRef< Type *> Params, bool isVarArg)
This static method is the primary way of constructing a FunctionType.
Value * getPointerOperand()
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="")
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
self_iterator getIterator()
static std::unique_ptr< SpecialCaseList > createOrDie(const std::vector< std::string > &Paths, llvm::vfs::FileSystem &FS)
Parses the special case list entries from files.
Class to represent integer types.
const Value * getCondition() const
static UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
const Constant * stripPointerCasts() const
static PointerType * getInt8PtrTy(LLVMContext &C, unsigned AS=0)
const std::string & getModuleIdentifier() const
Get the module identifier which is, essentially, the name of the module.
MDNode * createBranchWeights(uint32_t TrueWeight, uint32_t FalseWeight)
Return metadata containing two branch weights.
Value * CreateMul(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Value * CreateTrunc(Value *V, Type *DestTy, const Twine &Name="")
This struct is a compact representation of a valid (non-zero power of two) alignment.
Triple - Helper class for working with autoconf configuration names.
ConstantInt * getVolatileCst() const
void setSuccessor(unsigned idx, BasicBlock *NewSucc)
Value * CreateGEP(Value *Ptr, ArrayRef< Value *> IdxList, const Twine &Name="")
static IntegerType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing an IntegerType.
void addParamAttr(unsigned ArgNo, Attribute::AttrKind Kind)
Adds the attribute to the indicated argument.
Iterator for intrusive lists based on ilist_node.
unsigned getNumOperands() const
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
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.
This struct is a compact representation of a valid (power of two) or undefined (0) alignment...
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.
Value * CreateInsertElement(Value *Vec, Value *NewElt, Value *Idx, const Twine &Name="")
unsigned arg_size() const
Type * getReturnType() const
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 ConstantInt * getSigned(IntegerType *Ty, int64_t V)
Return a ConstantInt with the specified value for the specified type.
static BranchInst * Create(BasicBlock *IfTrue, Instruction *InsertBefore=nullptr)
static PHINode * Create(Type *Ty, unsigned NumReservedValues, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
Constructors - NumReservedValues is a hint for the number of incoming edges that this phi node will h...
std::string utostr(uint64_t X, bool isNeg=false)
User::op_iterator arg_iterator
The type of iterator to use when looping over actual arguments at this call site. ...
unsigned getNumIncomingValues() const
Return the number of incoming edges.
void setLinkage(LinkageTypes LT)
void setOperand(unsigned i, Value *Val)
The access may modify the value stored in memory.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
static cl::opt< bool > ClPreserveAlignment("dfsan-preserve-alignment", cl::desc("respect alignment requirements provided by input IR"), cl::Hidden, cl::init(false))
FunctionType * getFunctionType() const
Returns the FunctionType for me.
Class to represent vector types.
const Module * getModule() const
Return the module owning the function this instruction belongs to or nullptr it the function does not...
unsigned getNumAttrSets() const
LinkageTypes
An enumeration for the kinds of linkage for global values.
BBTy * getParent() const
Get the basic block containing the call site.
iterator_range< user_iterator > users()
Value * CreateShl(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
const Value * getFalseValue() const
void append(in_iter in_start, in_iter in_end)
Add the specified range to the end of the SmallVector.
Defines the virtual file system interface vfs::FileSystem.
void removeAttributes(unsigned i, const AttrBuilder &Attrs)
removes the attributes from the list of attributes.
This class wraps the llvm.memcpy/memmove intrinsics.
LLVM_NODISCARD AttributeList addAttribute(LLVMContext &C, unsigned Index, Attribute::AttrKind Kind) const
Add an attribute to the attribute set at the given index.
unsigned getAlignment() const
Return the alignment of the access that is being performed.
static IntegerType * getInt32Ty(LLVMContext &C)
static cl::opt< bool > ClCombinePointerLabelsOnLoad("dfsan-combine-pointer-labels-on-load", cl::desc("Combine the label of the pointer with the label of the data when " "loading from memory."), cl::Hidden, cl::init(true))
Value * CreateConstGEP2_64(Type *Ty, Value *Ptr, uint64_t Idx0, uint64_t Idx1, const Twine &Name="")
static VectorType * get(Type *ElementType, ElementCount EC)
This static method is the primary way to construct an VectorType.
StringRef getName() const
Return a constant reference to the value's name.
user_iterator_impl< User > user_iterator
ModulePass class - This class is used to implement unstructured interprocedural optimizations and ana...
void setAlignment(MaybeAlign Alignment)
static ArrayType * get(Type *ElementType, uint64_t NumElements)
This static method is the primary way to construct an ArrayType.
void setAttributes(AttributeList A)
Set the parameter attributes for this call.
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
Type * getValueType() const
const BasicBlockListType & getBasicBlockList() const
Get the underlying elements of the Function...
CallInst * CreateCall(FunctionType *FTy, Value *Callee, ArrayRef< Value *> Args=None, const Twine &Name="", MDNode *FPMathTag=nullptr)
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.
Value * getReturnValue() const
Convenience accessor. Returns null if there is no return value.
Tail - This calling convention attemps to make calls as fast as possible while guaranteeing that tail...
bool removeUnreachableBlocks(Function &F, DomTreeUpdater *DTU=nullptr, MemorySSAUpdater *MSSAU=nullptr)
Remove all blocks that can not be reached from the function's entry.
unsigned getAlignment() const
Return the alignment of the access that is being performed FIXME: Remove this function once transitio...
static StringRef GetGlobalTypeString(const GlobalValue &G)
Value * CreateAnd(Value *LHS, Value *RHS, const Twine &Name="")
Value * CreatePtrToInt(Value *V, Type *DestTy, const Twine &Name="")
const std::string & getModuleInlineAsm() const
Get any module-scope inline assembly blocks.
bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
iterator_range< df_iterator< T > > depth_first(const T &G)
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
user_iterator user_begin()
Module * getParent()
Get the module that this global value is contained inside of...
LLVM Value Representation.
BranchInst * CreateBr(BasicBlock *Dest)
Create an unconditional 'br label X' instruction.
AttrBuilder typeIncompatible(Type *Ty)
Which attributes cannot be applied to a type.
AttributeSet getFnAttributes() const
The function attributes are returned.
ModulePass * createDataFlowSanitizerPass(const std::vector< std::string > &ABIListFiles=std::vector< std::string >(), void *(*getArgTLS)()=nullptr, void *(*getRetValTLS)()=nullptr)
Value * CreateLShr(Value *LHS, Value *RHS, const Twine &Name="", bool isExact=false)
Value * getSource() const
This is just like getRawSource, but it strips off any cast instructions that feed it...
StringRef - Represent a constant reference to a string, i.e.
Value * CreateInsertValue(Value *Agg, Value *Val, ArrayRef< unsigned > Idxs, const Twine &Name="")
Value * getPointerOperand()
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
Instruction * SplitBlockAndInsertIfThen(Value *Cond, Instruction *SplitBefore, bool Unreachable, MDNode *BranchWeights=nullptr, DominatorTree *DT=nullptr, LoopInfo *LI=nullptr, BasicBlock *ThenBlock=nullptr)
Split the containing block at the specified instruction - everything before SplitBefore stays in the ...
PointerType * getType() const
Global values are always pointers.
static AttributeList get(LLVMContext &C, ArrayRef< std::pair< unsigned, Attribute >> Attrs)
Create an AttributeList with the specified parameters in it.
const BasicBlock * getParent() const
an instruction to allocate memory on the stack
This instruction inserts a struct field of array element value into an aggregate value.