1 //===-- DataFlowSanitizer.cpp - dynamic data flow analysis ----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 /// This file is a part of DataFlowSanitizer, a generalised dynamic data flow
13 /// Unlike other Sanitizer tools, this tool is not designed to detect a specific
14 /// class of bugs on its own. Instead, it provides a generic dynamic data flow
15 /// analysis framework to be used by clients to help detect application-specific
16 /// issues within their own code.
18 /// The analysis is based on automatic propagation of data flow labels (also
19 /// known as taint labels) through a program as it performs computation. Each
20 /// byte of application memory is backed by two bytes of shadow memory which
21 /// hold the label. On Linux/x86_64, memory is laid out as follows:
23 /// +--------------------+ 0x800000000000 (top of memory)
24 /// | application memory |
25 /// +--------------------+ 0x700000008000 (kAppAddr)
29 /// +--------------------+ 0x200200000000 (kUnusedAddr)
31 /// +--------------------+ 0x200000000000 (kUnionTableAddr)
33 /// +--------------------+ 0x000000010000 (kShadowAddr)
34 /// | reserved by kernel |
35 /// +--------------------+ 0x000000000000
37 /// To derive a shadow memory address from an application memory address,
38 /// bits 44-46 are cleared to bring the address into the range
39 /// [0x000000008000,0x100000000000). Then the address is shifted left by 1 to
40 /// account for the double byte representation of shadow labels and move the
41 /// address into the shadow memory range. See the function
42 /// DataFlowSanitizer::getShadowAddress below.
44 /// For more information, please refer to the design document:
45 /// http://clang.llvm.org/docs/DataFlowSanitizerDesign.html
47 #include "llvm/Transforms/Instrumentation.h"
48 #include "llvm/ADT/DenseMap.h"
49 #include "llvm/ADT/DenseSet.h"
50 #include "llvm/ADT/DepthFirstIterator.h"
51 #include "llvm/Analysis/ValueTracking.h"
52 #include "llvm/IR/InlineAsm.h"
53 #include "llvm/IR/IRBuilder.h"
54 #include "llvm/IR/LLVMContext.h"
55 #include "llvm/IR/MDBuilder.h"
56 #include "llvm/IR/Type.h"
57 #include "llvm/IR/Value.h"
58 #include "llvm/InstVisitor.h"
59 #include "llvm/Pass.h"
60 #include "llvm/Support/CommandLine.h"
61 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
62 #include "llvm/Transforms/Utils/Local.h"
63 #include "llvm/Transforms/Utils/SpecialCaseList.h"
68 // The -dfsan-preserve-alignment flag controls whether this pass assumes that
69 // alignment requirements provided by the input IR are correct. For example,
70 // if the input IR contains a load with alignment 8, this flag will cause
71 // the shadow load to have alignment 16. This flag is disabled by default as
72 // we have unfortunately encountered too much code (including Clang itself;
73 // see PR14291) which performs misaligned access.
74 static cl::opt<bool> ClPreserveAlignment(
75 "dfsan-preserve-alignment",
76 cl::desc("respect alignment requirements provided by input IR"), cl::Hidden,
79 // The ABI list file controls how shadow parameters are passed. The pass treats
80 // every function labelled "uninstrumented" in the ABI list file as conforming
81 // to the "native" (i.e. unsanitized) ABI. Unless the ABI list contains
82 // additional annotations for those functions, a call to one of those functions
83 // will produce a warning message, as the labelling behaviour of the function is
84 // unknown. The other supported annotations are "functional" and "discard",
85 // which are described below under DataFlowSanitizer::WrapperKind.
86 static cl::opt<std::string> ClABIListFile(
88 cl::desc("File listing native ABI functions and how the pass treats them"),
91 // Controls whether the pass uses IA_Args or IA_TLS as the ABI for instrumented
92 // functions (see DataFlowSanitizer::InstrumentedABI below).
93 static cl::opt<bool> ClArgsABI(
95 cl::desc("Use the argument ABI rather than the TLS ABI"),
98 static cl::opt<bool> ClDebugNonzeroLabels(
99 "dfsan-debug-nonzero-labels",
100 cl::desc("Insert calls to __dfsan_nonzero_label on observing a parameter, "
101 "load or return with a nonzero label"),
106 class DataFlowSanitizer : public ModulePass {
107 friend struct DFSanFunction;
108 friend class DFSanVisitor;
114 /// Which ABI should be used for instrumented functions?
115 enum InstrumentedABI {
116 /// Argument and return value labels are passed through additional
117 /// arguments and by modifying the return type.
120 /// Argument and return value labels are passed through TLS variables
121 /// __dfsan_arg_tls and __dfsan_retval_tls.
125 /// How should calls to uninstrumented functions be handled?
127 /// This function is present in an uninstrumented form but we don't know
128 /// how it should be handled. Print a warning and call the function anyway.
129 /// Don't label the return value.
132 /// This function does not write to (user-accessible) memory, and its return
133 /// value is unlabelled.
136 /// This function does not write to (user-accessible) memory, and the label
137 /// of its return value is the union of the label of its arguments.
140 /// Instead of calling the function, a custom wrapper __dfsw_F is called,
141 /// where F is the name of the function. This function may wrap the
142 /// original function or provide its own implementation. This is similar to
143 /// the IA_Args ABI, except that IA_Args uses a struct return type to
144 /// pass the return value shadow in a register, while WK_Custom uses an
145 /// extra pointer argument to return the shadow. This allows the wrapped
146 /// form of the function type to be expressed in C.
153 IntegerType *ShadowTy;
154 PointerType *ShadowPtrTy;
155 IntegerType *IntptrTy;
156 ConstantInt *ZeroShadow;
157 ConstantInt *ShadowPtrMask;
158 ConstantInt *ShadowPtrMul;
161 void *(*GetArgTLSPtr)();
162 void *(*GetRetvalTLSPtr)();
164 Constant *GetRetvalTLS;
165 FunctionType *DFSanUnionFnTy;
166 FunctionType *DFSanUnionLoadFnTy;
167 FunctionType *DFSanUnimplementedFnTy;
168 FunctionType *DFSanSetLabelFnTy;
169 FunctionType *DFSanNonzeroLabelFnTy;
170 Constant *DFSanUnionFn;
171 Constant *DFSanUnionLoadFn;
172 Constant *DFSanUnimplementedFn;
173 Constant *DFSanSetLabelFn;
174 Constant *DFSanNonzeroLabelFn;
175 MDNode *ColdCallWeights;
176 OwningPtr<SpecialCaseList> ABIList;
177 DenseMap<Value *, Function *> UnwrappedFnMap;
178 AttributeSet ReadOnlyNoneAttrs;
180 Value *getShadowAddress(Value *Addr, Instruction *Pos);
181 Value *combineShadows(Value *V1, Value *V2, Instruction *Pos);
182 bool isInstrumented(const Function *F);
183 bool isInstrumented(const GlobalAlias *GA);
184 FunctionType *getArgsFunctionType(FunctionType *T);
185 FunctionType *getCustomFunctionType(FunctionType *T);
186 InstrumentedABI getInstrumentedABI();
187 WrapperKind getWrapperKind(Function *F);
188 void addGlobalNamePrefix(GlobalValue *GV);
191 DataFlowSanitizer(StringRef ABIListFile = StringRef(),
192 void *(*getArgTLS)() = 0, void *(*getRetValTLS)() = 0);
194 bool doInitialization(Module &M);
195 bool runOnModule(Module &M);
198 struct DFSanFunction {
199 DataFlowSanitizer &DFS;
201 DataFlowSanitizer::InstrumentedABI IA;
205 AllocaInst *LabelReturnAlloca;
206 DenseMap<Value *, Value *> ValShadowMap;
207 DenseMap<AllocaInst *, AllocaInst *> AllocaShadowMap;
208 std::vector<std::pair<PHINode *, PHINode *> > PHIFixups;
209 DenseSet<Instruction *> SkipInsts;
210 DenseSet<Value *> NonZeroChecks;
212 DFSanFunction(DataFlowSanitizer &DFS, Function *F, bool IsNativeABI)
213 : DFS(DFS), F(F), IA(DFS.getInstrumentedABI()),
214 IsNativeABI(IsNativeABI), ArgTLSPtr(0), RetvalTLSPtr(0),
215 LabelReturnAlloca(0) {}
216 Value *getArgTLSPtr();
217 Value *getArgTLS(unsigned Index, Instruction *Pos);
218 Value *getRetvalTLS();
219 Value *getShadow(Value *V);
220 void setShadow(Instruction *I, Value *Shadow);
221 Value *combineOperandShadows(Instruction *Inst);
222 Value *loadShadow(Value *ShadowAddr, uint64_t Size, uint64_t Align,
224 void storeShadow(Value *Addr, uint64_t Size, uint64_t Align, Value *Shadow,
228 class DFSanVisitor : public InstVisitor<DFSanVisitor> {
231 DFSanVisitor(DFSanFunction &DFSF) : DFSF(DFSF) {}
233 void visitOperandShadowInst(Instruction &I);
235 void visitBinaryOperator(BinaryOperator &BO);
236 void visitCastInst(CastInst &CI);
237 void visitCmpInst(CmpInst &CI);
238 void visitGetElementPtrInst(GetElementPtrInst &GEPI);
239 void visitLoadInst(LoadInst &LI);
240 void visitStoreInst(StoreInst &SI);
241 void visitReturnInst(ReturnInst &RI);
242 void visitCallSite(CallSite CS);
243 void visitPHINode(PHINode &PN);
244 void visitExtractElementInst(ExtractElementInst &I);
245 void visitInsertElementInst(InsertElementInst &I);
246 void visitShuffleVectorInst(ShuffleVectorInst &I);
247 void visitExtractValueInst(ExtractValueInst &I);
248 void visitInsertValueInst(InsertValueInst &I);
249 void visitAllocaInst(AllocaInst &I);
250 void visitSelectInst(SelectInst &I);
251 void visitMemSetInst(MemSetInst &I);
252 void visitMemTransferInst(MemTransferInst &I);
257 char DataFlowSanitizer::ID;
258 INITIALIZE_PASS(DataFlowSanitizer, "dfsan",
259 "DataFlowSanitizer: dynamic data flow analysis.", false, false)
261 ModulePass *llvm::createDataFlowSanitizerPass(StringRef ABIListFile,
262 void *(*getArgTLS)(),
263 void *(*getRetValTLS)()) {
264 return new DataFlowSanitizer(ABIListFile, getArgTLS, getRetValTLS);
267 DataFlowSanitizer::DataFlowSanitizer(StringRef ABIListFile,
268 void *(*getArgTLS)(),
269 void *(*getRetValTLS)())
270 : ModulePass(ID), GetArgTLSPtr(getArgTLS), GetRetvalTLSPtr(getRetValTLS),
271 ABIList(SpecialCaseList::createOrDie(ABIListFile.empty() ? ClABIListFile
275 FunctionType *DataFlowSanitizer::getArgsFunctionType(FunctionType *T) {
276 llvm::SmallVector<Type *, 4> ArgTypes;
277 std::copy(T->param_begin(), T->param_end(), std::back_inserter(ArgTypes));
278 for (unsigned i = 0, e = T->getNumParams(); i != e; ++i)
279 ArgTypes.push_back(ShadowTy);
281 ArgTypes.push_back(ShadowPtrTy);
282 Type *RetType = T->getReturnType();
283 if (!RetType->isVoidTy())
284 RetType = StructType::get(RetType, ShadowTy, (Type *)0);
285 return FunctionType::get(RetType, ArgTypes, T->isVarArg());
288 FunctionType *DataFlowSanitizer::getCustomFunctionType(FunctionType *T) {
289 assert(!T->isVarArg());
290 llvm::SmallVector<Type *, 4> ArgTypes;
291 std::copy(T->param_begin(), T->param_end(), std::back_inserter(ArgTypes));
292 for (unsigned i = 0, e = T->getNumParams(); i != e; ++i)
293 ArgTypes.push_back(ShadowTy);
294 Type *RetType = T->getReturnType();
295 if (!RetType->isVoidTy())
296 ArgTypes.push_back(ShadowPtrTy);
297 return FunctionType::get(T->getReturnType(), ArgTypes, false);
300 bool DataFlowSanitizer::doInitialization(Module &M) {
301 DL = getAnalysisIfAvailable<DataLayout>();
306 Ctx = &M.getContext();
307 ShadowTy = IntegerType::get(*Ctx, ShadowWidth);
308 ShadowPtrTy = PointerType::getUnqual(ShadowTy);
309 IntptrTy = DL->getIntPtrType(*Ctx);
310 ZeroShadow = ConstantInt::getSigned(ShadowTy, 0);
311 ShadowPtrMask = ConstantInt::getSigned(IntptrTy, ~0x700000000000LL);
312 ShadowPtrMul = ConstantInt::getSigned(IntptrTy, ShadowWidth / 8);
314 Type *DFSanUnionArgs[2] = { ShadowTy, ShadowTy };
316 FunctionType::get(ShadowTy, DFSanUnionArgs, /*isVarArg=*/ false);
317 Type *DFSanUnionLoadArgs[2] = { ShadowPtrTy, IntptrTy };
319 FunctionType::get(ShadowTy, DFSanUnionLoadArgs, /*isVarArg=*/ false);
320 DFSanUnimplementedFnTy = FunctionType::get(
321 Type::getVoidTy(*Ctx), Type::getInt8PtrTy(*Ctx), /*isVarArg=*/false);
322 Type *DFSanSetLabelArgs[3] = { ShadowTy, Type::getInt8PtrTy(*Ctx), IntptrTy };
323 DFSanSetLabelFnTy = FunctionType::get(Type::getVoidTy(*Ctx),
324 DFSanSetLabelArgs, /*isVarArg=*/false);
325 DFSanNonzeroLabelFnTy = FunctionType::get(
326 Type::getVoidTy(*Ctx), ArrayRef<Type *>(), /*isVarArg=*/false);
329 Type *ArgTLSTy = ArrayType::get(ShadowTy, 64);
331 GetArgTLS = ConstantExpr::getIntToPtr(
332 ConstantInt::get(IntptrTy, uintptr_t(GetArgTLSPtr)),
333 PointerType::getUnqual(
334 FunctionType::get(PointerType::getUnqual(ArgTLSTy), (Type *)0)));
336 if (GetRetvalTLSPtr) {
338 GetRetvalTLS = ConstantExpr::getIntToPtr(
339 ConstantInt::get(IntptrTy, uintptr_t(GetRetvalTLSPtr)),
340 PointerType::getUnqual(
341 FunctionType::get(PointerType::getUnqual(ShadowTy), (Type *)0)));
344 ColdCallWeights = MDBuilder(*Ctx).createBranchWeights(1, 1000);
348 bool DataFlowSanitizer::isInstrumented(const Function *F) {
349 return !ABIList->isIn(*F, "uninstrumented");
352 bool DataFlowSanitizer::isInstrumented(const GlobalAlias *GA) {
353 return !ABIList->isIn(*GA, "uninstrumented");
356 DataFlowSanitizer::InstrumentedABI DataFlowSanitizer::getInstrumentedABI() {
357 return ClArgsABI ? IA_Args : IA_TLS;
360 DataFlowSanitizer::WrapperKind DataFlowSanitizer::getWrapperKind(Function *F) {
361 if (ABIList->isIn(*F, "functional"))
362 return WK_Functional;
363 if (ABIList->isIn(*F, "discard"))
365 if (ABIList->isIn(*F, "custom"))
371 void DataFlowSanitizer::addGlobalNamePrefix(GlobalValue *GV) {
372 std::string GVName = GV->getName(), Prefix = "dfs$";
373 GV->setName(Prefix + GVName);
375 // Try to change the name of the function in module inline asm. We only do
376 // this for specific asm directives, currently only ".symver", to try to avoid
377 // corrupting asm which happens to contain the symbol name as a substring.
378 // Note that the substitution for .symver assumes that the versioned symbol
379 // also has an instrumented name.
380 std::string Asm = GV->getParent()->getModuleInlineAsm();
381 std::string SearchStr = ".symver " + GVName + ",";
382 size_t Pos = Asm.find(SearchStr);
383 if (Pos != std::string::npos) {
384 Asm.replace(Pos, SearchStr.size(),
385 ".symver " + Prefix + GVName + "," + Prefix);
386 GV->getParent()->setModuleInlineAsm(Asm);
390 bool DataFlowSanitizer::runOnModule(Module &M) {
394 if (ABIList->isIn(M, "skip"))
398 Type *ArgTLSTy = ArrayType::get(ShadowTy, 64);
399 ArgTLS = Mod->getOrInsertGlobal("__dfsan_arg_tls", ArgTLSTy);
400 if (GlobalVariable *G = dyn_cast<GlobalVariable>(ArgTLS))
401 G->setThreadLocalMode(GlobalVariable::InitialExecTLSModel);
403 if (!GetRetvalTLSPtr) {
404 RetvalTLS = Mod->getOrInsertGlobal("__dfsan_retval_tls", ShadowTy);
405 if (GlobalVariable *G = dyn_cast<GlobalVariable>(RetvalTLS))
406 G->setThreadLocalMode(GlobalVariable::InitialExecTLSModel);
409 DFSanUnionFn = Mod->getOrInsertFunction("__dfsan_union", DFSanUnionFnTy);
410 if (Function *F = dyn_cast<Function>(DFSanUnionFn)) {
411 F->addAttribute(AttributeSet::FunctionIndex, Attribute::ReadNone);
412 F->addAttribute(AttributeSet::ReturnIndex, Attribute::ZExt);
413 F->addAttribute(1, Attribute::ZExt);
414 F->addAttribute(2, Attribute::ZExt);
417 Mod->getOrInsertFunction("__dfsan_union_load", DFSanUnionLoadFnTy);
418 if (Function *F = dyn_cast<Function>(DFSanUnionLoadFn)) {
419 F->addAttribute(AttributeSet::ReturnIndex, Attribute::ZExt);
421 DFSanUnimplementedFn =
422 Mod->getOrInsertFunction("__dfsan_unimplemented", DFSanUnimplementedFnTy);
424 Mod->getOrInsertFunction("__dfsan_set_label", DFSanSetLabelFnTy);
425 if (Function *F = dyn_cast<Function>(DFSanSetLabelFn)) {
426 F->addAttribute(1, Attribute::ZExt);
428 DFSanNonzeroLabelFn =
429 Mod->getOrInsertFunction("__dfsan_nonzero_label", DFSanNonzeroLabelFnTy);
431 std::vector<Function *> FnsToInstrument;
432 llvm::SmallPtrSet<Function *, 2> FnsWithNativeABI;
433 for (Module::iterator i = M.begin(), e = M.end(); i != e; ++i) {
434 if (!i->isIntrinsic() &&
436 i != DFSanUnionLoadFn &&
437 i != DFSanUnimplementedFn &&
438 i != DFSanSetLabelFn &&
439 i != DFSanNonzeroLabelFn)
440 FnsToInstrument.push_back(&*i);
443 // Give function aliases prefixes when necessary.
444 for (Module::alias_iterator i = M.alias_begin(), e = M.alias_end(); i != e;) {
445 GlobalAlias *GA = &*i;
447 // Don't stop on weak. We assume people aren't playing games with the
448 // instrumentedness of overridden weak aliases.
449 if (Function *F = dyn_cast<Function>(
450 GA->resolveAliasedGlobal(/*stopOnWeak=*/false))) {
451 bool GAInst = isInstrumented(GA), FInst = isInstrumented(F);
452 if (GAInst && FInst) {
453 addGlobalNamePrefix(GA);
459 B.addAttribute(Attribute::ReadOnly).addAttribute(Attribute::ReadNone);
460 ReadOnlyNoneAttrs = AttributeSet::get(*Ctx, AttributeSet::FunctionIndex, B);
462 // First, change the ABI of every function in the module. ABI-listed
463 // functions keep their original ABI and get a wrapper function.
464 for (std::vector<Function *>::iterator i = FnsToInstrument.begin(),
465 e = FnsToInstrument.end();
468 FunctionType *FT = F.getFunctionType();
470 bool IsZeroArgsVoidRet = (FT->getNumParams() == 0 && !FT->isVarArg() &&
471 FT->getReturnType()->isVoidTy());
473 if (isInstrumented(&F)) {
474 // Instrumented functions get a 'dfs$' prefix. This allows us to more
475 // easily identify cases of mismatching ABIs.
476 if (getInstrumentedABI() == IA_Args && !IsZeroArgsVoidRet) {
477 FunctionType *NewFT = getArgsFunctionType(FT);
478 Function *NewF = Function::Create(NewFT, F.getLinkage(), "", &M);
479 NewF->copyAttributesFrom(&F);
480 NewF->removeAttributes(
481 AttributeSet::ReturnIndex,
482 AttributeFuncs::typeIncompatible(NewFT->getReturnType(),
483 AttributeSet::ReturnIndex));
484 for (Function::arg_iterator FArg = F.arg_begin(),
485 NewFArg = NewF->arg_begin(),
486 FArgEnd = F.arg_end();
487 FArg != FArgEnd; ++FArg, ++NewFArg) {
488 FArg->replaceAllUsesWith(NewFArg);
490 NewF->getBasicBlockList().splice(NewF->begin(), F.getBasicBlockList());
492 for (Function::use_iterator ui = F.use_begin(), ue = F.use_end();
494 BlockAddress *BA = dyn_cast<BlockAddress>(ui.getUse().getUser());
497 BA->replaceAllUsesWith(
498 BlockAddress::get(NewF, BA->getBasicBlock()));
502 F.replaceAllUsesWith(
503 ConstantExpr::getBitCast(NewF, PointerType::getUnqual(FT)));
507 addGlobalNamePrefix(NewF);
509 addGlobalNamePrefix(&F);
511 // Hopefully, nobody will try to indirectly call a vararg
513 } else if (FT->isVarArg()) {
514 UnwrappedFnMap[&F] = &F;
516 } else if (!IsZeroArgsVoidRet || getWrapperKind(&F) == WK_Custom) {
517 // Build a wrapper function for F. The wrapper simply calls F, and is
518 // added to FnsToInstrument so that any instrumentation according to its
519 // WrapperKind is done in the second pass below.
520 FunctionType *NewFT = getInstrumentedABI() == IA_Args
521 ? getArgsFunctionType(FT)
524 Function::Create(NewFT, GlobalValue::LinkOnceODRLinkage,
525 std::string("dfsw$") + F.getName(), &M);
526 NewF->copyAttributesFrom(&F);
527 NewF->removeAttributes(
528 AttributeSet::ReturnIndex,
529 AttributeFuncs::typeIncompatible(NewFT->getReturnType(),
530 AttributeSet::ReturnIndex));
531 if (getInstrumentedABI() == IA_TLS)
532 NewF->removeAttributes(AttributeSet::FunctionIndex,
535 BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", NewF);
536 std::vector<Value *> Args;
537 unsigned n = FT->getNumParams();
538 for (Function::arg_iterator ai = NewF->arg_begin(); n != 0; ++ai, --n)
539 Args.push_back(&*ai);
540 CallInst *CI = CallInst::Create(&F, Args, "", BB);
541 if (FT->getReturnType()->isVoidTy())
542 ReturnInst::Create(*Ctx, BB);
544 ReturnInst::Create(*Ctx, CI, BB);
546 Value *WrappedFnCst =
547 ConstantExpr::getBitCast(NewF, PointerType::getUnqual(FT));
548 F.replaceAllUsesWith(WrappedFnCst);
549 UnwrappedFnMap[WrappedFnCst] = &F;
552 if (!F.isDeclaration()) {
553 // This function is probably defining an interposition of an
554 // uninstrumented function and hence needs to keep the original ABI.
555 // But any functions it may call need to use the instrumented ABI, so
556 // we instrument it in a mode which preserves the original ABI.
557 FnsWithNativeABI.insert(&F);
559 // This code needs to rebuild the iterators, as they may be invalidated
560 // by the push_back, taking care that the new range does not include
561 // any functions added by this code.
562 size_t N = i - FnsToInstrument.begin(),
563 Count = e - FnsToInstrument.begin();
564 FnsToInstrument.push_back(&F);
565 i = FnsToInstrument.begin() + N;
566 e = FnsToInstrument.begin() + Count;
571 for (std::vector<Function *>::iterator i = FnsToInstrument.begin(),
572 e = FnsToInstrument.end();
574 if (!*i || (*i)->isDeclaration())
577 removeUnreachableBlocks(**i);
579 DFSanFunction DFSF(*this, *i, FnsWithNativeABI.count(*i));
581 // DFSanVisitor may create new basic blocks, which confuses df_iterator.
582 // Build a copy of the list before iterating over it.
583 llvm::SmallVector<BasicBlock *, 4> BBList;
584 std::copy(df_begin(&(*i)->getEntryBlock()), df_end(&(*i)->getEntryBlock()),
585 std::back_inserter(BBList));
587 for (llvm::SmallVector<BasicBlock *, 4>::iterator i = BBList.begin(),
590 Instruction *Inst = &(*i)->front();
592 // DFSanVisitor may split the current basic block, changing the current
593 // instruction's next pointer and moving the next instruction to the
594 // tail block from which we should continue.
595 Instruction *Next = Inst->getNextNode();
596 // DFSanVisitor may delete Inst, so keep track of whether it was a
598 bool IsTerminator = isa<TerminatorInst>(Inst);
599 if (!DFSF.SkipInsts.count(Inst))
600 DFSanVisitor(DFSF).visit(Inst);
607 // We will not necessarily be able to compute the shadow for every phi node
608 // until we have visited every block. Therefore, the code that handles phi
609 // nodes adds them to the PHIFixups list so that they can be properly
611 for (std::vector<std::pair<PHINode *, PHINode *> >::iterator
612 i = DFSF.PHIFixups.begin(),
613 e = DFSF.PHIFixups.end();
615 for (unsigned val = 0, n = i->first->getNumIncomingValues(); val != n;
617 i->second->setIncomingValue(
618 val, DFSF.getShadow(i->first->getIncomingValue(val)));
622 // -dfsan-debug-nonzero-labels will split the CFG in all kinds of crazy
623 // places (i.e. instructions in basic blocks we haven't even begun visiting
624 // yet). To make our life easier, do this work in a pass after the main
626 if (ClDebugNonzeroLabels) {
627 for (DenseSet<Value *>::iterator i = DFSF.NonZeroChecks.begin(),
628 e = DFSF.NonZeroChecks.end();
631 if (Instruction *I = dyn_cast<Instruction>(*i))
632 Pos = I->getNextNode();
634 Pos = DFSF.F->getEntryBlock().begin();
635 while (isa<PHINode>(Pos) || isa<AllocaInst>(Pos))
636 Pos = Pos->getNextNode();
637 IRBuilder<> IRB(Pos);
638 Instruction *NeInst = cast<Instruction>(
639 IRB.CreateICmpNE(*i, DFSF.DFS.ZeroShadow));
640 BranchInst *BI = cast<BranchInst>(SplitBlockAndInsertIfThen(
641 NeInst, /*Unreachable=*/ false, ColdCallWeights));
642 IRBuilder<> ThenIRB(BI);
643 ThenIRB.CreateCall(DFSF.DFS.DFSanNonzeroLabelFn);
651 Value *DFSanFunction::getArgTLSPtr() {
655 return ArgTLSPtr = DFS.ArgTLS;
657 IRBuilder<> IRB(F->getEntryBlock().begin());
658 return ArgTLSPtr = IRB.CreateCall(DFS.GetArgTLS);
661 Value *DFSanFunction::getRetvalTLS() {
665 return RetvalTLSPtr = DFS.RetvalTLS;
667 IRBuilder<> IRB(F->getEntryBlock().begin());
668 return RetvalTLSPtr = IRB.CreateCall(DFS.GetRetvalTLS);
671 Value *DFSanFunction::getArgTLS(unsigned Idx, Instruction *Pos) {
672 IRBuilder<> IRB(Pos);
673 return IRB.CreateConstGEP2_64(getArgTLSPtr(), 0, Idx);
676 Value *DFSanFunction::getShadow(Value *V) {
677 if (!isa<Argument>(V) && !isa<Instruction>(V))
678 return DFS.ZeroShadow;
679 Value *&Shadow = ValShadowMap[V];
681 if (Argument *A = dyn_cast<Argument>(V)) {
683 return DFS.ZeroShadow;
685 case DataFlowSanitizer::IA_TLS: {
686 Value *ArgTLSPtr = getArgTLSPtr();
687 Instruction *ArgTLSPos =
688 DFS.ArgTLS ? &*F->getEntryBlock().begin()
689 : cast<Instruction>(ArgTLSPtr)->getNextNode();
690 IRBuilder<> IRB(ArgTLSPos);
691 Shadow = IRB.CreateLoad(getArgTLS(A->getArgNo(), ArgTLSPos));
694 case DataFlowSanitizer::IA_Args: {
695 unsigned ArgIdx = A->getArgNo() + F->getArgumentList().size() / 2;
696 Function::arg_iterator i = F->arg_begin();
700 assert(Shadow->getType() == DFS.ShadowTy);
704 NonZeroChecks.insert(Shadow);
706 Shadow = DFS.ZeroShadow;
712 void DFSanFunction::setShadow(Instruction *I, Value *Shadow) {
713 assert(!ValShadowMap.count(I));
714 assert(Shadow->getType() == DFS.ShadowTy);
715 ValShadowMap[I] = Shadow;
718 Value *DataFlowSanitizer::getShadowAddress(Value *Addr, Instruction *Pos) {
719 assert(Addr != RetvalTLS && "Reinstrumenting?");
720 IRBuilder<> IRB(Pos);
721 return IRB.CreateIntToPtr(
723 IRB.CreateAnd(IRB.CreatePtrToInt(Addr, IntptrTy), ShadowPtrMask),
728 // Generates IR to compute the union of the two given shadows, inserting it
729 // before Pos. Returns the computed union Value.
730 Value *DataFlowSanitizer::combineShadows(Value *V1, Value *V2,
732 if (V1 == ZeroShadow)
734 if (V2 == ZeroShadow)
738 IRBuilder<> IRB(Pos);
739 BasicBlock *Head = Pos->getParent();
740 Value *Ne = IRB.CreateICmpNE(V1, V2);
741 Instruction *NeInst = dyn_cast<Instruction>(Ne);
743 BranchInst *BI = cast<BranchInst>(SplitBlockAndInsertIfThen(
744 NeInst, /*Unreachable=*/ false, ColdCallWeights));
745 IRBuilder<> ThenIRB(BI);
746 CallInst *Call = ThenIRB.CreateCall2(DFSanUnionFn, V1, V2);
747 Call->addAttribute(AttributeSet::ReturnIndex, Attribute::ZExt);
748 Call->addAttribute(1, Attribute::ZExt);
749 Call->addAttribute(2, Attribute::ZExt);
751 BasicBlock *Tail = BI->getSuccessor(0);
752 PHINode *Phi = PHINode::Create(ShadowTy, 2, "", Tail->begin());
753 Phi->addIncoming(Call, Call->getParent());
754 Phi->addIncoming(ZeroShadow, Head);
763 // A convenience function which folds the shadows of each of the operands
764 // of the provided instruction Inst, inserting the IR before Inst. Returns
765 // the computed union Value.
766 Value *DFSanFunction::combineOperandShadows(Instruction *Inst) {
767 if (Inst->getNumOperands() == 0)
768 return DFS.ZeroShadow;
770 Value *Shadow = getShadow(Inst->getOperand(0));
771 for (unsigned i = 1, n = Inst->getNumOperands(); i != n; ++i) {
772 Shadow = DFS.combineShadows(Shadow, getShadow(Inst->getOperand(i)), Inst);
777 void DFSanVisitor::visitOperandShadowInst(Instruction &I) {
778 Value *CombinedShadow = DFSF.combineOperandShadows(&I);
779 DFSF.setShadow(&I, CombinedShadow);
782 // Generates IR to load shadow corresponding to bytes [Addr, Addr+Size), where
783 // Addr has alignment Align, and take the union of each of those shadows.
784 Value *DFSanFunction::loadShadow(Value *Addr, uint64_t Size, uint64_t Align,
786 if (AllocaInst *AI = dyn_cast<AllocaInst>(Addr)) {
787 llvm::DenseMap<AllocaInst *, AllocaInst *>::iterator i =
788 AllocaShadowMap.find(AI);
789 if (i != AllocaShadowMap.end()) {
790 IRBuilder<> IRB(Pos);
791 return IRB.CreateLoad(i->second);
795 uint64_t ShadowAlign = Align * DFS.ShadowWidth / 8;
796 SmallVector<Value *, 2> Objs;
797 GetUnderlyingObjects(Addr, Objs, DFS.DL);
798 bool AllConstants = true;
799 for (SmallVector<Value *, 2>::iterator i = Objs.begin(), e = Objs.end();
801 if (isa<Function>(*i) || isa<BlockAddress>(*i))
803 if (isa<GlobalVariable>(*i) && cast<GlobalVariable>(*i)->isConstant())
806 AllConstants = false;
810 return DFS.ZeroShadow;
812 Value *ShadowAddr = DFS.getShadowAddress(Addr, Pos);
815 return DFS.ZeroShadow;
817 LoadInst *LI = new LoadInst(ShadowAddr, "", Pos);
818 LI->setAlignment(ShadowAlign);
822 IRBuilder<> IRB(Pos);
824 IRB.CreateGEP(ShadowAddr, ConstantInt::get(DFS.IntptrTy, 1));
825 return DFS.combineShadows(IRB.CreateAlignedLoad(ShadowAddr, ShadowAlign),
826 IRB.CreateAlignedLoad(ShadowAddr1, ShadowAlign),
830 if (Size % (64 / DFS.ShadowWidth) == 0) {
831 // Fast path for the common case where each byte has identical shadow: load
832 // shadow 64 bits at a time, fall out to a __dfsan_union_load call if any
833 // shadow is non-equal.
834 BasicBlock *FallbackBB = BasicBlock::Create(*DFS.Ctx, "", F);
835 IRBuilder<> FallbackIRB(FallbackBB);
836 CallInst *FallbackCall = FallbackIRB.CreateCall2(
837 DFS.DFSanUnionLoadFn, ShadowAddr, ConstantInt::get(DFS.IntptrTy, Size));
838 FallbackCall->addAttribute(AttributeSet::ReturnIndex, Attribute::ZExt);
840 // Compare each of the shadows stored in the loaded 64 bits to each other,
841 // by computing (WideShadow rotl ShadowWidth) == WideShadow.
842 IRBuilder<> IRB(Pos);
844 IRB.CreateBitCast(ShadowAddr, Type::getInt64PtrTy(*DFS.Ctx));
845 Value *WideShadow = IRB.CreateAlignedLoad(WideAddr, ShadowAlign);
846 Value *TruncShadow = IRB.CreateTrunc(WideShadow, DFS.ShadowTy);
847 Value *ShlShadow = IRB.CreateShl(WideShadow, DFS.ShadowWidth);
848 Value *ShrShadow = IRB.CreateLShr(WideShadow, 64 - DFS.ShadowWidth);
849 Value *RotShadow = IRB.CreateOr(ShlShadow, ShrShadow);
850 Value *ShadowsEq = IRB.CreateICmpEQ(WideShadow, RotShadow);
852 BasicBlock *Head = Pos->getParent();
853 BasicBlock *Tail = Head->splitBasicBlock(Pos);
854 // In the following code LastBr will refer to the previous basic block's
855 // conditional branch instruction, whose true successor is fixed up to point
856 // to the next block during the loop below or to the tail after the final
858 BranchInst *LastBr = BranchInst::Create(FallbackBB, FallbackBB, ShadowsEq);
859 ReplaceInstWithInst(Head->getTerminator(), LastBr);
861 for (uint64_t Ofs = 64 / DFS.ShadowWidth; Ofs != Size;
862 Ofs += 64 / DFS.ShadowWidth) {
863 BasicBlock *NextBB = BasicBlock::Create(*DFS.Ctx, "", F);
864 IRBuilder<> NextIRB(NextBB);
865 WideAddr = NextIRB.CreateGEP(WideAddr, ConstantInt::get(DFS.IntptrTy, 1));
866 Value *NextWideShadow = NextIRB.CreateAlignedLoad(WideAddr, ShadowAlign);
867 ShadowsEq = NextIRB.CreateICmpEQ(WideShadow, NextWideShadow);
868 LastBr->setSuccessor(0, NextBB);
869 LastBr = NextIRB.CreateCondBr(ShadowsEq, FallbackBB, FallbackBB);
872 LastBr->setSuccessor(0, Tail);
873 FallbackIRB.CreateBr(Tail);
874 PHINode *Shadow = PHINode::Create(DFS.ShadowTy, 2, "", &Tail->front());
875 Shadow->addIncoming(FallbackCall, FallbackBB);
876 Shadow->addIncoming(TruncShadow, LastBr->getParent());
880 IRBuilder<> IRB(Pos);
881 CallInst *FallbackCall = IRB.CreateCall2(
882 DFS.DFSanUnionLoadFn, ShadowAddr, ConstantInt::get(DFS.IntptrTy, Size));
883 FallbackCall->addAttribute(AttributeSet::ReturnIndex, Attribute::ZExt);
887 void DFSanVisitor::visitLoadInst(LoadInst &LI) {
888 uint64_t Size = DFSF.DFS.DL->getTypeStoreSize(LI.getType());
890 if (ClPreserveAlignment) {
891 Align = LI.getAlignment();
893 Align = DFSF.DFS.DL->getABITypeAlignment(LI.getType());
897 IRBuilder<> IRB(&LI);
898 Value *LoadedShadow =
899 DFSF.loadShadow(LI.getPointerOperand(), Size, Align, &LI);
900 Value *PtrShadow = DFSF.getShadow(LI.getPointerOperand());
901 Value *CombinedShadow = DFSF.DFS.combineShadows(LoadedShadow, PtrShadow, &LI);
902 if (CombinedShadow != DFSF.DFS.ZeroShadow)
903 DFSF.NonZeroChecks.insert(CombinedShadow);
905 DFSF.setShadow(&LI, CombinedShadow);
908 void DFSanFunction::storeShadow(Value *Addr, uint64_t Size, uint64_t Align,
909 Value *Shadow, Instruction *Pos) {
910 if (AllocaInst *AI = dyn_cast<AllocaInst>(Addr)) {
911 llvm::DenseMap<AllocaInst *, AllocaInst *>::iterator i =
912 AllocaShadowMap.find(AI);
913 if (i != AllocaShadowMap.end()) {
914 IRBuilder<> IRB(Pos);
915 IRB.CreateStore(Shadow, i->second);
920 uint64_t ShadowAlign = Align * DFS.ShadowWidth / 8;
921 IRBuilder<> IRB(Pos);
922 Value *ShadowAddr = DFS.getShadowAddress(Addr, Pos);
923 if (Shadow == DFS.ZeroShadow) {
924 IntegerType *ShadowTy = IntegerType::get(*DFS.Ctx, Size * DFS.ShadowWidth);
925 Value *ExtZeroShadow = ConstantInt::get(ShadowTy, 0);
926 Value *ExtShadowAddr =
927 IRB.CreateBitCast(ShadowAddr, PointerType::getUnqual(ShadowTy));
928 IRB.CreateAlignedStore(ExtZeroShadow, ExtShadowAddr, ShadowAlign);
932 const unsigned ShadowVecSize = 128 / DFS.ShadowWidth;
934 if (Size >= ShadowVecSize) {
935 VectorType *ShadowVecTy = VectorType::get(DFS.ShadowTy, ShadowVecSize);
936 Value *ShadowVec = UndefValue::get(ShadowVecTy);
937 for (unsigned i = 0; i != ShadowVecSize; ++i) {
938 ShadowVec = IRB.CreateInsertElement(
939 ShadowVec, Shadow, ConstantInt::get(Type::getInt32Ty(*DFS.Ctx), i));
941 Value *ShadowVecAddr =
942 IRB.CreateBitCast(ShadowAddr, PointerType::getUnqual(ShadowVecTy));
944 Value *CurShadowVecAddr = IRB.CreateConstGEP1_32(ShadowVecAddr, Offset);
945 IRB.CreateAlignedStore(ShadowVec, CurShadowVecAddr, ShadowAlign);
946 Size -= ShadowVecSize;
948 } while (Size >= ShadowVecSize);
949 Offset *= ShadowVecSize;
952 Value *CurShadowAddr = IRB.CreateConstGEP1_32(ShadowAddr, Offset);
953 IRB.CreateAlignedStore(Shadow, CurShadowAddr, ShadowAlign);
959 void DFSanVisitor::visitStoreInst(StoreInst &SI) {
961 DFSF.DFS.DL->getTypeStoreSize(SI.getValueOperand()->getType());
963 if (ClPreserveAlignment) {
964 Align = SI.getAlignment();
966 Align = DFSF.DFS.DL->getABITypeAlignment(SI.getValueOperand()->getType());
970 DFSF.storeShadow(SI.getPointerOperand(), Size, Align,
971 DFSF.getShadow(SI.getValueOperand()), &SI);
974 void DFSanVisitor::visitBinaryOperator(BinaryOperator &BO) {
975 visitOperandShadowInst(BO);
978 void DFSanVisitor::visitCastInst(CastInst &CI) { visitOperandShadowInst(CI); }
980 void DFSanVisitor::visitCmpInst(CmpInst &CI) { visitOperandShadowInst(CI); }
982 void DFSanVisitor::visitGetElementPtrInst(GetElementPtrInst &GEPI) {
983 visitOperandShadowInst(GEPI);
986 void DFSanVisitor::visitExtractElementInst(ExtractElementInst &I) {
987 visitOperandShadowInst(I);
990 void DFSanVisitor::visitInsertElementInst(InsertElementInst &I) {
991 visitOperandShadowInst(I);
994 void DFSanVisitor::visitShuffleVectorInst(ShuffleVectorInst &I) {
995 visitOperandShadowInst(I);
998 void DFSanVisitor::visitExtractValueInst(ExtractValueInst &I) {
999 visitOperandShadowInst(I);
1002 void DFSanVisitor::visitInsertValueInst(InsertValueInst &I) {
1003 visitOperandShadowInst(I);
1006 void DFSanVisitor::visitAllocaInst(AllocaInst &I) {
1007 bool AllLoadsStores = true;
1008 for (Instruction::use_iterator i = I.use_begin(), e = I.use_end(); i != e;
1010 if (isa<LoadInst>(*i))
1013 if (StoreInst *SI = dyn_cast<StoreInst>(*i)) {
1014 if (SI->getPointerOperand() == &I)
1018 AllLoadsStores = false;
1021 if (AllLoadsStores) {
1022 IRBuilder<> IRB(&I);
1023 DFSF.AllocaShadowMap[&I] = IRB.CreateAlloca(DFSF.DFS.ShadowTy);
1025 DFSF.setShadow(&I, DFSF.DFS.ZeroShadow);
1028 void DFSanVisitor::visitSelectInst(SelectInst &I) {
1029 Value *CondShadow = DFSF.getShadow(I.getCondition());
1030 Value *TrueShadow = DFSF.getShadow(I.getTrueValue());
1031 Value *FalseShadow = DFSF.getShadow(I.getFalseValue());
1033 if (isa<VectorType>(I.getCondition()->getType())) {
1035 &I, DFSF.DFS.combineShadows(
1037 DFSF.DFS.combineShadows(TrueShadow, FalseShadow, &I), &I));
1040 if (TrueShadow == FalseShadow) {
1041 ShadowSel = TrueShadow;
1044 SelectInst::Create(I.getCondition(), TrueShadow, FalseShadow, "", &I);
1046 DFSF.setShadow(&I, DFSF.DFS.combineShadows(CondShadow, ShadowSel, &I));
1050 void DFSanVisitor::visitMemSetInst(MemSetInst &I) {
1051 IRBuilder<> IRB(&I);
1052 Value *ValShadow = DFSF.getShadow(I.getValue());
1054 DFSF.DFS.DFSanSetLabelFn, ValShadow,
1055 IRB.CreateBitCast(I.getDest(), Type::getInt8PtrTy(*DFSF.DFS.Ctx)),
1056 IRB.CreateZExtOrTrunc(I.getLength(), DFSF.DFS.IntptrTy));
1059 void DFSanVisitor::visitMemTransferInst(MemTransferInst &I) {
1060 IRBuilder<> IRB(&I);
1061 Value *DestShadow = DFSF.DFS.getShadowAddress(I.getDest(), &I);
1062 Value *SrcShadow = DFSF.DFS.getShadowAddress(I.getSource(), &I);
1063 Value *LenShadow = IRB.CreateMul(
1065 ConstantInt::get(I.getLength()->getType(), DFSF.DFS.ShadowWidth / 8));
1067 if (ClPreserveAlignment) {
1068 AlignShadow = IRB.CreateMul(I.getAlignmentCst(),
1069 ConstantInt::get(I.getAlignmentCst()->getType(),
1070 DFSF.DFS.ShadowWidth / 8));
1072 AlignShadow = ConstantInt::get(I.getAlignmentCst()->getType(),
1073 DFSF.DFS.ShadowWidth / 8);
1075 Type *Int8Ptr = Type::getInt8PtrTy(*DFSF.DFS.Ctx);
1076 DestShadow = IRB.CreateBitCast(DestShadow, Int8Ptr);
1077 SrcShadow = IRB.CreateBitCast(SrcShadow, Int8Ptr);
1078 IRB.CreateCall5(I.getCalledValue(), DestShadow, SrcShadow, LenShadow,
1079 AlignShadow, I.getVolatileCst());
1082 void DFSanVisitor::visitReturnInst(ReturnInst &RI) {
1083 if (!DFSF.IsNativeABI && RI.getReturnValue()) {
1085 case DataFlowSanitizer::IA_TLS: {
1086 Value *S = DFSF.getShadow(RI.getReturnValue());
1087 IRBuilder<> IRB(&RI);
1088 IRB.CreateStore(S, DFSF.getRetvalTLS());
1091 case DataFlowSanitizer::IA_Args: {
1092 IRBuilder<> IRB(&RI);
1093 Type *RT = DFSF.F->getFunctionType()->getReturnType();
1095 IRB.CreateInsertValue(UndefValue::get(RT), RI.getReturnValue(), 0);
1097 IRB.CreateInsertValue(InsVal, DFSF.getShadow(RI.getReturnValue()), 1);
1098 RI.setOperand(0, InsShadow);
1105 void DFSanVisitor::visitCallSite(CallSite CS) {
1106 Function *F = CS.getCalledFunction();
1107 if ((F && F->isIntrinsic()) || isa<InlineAsm>(CS.getCalledValue())) {
1108 visitOperandShadowInst(*CS.getInstruction());
1112 IRBuilder<> IRB(CS.getInstruction());
1114 DenseMap<Value *, Function *>::iterator i =
1115 DFSF.DFS.UnwrappedFnMap.find(CS.getCalledValue());
1116 if (i != DFSF.DFS.UnwrappedFnMap.end()) {
1117 Function *F = i->second;
1118 switch (DFSF.DFS.getWrapperKind(F)) {
1119 case DataFlowSanitizer::WK_Warning: {
1120 CS.setCalledFunction(F);
1121 IRB.CreateCall(DFSF.DFS.DFSanUnimplementedFn,
1122 IRB.CreateGlobalStringPtr(F->getName()));
1123 DFSF.setShadow(CS.getInstruction(), DFSF.DFS.ZeroShadow);
1126 case DataFlowSanitizer::WK_Discard: {
1127 CS.setCalledFunction(F);
1128 DFSF.setShadow(CS.getInstruction(), DFSF.DFS.ZeroShadow);
1131 case DataFlowSanitizer::WK_Functional: {
1132 CS.setCalledFunction(F);
1133 visitOperandShadowInst(*CS.getInstruction());
1136 case DataFlowSanitizer::WK_Custom: {
1137 // Don't try to handle invokes of custom functions, it's too complicated.
1138 // Instead, invoke the dfsw$ wrapper, which will in turn call the __dfsw_
1140 if (CallInst *CI = dyn_cast<CallInst>(CS.getInstruction())) {
1141 FunctionType *FT = F->getFunctionType();
1142 FunctionType *CustomFT = DFSF.DFS.getCustomFunctionType(FT);
1143 std::string CustomFName = "__dfsw_";
1144 CustomFName += F->getName();
1146 DFSF.DFS.Mod->getOrInsertFunction(CustomFName, CustomFT);
1147 if (Function *CustomFn = dyn_cast<Function>(CustomF)) {
1148 CustomFn->copyAttributesFrom(F);
1150 // Custom functions returning non-void will write to the return label.
1151 if (!FT->getReturnType()->isVoidTy()) {
1152 CustomFn->removeAttributes(AttributeSet::FunctionIndex,
1153 DFSF.DFS.ReadOnlyNoneAttrs);
1157 std::vector<Value *> Args;
1159 CallSite::arg_iterator i = CS.arg_begin();
1160 for (unsigned n = FT->getNumParams(); n != 0; ++i, --n)
1164 for (unsigned n = FT->getNumParams(); n != 0; ++i, --n)
1165 Args.push_back(DFSF.getShadow(*i));
1167 if (!FT->getReturnType()->isVoidTy()) {
1168 if (!DFSF.LabelReturnAlloca) {
1169 DFSF.LabelReturnAlloca =
1170 new AllocaInst(DFSF.DFS.ShadowTy, "labelreturn",
1171 DFSF.F->getEntryBlock().begin());
1173 Args.push_back(DFSF.LabelReturnAlloca);
1176 CallInst *CustomCI = IRB.CreateCall(CustomF, Args);
1177 CustomCI->setCallingConv(CI->getCallingConv());
1178 CustomCI->setAttributes(CI->getAttributes());
1180 if (!FT->getReturnType()->isVoidTy()) {
1181 LoadInst *LabelLoad = IRB.CreateLoad(DFSF.LabelReturnAlloca);
1182 DFSF.setShadow(CustomCI, LabelLoad);
1185 CI->replaceAllUsesWith(CustomCI);
1186 CI->eraseFromParent();
1194 FunctionType *FT = cast<FunctionType>(
1195 CS.getCalledValue()->getType()->getPointerElementType());
1196 if (DFSF.DFS.getInstrumentedABI() == DataFlowSanitizer::IA_TLS) {
1197 for (unsigned i = 0, n = FT->getNumParams(); i != n; ++i) {
1198 IRB.CreateStore(DFSF.getShadow(CS.getArgument(i)),
1199 DFSF.getArgTLS(i, CS.getInstruction()));
1203 Instruction *Next = 0;
1204 if (!CS.getType()->isVoidTy()) {
1205 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
1206 if (II->getNormalDest()->getSinglePredecessor()) {
1207 Next = II->getNormalDest()->begin();
1210 SplitEdge(II->getParent(), II->getNormalDest(), &DFSF.DFS);
1211 Next = NewBB->begin();
1214 Next = CS->getNextNode();
1217 if (DFSF.DFS.getInstrumentedABI() == DataFlowSanitizer::IA_TLS) {
1218 IRBuilder<> NextIRB(Next);
1219 LoadInst *LI = NextIRB.CreateLoad(DFSF.getRetvalTLS());
1220 DFSF.SkipInsts.insert(LI);
1221 DFSF.setShadow(CS.getInstruction(), LI);
1222 DFSF.NonZeroChecks.insert(LI);
1226 // Do all instrumentation for IA_Args down here to defer tampering with the
1227 // CFG in a way that SplitEdge may be able to detect.
1228 if (DFSF.DFS.getInstrumentedABI() == DataFlowSanitizer::IA_Args) {
1229 FunctionType *NewFT = DFSF.DFS.getArgsFunctionType(FT);
1231 IRB.CreateBitCast(CS.getCalledValue(), PointerType::getUnqual(NewFT));
1232 std::vector<Value *> Args;
1234 CallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
1235 for (unsigned n = FT->getNumParams(); n != 0; ++i, --n)
1239 for (unsigned n = FT->getNumParams(); n != 0; ++i, --n)
1240 Args.push_back(DFSF.getShadow(*i));
1242 if (FT->isVarArg()) {
1243 unsigned VarArgSize = CS.arg_size() - FT->getNumParams();
1244 ArrayType *VarArgArrayTy = ArrayType::get(DFSF.DFS.ShadowTy, VarArgSize);
1245 AllocaInst *VarArgShadow =
1246 new AllocaInst(VarArgArrayTy, "", DFSF.F->getEntryBlock().begin());
1247 Args.push_back(IRB.CreateConstGEP2_32(VarArgShadow, 0, 0));
1248 for (unsigned n = 0; i != e; ++i, ++n) {
1249 IRB.CreateStore(DFSF.getShadow(*i),
1250 IRB.CreateConstGEP2_32(VarArgShadow, 0, n));
1256 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
1257 NewCS = IRB.CreateInvoke(Func, II->getNormalDest(), II->getUnwindDest(),
1260 NewCS = IRB.CreateCall(Func, Args);
1262 NewCS.setCallingConv(CS.getCallingConv());
1263 NewCS.setAttributes(CS.getAttributes().removeAttributes(
1264 *DFSF.DFS.Ctx, AttributeSet::ReturnIndex,
1265 AttributeFuncs::typeIncompatible(NewCS.getInstruction()->getType(),
1266 AttributeSet::ReturnIndex)));
1269 ExtractValueInst *ExVal =
1270 ExtractValueInst::Create(NewCS.getInstruction(), 0, "", Next);
1271 DFSF.SkipInsts.insert(ExVal);
1272 ExtractValueInst *ExShadow =
1273 ExtractValueInst::Create(NewCS.getInstruction(), 1, "", Next);
1274 DFSF.SkipInsts.insert(ExShadow);
1275 DFSF.setShadow(ExVal, ExShadow);
1276 DFSF.NonZeroChecks.insert(ExShadow);
1278 CS.getInstruction()->replaceAllUsesWith(ExVal);
1281 CS.getInstruction()->eraseFromParent();
1285 void DFSanVisitor::visitPHINode(PHINode &PN) {
1287 PHINode::Create(DFSF.DFS.ShadowTy, PN.getNumIncomingValues(), "", &PN);
1289 // Give the shadow phi node valid predecessors to fool SplitEdge into working.
1290 Value *UndefShadow = UndefValue::get(DFSF.DFS.ShadowTy);
1291 for (PHINode::block_iterator i = PN.block_begin(), e = PN.block_end(); i != e;
1293 ShadowPN->addIncoming(UndefShadow, *i);
1296 DFSF.PHIFixups.push_back(std::make_pair(&PN, ShadowPN));
1297 DFSF.setShadow(&PN, ShadowPN);