DataFlowSanitizer: Factor the wrapper builder out to buildWrapperFunction.
[oota-llvm.git] / lib / Transforms / Instrumentation / DataFlowSanitizer.cpp
1 //===-- DataFlowSanitizer.cpp - dynamic data flow analysis ----------------===//
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 /// \file
10 /// This file is a part of DataFlowSanitizer, a generalised dynamic data flow
11 /// analysis.
12 ///
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.
17 ///
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:
22 ///
23 /// +--------------------+ 0x800000000000 (top of memory)
24 /// | application memory |
25 /// +--------------------+ 0x700000008000 (kAppAddr)
26 /// |                    |
27 /// |       unused       |
28 /// |                    |
29 /// +--------------------+ 0x200200000000 (kUnusedAddr)
30 /// |    union table     |
31 /// +--------------------+ 0x200000000000 (kUnionTableAddr)
32 /// |   shadow memory    |
33 /// +--------------------+ 0x000000010000 (kShadowAddr)
34 /// | reserved by kernel |
35 /// +--------------------+ 0x000000000000
36 ///
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.
43 ///
44 /// For more information, please refer to the design document:
45 /// http://clang.llvm.org/docs/DataFlowSanitizerDesign.html
46
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"
64 #include <iterator>
65
66 using namespace llvm;
67
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,
77     cl::init(false));
78
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(
87     "dfsan-abilist",
88     cl::desc("File listing native ABI functions and how the pass treats them"),
89     cl::Hidden);
90
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(
94     "dfsan-args-abi",
95     cl::desc("Use the argument ABI rather than the TLS ABI"),
96     cl::Hidden);
97
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"),
102     cl::Hidden);
103
104 namespace {
105
106 class DataFlowSanitizer : public ModulePass {
107   friend struct DFSanFunction;
108   friend class DFSanVisitor;
109
110   enum {
111     ShadowWidth = 16
112   };
113
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.
118     IA_Args,
119
120     /// Argument and return value labels are passed through TLS variables
121     /// __dfsan_arg_tls and __dfsan_retval_tls.
122     IA_TLS
123   };
124
125   /// How should calls to uninstrumented functions be handled?
126   enum WrapperKind {
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.
130     WK_Warning,
131
132     /// This function does not write to (user-accessible) memory, and its return
133     /// value is unlabelled.
134     WK_Discard,
135
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.
138     WK_Functional,
139
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.
147     WK_Custom
148   };
149
150   DataLayout *DL;
151   Module *Mod;
152   LLVMContext *Ctx;
153   IntegerType *ShadowTy;
154   PointerType *ShadowPtrTy;
155   IntegerType *IntptrTy;
156   ConstantInt *ZeroShadow;
157   ConstantInt *ShadowPtrMask;
158   ConstantInt *ShadowPtrMul;
159   Constant *ArgTLS;
160   Constant *RetvalTLS;
161   void *(*GetArgTLSPtr)();
162   void *(*GetRetvalTLSPtr)();
163   Constant *GetArgTLS;
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;
179
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);
189   Function *buildWrapperFunction(Function *F, StringRef NewFName,
190                                  GlobalValue::LinkageTypes NewFLink,
191                                  FunctionType *NewFT);
192
193  public:
194   DataFlowSanitizer(StringRef ABIListFile = StringRef(),
195                     void *(*getArgTLS)() = 0, void *(*getRetValTLS)() = 0);
196   static char ID;
197   bool doInitialization(Module &M);
198   bool runOnModule(Module &M);
199 };
200
201 struct DFSanFunction {
202   DataFlowSanitizer &DFS;
203   Function *F;
204   DataFlowSanitizer::InstrumentedABI IA;
205   bool IsNativeABI;
206   Value *ArgTLSPtr;
207   Value *RetvalTLSPtr;
208   AllocaInst *LabelReturnAlloca;
209   DenseMap<Value *, Value *> ValShadowMap;
210   DenseMap<AllocaInst *, AllocaInst *> AllocaShadowMap;
211   std::vector<std::pair<PHINode *, PHINode *> > PHIFixups;
212   DenseSet<Instruction *> SkipInsts;
213   DenseSet<Value *> NonZeroChecks;
214
215   DFSanFunction(DataFlowSanitizer &DFS, Function *F, bool IsNativeABI)
216       : DFS(DFS), F(F), IA(DFS.getInstrumentedABI()),
217         IsNativeABI(IsNativeABI), ArgTLSPtr(0), RetvalTLSPtr(0),
218         LabelReturnAlloca(0) {}
219   Value *getArgTLSPtr();
220   Value *getArgTLS(unsigned Index, Instruction *Pos);
221   Value *getRetvalTLS();
222   Value *getShadow(Value *V);
223   void setShadow(Instruction *I, Value *Shadow);
224   Value *combineOperandShadows(Instruction *Inst);
225   Value *loadShadow(Value *ShadowAddr, uint64_t Size, uint64_t Align,
226                     Instruction *Pos);
227   void storeShadow(Value *Addr, uint64_t Size, uint64_t Align, Value *Shadow,
228                    Instruction *Pos);
229 };
230
231 class DFSanVisitor : public InstVisitor<DFSanVisitor> {
232  public:
233   DFSanFunction &DFSF;
234   DFSanVisitor(DFSanFunction &DFSF) : DFSF(DFSF) {}
235
236   void visitOperandShadowInst(Instruction &I);
237
238   void visitBinaryOperator(BinaryOperator &BO);
239   void visitCastInst(CastInst &CI);
240   void visitCmpInst(CmpInst &CI);
241   void visitGetElementPtrInst(GetElementPtrInst &GEPI);
242   void visitLoadInst(LoadInst &LI);
243   void visitStoreInst(StoreInst &SI);
244   void visitReturnInst(ReturnInst &RI);
245   void visitCallSite(CallSite CS);
246   void visitPHINode(PHINode &PN);
247   void visitExtractElementInst(ExtractElementInst &I);
248   void visitInsertElementInst(InsertElementInst &I);
249   void visitShuffleVectorInst(ShuffleVectorInst &I);
250   void visitExtractValueInst(ExtractValueInst &I);
251   void visitInsertValueInst(InsertValueInst &I);
252   void visitAllocaInst(AllocaInst &I);
253   void visitSelectInst(SelectInst &I);
254   void visitMemSetInst(MemSetInst &I);
255   void visitMemTransferInst(MemTransferInst &I);
256 };
257
258 }
259
260 char DataFlowSanitizer::ID;
261 INITIALIZE_PASS(DataFlowSanitizer, "dfsan",
262                 "DataFlowSanitizer: dynamic data flow analysis.", false, false)
263
264 ModulePass *llvm::createDataFlowSanitizerPass(StringRef ABIListFile,
265                                               void *(*getArgTLS)(),
266                                               void *(*getRetValTLS)()) {
267   return new DataFlowSanitizer(ABIListFile, getArgTLS, getRetValTLS);
268 }
269
270 DataFlowSanitizer::DataFlowSanitizer(StringRef ABIListFile,
271                                      void *(*getArgTLS)(),
272                                      void *(*getRetValTLS)())
273     : ModulePass(ID), GetArgTLSPtr(getArgTLS), GetRetvalTLSPtr(getRetValTLS),
274       ABIList(SpecialCaseList::createOrDie(ABIListFile.empty() ? ClABIListFile
275                                                                : ABIListFile)) {
276 }
277
278 FunctionType *DataFlowSanitizer::getArgsFunctionType(FunctionType *T) {
279   llvm::SmallVector<Type *, 4> ArgTypes;
280   std::copy(T->param_begin(), T->param_end(), std::back_inserter(ArgTypes));
281   for (unsigned i = 0, e = T->getNumParams(); i != e; ++i)
282     ArgTypes.push_back(ShadowTy);
283   if (T->isVarArg())
284     ArgTypes.push_back(ShadowPtrTy);
285   Type *RetType = T->getReturnType();
286   if (!RetType->isVoidTy())
287     RetType = StructType::get(RetType, ShadowTy, (Type *)0);
288   return FunctionType::get(RetType, ArgTypes, T->isVarArg());
289 }
290
291 FunctionType *DataFlowSanitizer::getCustomFunctionType(FunctionType *T) {
292   assert(!T->isVarArg());
293   llvm::SmallVector<Type *, 4> ArgTypes;
294   std::copy(T->param_begin(), T->param_end(), std::back_inserter(ArgTypes));
295   for (unsigned i = 0, e = T->getNumParams(); i != e; ++i)
296     ArgTypes.push_back(ShadowTy);
297   Type *RetType = T->getReturnType();
298   if (!RetType->isVoidTy())
299     ArgTypes.push_back(ShadowPtrTy);
300   return FunctionType::get(T->getReturnType(), ArgTypes, false);
301 }
302
303 bool DataFlowSanitizer::doInitialization(Module &M) {
304   DL = getAnalysisIfAvailable<DataLayout>();
305   if (!DL)
306     return false;
307
308   Mod = &M;
309   Ctx = &M.getContext();
310   ShadowTy = IntegerType::get(*Ctx, ShadowWidth);
311   ShadowPtrTy = PointerType::getUnqual(ShadowTy);
312   IntptrTy = DL->getIntPtrType(*Ctx);
313   ZeroShadow = ConstantInt::getSigned(ShadowTy, 0);
314   ShadowPtrMask = ConstantInt::getSigned(IntptrTy, ~0x700000000000LL);
315   ShadowPtrMul = ConstantInt::getSigned(IntptrTy, ShadowWidth / 8);
316
317   Type *DFSanUnionArgs[2] = { ShadowTy, ShadowTy };
318   DFSanUnionFnTy =
319       FunctionType::get(ShadowTy, DFSanUnionArgs, /*isVarArg=*/ false);
320   Type *DFSanUnionLoadArgs[2] = { ShadowPtrTy, IntptrTy };
321   DFSanUnionLoadFnTy =
322       FunctionType::get(ShadowTy, DFSanUnionLoadArgs, /*isVarArg=*/ false);
323   DFSanUnimplementedFnTy = FunctionType::get(
324       Type::getVoidTy(*Ctx), Type::getInt8PtrTy(*Ctx), /*isVarArg=*/false);
325   Type *DFSanSetLabelArgs[3] = { ShadowTy, Type::getInt8PtrTy(*Ctx), IntptrTy };
326   DFSanSetLabelFnTy = FunctionType::get(Type::getVoidTy(*Ctx),
327                                         DFSanSetLabelArgs, /*isVarArg=*/false);
328   DFSanNonzeroLabelFnTy = FunctionType::get(
329       Type::getVoidTy(*Ctx), ArrayRef<Type *>(), /*isVarArg=*/false);
330
331   if (GetArgTLSPtr) {
332     Type *ArgTLSTy = ArrayType::get(ShadowTy, 64);
333     ArgTLS = 0;
334     GetArgTLS = ConstantExpr::getIntToPtr(
335         ConstantInt::get(IntptrTy, uintptr_t(GetArgTLSPtr)),
336         PointerType::getUnqual(
337             FunctionType::get(PointerType::getUnqual(ArgTLSTy), (Type *)0)));
338   }
339   if (GetRetvalTLSPtr) {
340     RetvalTLS = 0;
341     GetRetvalTLS = ConstantExpr::getIntToPtr(
342         ConstantInt::get(IntptrTy, uintptr_t(GetRetvalTLSPtr)),
343         PointerType::getUnqual(
344             FunctionType::get(PointerType::getUnqual(ShadowTy), (Type *)0)));
345   }
346
347   ColdCallWeights = MDBuilder(*Ctx).createBranchWeights(1, 1000);
348   return true;
349 }
350
351 bool DataFlowSanitizer::isInstrumented(const Function *F) {
352   return !ABIList->isIn(*F, "uninstrumented");
353 }
354
355 bool DataFlowSanitizer::isInstrumented(const GlobalAlias *GA) {
356   return !ABIList->isIn(*GA, "uninstrumented");
357 }
358
359 DataFlowSanitizer::InstrumentedABI DataFlowSanitizer::getInstrumentedABI() {
360   return ClArgsABI ? IA_Args : IA_TLS;
361 }
362
363 DataFlowSanitizer::WrapperKind DataFlowSanitizer::getWrapperKind(Function *F) {
364   if (ABIList->isIn(*F, "functional"))
365     return WK_Functional;
366   if (ABIList->isIn(*F, "discard"))
367     return WK_Discard;
368   if (ABIList->isIn(*F, "custom"))
369     return WK_Custom;
370
371   return WK_Warning;
372 }
373
374 void DataFlowSanitizer::addGlobalNamePrefix(GlobalValue *GV) {
375   std::string GVName = GV->getName(), Prefix = "dfs$";
376   GV->setName(Prefix + GVName);
377
378   // Try to change the name of the function in module inline asm.  We only do
379   // this for specific asm directives, currently only ".symver", to try to avoid
380   // corrupting asm which happens to contain the symbol name as a substring.
381   // Note that the substitution for .symver assumes that the versioned symbol
382   // also has an instrumented name.
383   std::string Asm = GV->getParent()->getModuleInlineAsm();
384   std::string SearchStr = ".symver " + GVName + ",";
385   size_t Pos = Asm.find(SearchStr);
386   if (Pos != std::string::npos) {
387     Asm.replace(Pos, SearchStr.size(),
388                 ".symver " + Prefix + GVName + "," + Prefix);
389     GV->getParent()->setModuleInlineAsm(Asm);
390   }
391 }
392
393 Function *
394 DataFlowSanitizer::buildWrapperFunction(Function *F, StringRef NewFName,
395                                         GlobalValue::LinkageTypes NewFLink,
396                                         FunctionType *NewFT) {
397   FunctionType *FT = F->getFunctionType();
398   Function *NewF = Function::Create(NewFT, NewFLink, NewFName,
399                                     F->getParent());
400   NewF->copyAttributesFrom(F);
401   NewF->removeAttributes(
402       AttributeSet::ReturnIndex,
403       AttributeFuncs::typeIncompatible(NewFT->getReturnType(),
404                                        AttributeSet::ReturnIndex));
405
406   BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", NewF);
407   std::vector<Value *> Args;
408   unsigned n = FT->getNumParams();
409   for (Function::arg_iterator ai = NewF->arg_begin(); n != 0; ++ai, --n)
410     Args.push_back(&*ai);
411   CallInst *CI = CallInst::Create(F, Args, "", BB);
412   if (FT->getReturnType()->isVoidTy())
413     ReturnInst::Create(*Ctx, BB);
414   else
415     ReturnInst::Create(*Ctx, CI, BB);
416
417   return NewF;
418 }
419
420 bool DataFlowSanitizer::runOnModule(Module &M) {
421   if (!DL)
422     return false;
423
424   if (ABIList->isIn(M, "skip"))
425     return false;
426
427   if (!GetArgTLSPtr) {
428     Type *ArgTLSTy = ArrayType::get(ShadowTy, 64);
429     ArgTLS = Mod->getOrInsertGlobal("__dfsan_arg_tls", ArgTLSTy);
430     if (GlobalVariable *G = dyn_cast<GlobalVariable>(ArgTLS))
431       G->setThreadLocalMode(GlobalVariable::InitialExecTLSModel);
432   }
433   if (!GetRetvalTLSPtr) {
434     RetvalTLS = Mod->getOrInsertGlobal("__dfsan_retval_tls", ShadowTy);
435     if (GlobalVariable *G = dyn_cast<GlobalVariable>(RetvalTLS))
436       G->setThreadLocalMode(GlobalVariable::InitialExecTLSModel);
437   }
438
439   DFSanUnionFn = Mod->getOrInsertFunction("__dfsan_union", DFSanUnionFnTy);
440   if (Function *F = dyn_cast<Function>(DFSanUnionFn)) {
441     F->addAttribute(AttributeSet::FunctionIndex, Attribute::ReadNone);
442     F->addAttribute(AttributeSet::ReturnIndex, Attribute::ZExt);
443     F->addAttribute(1, Attribute::ZExt);
444     F->addAttribute(2, Attribute::ZExt);
445   }
446   DFSanUnionLoadFn =
447       Mod->getOrInsertFunction("__dfsan_union_load", DFSanUnionLoadFnTy);
448   if (Function *F = dyn_cast<Function>(DFSanUnionLoadFn)) {
449     F->addAttribute(AttributeSet::ReturnIndex, Attribute::ZExt);
450   }
451   DFSanUnimplementedFn =
452       Mod->getOrInsertFunction("__dfsan_unimplemented", DFSanUnimplementedFnTy);
453   DFSanSetLabelFn =
454       Mod->getOrInsertFunction("__dfsan_set_label", DFSanSetLabelFnTy);
455   if (Function *F = dyn_cast<Function>(DFSanSetLabelFn)) {
456     F->addAttribute(1, Attribute::ZExt);
457   }
458   DFSanNonzeroLabelFn =
459       Mod->getOrInsertFunction("__dfsan_nonzero_label", DFSanNonzeroLabelFnTy);
460
461   std::vector<Function *> FnsToInstrument;
462   llvm::SmallPtrSet<Function *, 2> FnsWithNativeABI;
463   for (Module::iterator i = M.begin(), e = M.end(); i != e; ++i) {
464     if (!i->isIntrinsic() &&
465         i != DFSanUnionFn &&
466         i != DFSanUnionLoadFn &&
467         i != DFSanUnimplementedFn &&
468         i != DFSanSetLabelFn &&
469         i != DFSanNonzeroLabelFn)
470       FnsToInstrument.push_back(&*i);
471   }
472
473   // Give function aliases prefixes when necessary.
474   for (Module::alias_iterator i = M.alias_begin(), e = M.alias_end(); i != e;) {
475     GlobalAlias *GA = &*i;
476     ++i;
477     // Don't stop on weak.  We assume people aren't playing games with the
478     // instrumentedness of overridden weak aliases.
479     if (Function *F = dyn_cast<Function>(
480             GA->resolveAliasedGlobal(/*stopOnWeak=*/false))) {
481       bool GAInst = isInstrumented(GA), FInst = isInstrumented(F);
482       if (GAInst && FInst) {
483         addGlobalNamePrefix(GA);
484       }
485     }
486   }
487
488   AttrBuilder B;
489   B.addAttribute(Attribute::ReadOnly).addAttribute(Attribute::ReadNone);
490   ReadOnlyNoneAttrs = AttributeSet::get(*Ctx, AttributeSet::FunctionIndex, B);
491
492   // First, change the ABI of every function in the module.  ABI-listed
493   // functions keep their original ABI and get a wrapper function.
494   for (std::vector<Function *>::iterator i = FnsToInstrument.begin(),
495                                          e = FnsToInstrument.end();
496        i != e; ++i) {
497     Function &F = **i;
498     FunctionType *FT = F.getFunctionType();
499
500     bool IsZeroArgsVoidRet = (FT->getNumParams() == 0 && !FT->isVarArg() &&
501                               FT->getReturnType()->isVoidTy());
502
503     if (isInstrumented(&F)) {
504       // Instrumented functions get a 'dfs$' prefix.  This allows us to more
505       // easily identify cases of mismatching ABIs.
506       if (getInstrumentedABI() == IA_Args && !IsZeroArgsVoidRet) {
507         FunctionType *NewFT = getArgsFunctionType(FT);
508         Function *NewF = Function::Create(NewFT, F.getLinkage(), "", &M);
509         NewF->copyAttributesFrom(&F);
510         NewF->removeAttributes(
511             AttributeSet::ReturnIndex,
512             AttributeFuncs::typeIncompatible(NewFT->getReturnType(),
513                                              AttributeSet::ReturnIndex));
514         for (Function::arg_iterator FArg = F.arg_begin(),
515                                     NewFArg = NewF->arg_begin(),
516                                     FArgEnd = F.arg_end();
517              FArg != FArgEnd; ++FArg, ++NewFArg) {
518           FArg->replaceAllUsesWith(NewFArg);
519         }
520         NewF->getBasicBlockList().splice(NewF->begin(), F.getBasicBlockList());
521
522         for (Function::use_iterator ui = F.use_begin(), ue = F.use_end();
523              ui != ue;) {
524           BlockAddress *BA = dyn_cast<BlockAddress>(ui.getUse().getUser());
525           ++ui;
526           if (BA) {
527             BA->replaceAllUsesWith(
528                 BlockAddress::get(NewF, BA->getBasicBlock()));
529             delete BA;
530           }
531         }
532         F.replaceAllUsesWith(
533             ConstantExpr::getBitCast(NewF, PointerType::getUnqual(FT)));
534         NewF->takeName(&F);
535         F.eraseFromParent();
536         *i = NewF;
537         addGlobalNamePrefix(NewF);
538       } else {
539         addGlobalNamePrefix(&F);
540       }
541                // Hopefully, nobody will try to indirectly call a vararg
542                // function... yet.
543     } else if (FT->isVarArg()) {
544       UnwrappedFnMap[&F] = &F;
545       *i = 0;
546     } else if (!IsZeroArgsVoidRet || getWrapperKind(&F) == WK_Custom) {
547       // Build a wrapper function for F.  The wrapper simply calls F, and is
548       // added to FnsToInstrument so that any instrumentation according to its
549       // WrapperKind is done in the second pass below.
550       FunctionType *NewFT = getInstrumentedABI() == IA_Args
551                                 ? getArgsFunctionType(FT)
552                                 : FT;
553       Function *NewF =
554           buildWrapperFunction(&F, std::string("dfsw$") + std::string(F.getName()),
555                                GlobalValue::LinkOnceODRLinkage, NewFT);
556       if (getInstrumentedABI() == IA_TLS)
557         NewF->removeAttributes(AttributeSet::FunctionIndex, ReadOnlyNoneAttrs);
558
559       Value *WrappedFnCst =
560           ConstantExpr::getBitCast(NewF, PointerType::getUnqual(FT));
561       F.replaceAllUsesWith(WrappedFnCst);
562       UnwrappedFnMap[WrappedFnCst] = &F;
563       *i = NewF;
564
565       if (!F.isDeclaration()) {
566         // This function is probably defining an interposition of an
567         // uninstrumented function and hence needs to keep the original ABI.
568         // But any functions it may call need to use the instrumented ABI, so
569         // we instrument it in a mode which preserves the original ABI.
570         FnsWithNativeABI.insert(&F);
571
572         // This code needs to rebuild the iterators, as they may be invalidated
573         // by the push_back, taking care that the new range does not include
574         // any functions added by this code.
575         size_t N = i - FnsToInstrument.begin(),
576                Count = e - FnsToInstrument.begin();
577         FnsToInstrument.push_back(&F);
578         i = FnsToInstrument.begin() + N;
579         e = FnsToInstrument.begin() + Count;
580       }
581     }
582   }
583
584   for (std::vector<Function *>::iterator i = FnsToInstrument.begin(),
585                                          e = FnsToInstrument.end();
586        i != e; ++i) {
587     if (!*i || (*i)->isDeclaration())
588       continue;
589
590     removeUnreachableBlocks(**i);
591
592     DFSanFunction DFSF(*this, *i, FnsWithNativeABI.count(*i));
593
594     // DFSanVisitor may create new basic blocks, which confuses df_iterator.
595     // Build a copy of the list before iterating over it.
596     llvm::SmallVector<BasicBlock *, 4> BBList;
597     std::copy(df_begin(&(*i)->getEntryBlock()), df_end(&(*i)->getEntryBlock()),
598               std::back_inserter(BBList));
599
600     for (llvm::SmallVector<BasicBlock *, 4>::iterator i = BBList.begin(),
601                                                       e = BBList.end();
602          i != e; ++i) {
603       Instruction *Inst = &(*i)->front();
604       while (1) {
605         // DFSanVisitor may split the current basic block, changing the current
606         // instruction's next pointer and moving the next instruction to the
607         // tail block from which we should continue.
608         Instruction *Next = Inst->getNextNode();
609         // DFSanVisitor may delete Inst, so keep track of whether it was a
610         // terminator.
611         bool IsTerminator = isa<TerminatorInst>(Inst);
612         if (!DFSF.SkipInsts.count(Inst))
613           DFSanVisitor(DFSF).visit(Inst);
614         if (IsTerminator)
615           break;
616         Inst = Next;
617       }
618     }
619
620     // We will not necessarily be able to compute the shadow for every phi node
621     // until we have visited every block.  Therefore, the code that handles phi
622     // nodes adds them to the PHIFixups list so that they can be properly
623     // handled here.
624     for (std::vector<std::pair<PHINode *, PHINode *> >::iterator
625              i = DFSF.PHIFixups.begin(),
626              e = DFSF.PHIFixups.end();
627          i != e; ++i) {
628       for (unsigned val = 0, n = i->first->getNumIncomingValues(); val != n;
629            ++val) {
630         i->second->setIncomingValue(
631             val, DFSF.getShadow(i->first->getIncomingValue(val)));
632       }
633     }
634
635     // -dfsan-debug-nonzero-labels will split the CFG in all kinds of crazy
636     // places (i.e. instructions in basic blocks we haven't even begun visiting
637     // yet).  To make our life easier, do this work in a pass after the main
638     // instrumentation.
639     if (ClDebugNonzeroLabels) {
640       for (DenseSet<Value *>::iterator i = DFSF.NonZeroChecks.begin(),
641                                        e = DFSF.NonZeroChecks.end();
642            i != e; ++i) {
643         Instruction *Pos;
644         if (Instruction *I = dyn_cast<Instruction>(*i))
645           Pos = I->getNextNode();
646         else
647           Pos = DFSF.F->getEntryBlock().begin();
648         while (isa<PHINode>(Pos) || isa<AllocaInst>(Pos))
649           Pos = Pos->getNextNode();
650         IRBuilder<> IRB(Pos);
651         Instruction *NeInst = cast<Instruction>(
652             IRB.CreateICmpNE(*i, DFSF.DFS.ZeroShadow));
653         BranchInst *BI = cast<BranchInst>(SplitBlockAndInsertIfThen(
654             NeInst, /*Unreachable=*/ false, ColdCallWeights));
655         IRBuilder<> ThenIRB(BI);
656         ThenIRB.CreateCall(DFSF.DFS.DFSanNonzeroLabelFn);
657       }
658     }
659   }
660
661   return false;
662 }
663
664 Value *DFSanFunction::getArgTLSPtr() {
665   if (ArgTLSPtr)
666     return ArgTLSPtr;
667   if (DFS.ArgTLS)
668     return ArgTLSPtr = DFS.ArgTLS;
669
670   IRBuilder<> IRB(F->getEntryBlock().begin());
671   return ArgTLSPtr = IRB.CreateCall(DFS.GetArgTLS);
672 }
673
674 Value *DFSanFunction::getRetvalTLS() {
675   if (RetvalTLSPtr)
676     return RetvalTLSPtr;
677   if (DFS.RetvalTLS)
678     return RetvalTLSPtr = DFS.RetvalTLS;
679
680   IRBuilder<> IRB(F->getEntryBlock().begin());
681   return RetvalTLSPtr = IRB.CreateCall(DFS.GetRetvalTLS);
682 }
683
684 Value *DFSanFunction::getArgTLS(unsigned Idx, Instruction *Pos) {
685   IRBuilder<> IRB(Pos);
686   return IRB.CreateConstGEP2_64(getArgTLSPtr(), 0, Idx);
687 }
688
689 Value *DFSanFunction::getShadow(Value *V) {
690   if (!isa<Argument>(V) && !isa<Instruction>(V))
691     return DFS.ZeroShadow;
692   Value *&Shadow = ValShadowMap[V];
693   if (!Shadow) {
694     if (Argument *A = dyn_cast<Argument>(V)) {
695       if (IsNativeABI)
696         return DFS.ZeroShadow;
697       switch (IA) {
698       case DataFlowSanitizer::IA_TLS: {
699         Value *ArgTLSPtr = getArgTLSPtr();
700         Instruction *ArgTLSPos =
701             DFS.ArgTLS ? &*F->getEntryBlock().begin()
702                        : cast<Instruction>(ArgTLSPtr)->getNextNode();
703         IRBuilder<> IRB(ArgTLSPos);
704         Shadow = IRB.CreateLoad(getArgTLS(A->getArgNo(), ArgTLSPos));
705         break;
706       }
707       case DataFlowSanitizer::IA_Args: {
708         unsigned ArgIdx = A->getArgNo() + F->getArgumentList().size() / 2;
709         Function::arg_iterator i = F->arg_begin();
710         while (ArgIdx--)
711           ++i;
712         Shadow = i;
713         assert(Shadow->getType() == DFS.ShadowTy);
714         break;
715       }
716       }
717       NonZeroChecks.insert(Shadow);
718     } else {
719       Shadow = DFS.ZeroShadow;
720     }
721   }
722   return Shadow;
723 }
724
725 void DFSanFunction::setShadow(Instruction *I, Value *Shadow) {
726   assert(!ValShadowMap.count(I));
727   assert(Shadow->getType() == DFS.ShadowTy);
728   ValShadowMap[I] = Shadow;
729 }
730
731 Value *DataFlowSanitizer::getShadowAddress(Value *Addr, Instruction *Pos) {
732   assert(Addr != RetvalTLS && "Reinstrumenting?");
733   IRBuilder<> IRB(Pos);
734   return IRB.CreateIntToPtr(
735       IRB.CreateMul(
736           IRB.CreateAnd(IRB.CreatePtrToInt(Addr, IntptrTy), ShadowPtrMask),
737           ShadowPtrMul),
738       ShadowPtrTy);
739 }
740
741 // Generates IR to compute the union of the two given shadows, inserting it
742 // before Pos.  Returns the computed union Value.
743 Value *DataFlowSanitizer::combineShadows(Value *V1, Value *V2,
744                                          Instruction *Pos) {
745   if (V1 == ZeroShadow)
746     return V2;
747   if (V2 == ZeroShadow)
748     return V1;
749   if (V1 == V2)
750     return V1;
751   IRBuilder<> IRB(Pos);
752   BasicBlock *Head = Pos->getParent();
753   Value *Ne = IRB.CreateICmpNE(V1, V2);
754   Instruction *NeInst = dyn_cast<Instruction>(Ne);
755   if (NeInst) {
756     BranchInst *BI = cast<BranchInst>(SplitBlockAndInsertIfThen(
757         NeInst, /*Unreachable=*/ false, ColdCallWeights));
758     IRBuilder<> ThenIRB(BI);
759     CallInst *Call = ThenIRB.CreateCall2(DFSanUnionFn, V1, V2);
760     Call->addAttribute(AttributeSet::ReturnIndex, Attribute::ZExt);
761     Call->addAttribute(1, Attribute::ZExt);
762     Call->addAttribute(2, Attribute::ZExt);
763
764     BasicBlock *Tail = BI->getSuccessor(0);
765     PHINode *Phi = PHINode::Create(ShadowTy, 2, "", Tail->begin());
766     Phi->addIncoming(Call, Call->getParent());
767     Phi->addIncoming(ZeroShadow, Head);
768     Pos = Phi;
769     return Phi;
770   } else {
771     assert(0 && "todo");
772     return 0;
773   }
774 }
775
776 // A convenience function which folds the shadows of each of the operands
777 // of the provided instruction Inst, inserting the IR before Inst.  Returns
778 // the computed union Value.
779 Value *DFSanFunction::combineOperandShadows(Instruction *Inst) {
780   if (Inst->getNumOperands() == 0)
781     return DFS.ZeroShadow;
782
783   Value *Shadow = getShadow(Inst->getOperand(0));
784   for (unsigned i = 1, n = Inst->getNumOperands(); i != n; ++i) {
785     Shadow = DFS.combineShadows(Shadow, getShadow(Inst->getOperand(i)), Inst);
786   }
787   return Shadow;
788 }
789
790 void DFSanVisitor::visitOperandShadowInst(Instruction &I) {
791   Value *CombinedShadow = DFSF.combineOperandShadows(&I);
792   DFSF.setShadow(&I, CombinedShadow);
793 }
794
795 // Generates IR to load shadow corresponding to bytes [Addr, Addr+Size), where
796 // Addr has alignment Align, and take the union of each of those shadows.
797 Value *DFSanFunction::loadShadow(Value *Addr, uint64_t Size, uint64_t Align,
798                                  Instruction *Pos) {
799   if (AllocaInst *AI = dyn_cast<AllocaInst>(Addr)) {
800     llvm::DenseMap<AllocaInst *, AllocaInst *>::iterator i =
801         AllocaShadowMap.find(AI);
802     if (i != AllocaShadowMap.end()) {
803       IRBuilder<> IRB(Pos);
804       return IRB.CreateLoad(i->second);
805     }
806   }
807
808   uint64_t ShadowAlign = Align * DFS.ShadowWidth / 8;
809   SmallVector<Value *, 2> Objs;
810   GetUnderlyingObjects(Addr, Objs, DFS.DL);
811   bool AllConstants = true;
812   for (SmallVector<Value *, 2>::iterator i = Objs.begin(), e = Objs.end();
813        i != e; ++i) {
814     if (isa<Function>(*i) || isa<BlockAddress>(*i))
815       continue;
816     if (isa<GlobalVariable>(*i) && cast<GlobalVariable>(*i)->isConstant())
817       continue;
818
819     AllConstants = false;
820     break;
821   }
822   if (AllConstants)
823     return DFS.ZeroShadow;
824
825   Value *ShadowAddr = DFS.getShadowAddress(Addr, Pos);
826   switch (Size) {
827   case 0:
828     return DFS.ZeroShadow;
829   case 1: {
830     LoadInst *LI = new LoadInst(ShadowAddr, "", Pos);
831     LI->setAlignment(ShadowAlign);
832     return LI;
833   }
834   case 2: {
835     IRBuilder<> IRB(Pos);
836     Value *ShadowAddr1 =
837         IRB.CreateGEP(ShadowAddr, ConstantInt::get(DFS.IntptrTy, 1));
838     return DFS.combineShadows(IRB.CreateAlignedLoad(ShadowAddr, ShadowAlign),
839                               IRB.CreateAlignedLoad(ShadowAddr1, ShadowAlign),
840                               Pos);
841   }
842   }
843   if (Size % (64 / DFS.ShadowWidth) == 0) {
844     // Fast path for the common case where each byte has identical shadow: load
845     // shadow 64 bits at a time, fall out to a __dfsan_union_load call if any
846     // shadow is non-equal.
847     BasicBlock *FallbackBB = BasicBlock::Create(*DFS.Ctx, "", F);
848     IRBuilder<> FallbackIRB(FallbackBB);
849     CallInst *FallbackCall = FallbackIRB.CreateCall2(
850         DFS.DFSanUnionLoadFn, ShadowAddr, ConstantInt::get(DFS.IntptrTy, Size));
851     FallbackCall->addAttribute(AttributeSet::ReturnIndex, Attribute::ZExt);
852
853     // Compare each of the shadows stored in the loaded 64 bits to each other,
854     // by computing (WideShadow rotl ShadowWidth) == WideShadow.
855     IRBuilder<> IRB(Pos);
856     Value *WideAddr =
857         IRB.CreateBitCast(ShadowAddr, Type::getInt64PtrTy(*DFS.Ctx));
858     Value *WideShadow = IRB.CreateAlignedLoad(WideAddr, ShadowAlign);
859     Value *TruncShadow = IRB.CreateTrunc(WideShadow, DFS.ShadowTy);
860     Value *ShlShadow = IRB.CreateShl(WideShadow, DFS.ShadowWidth);
861     Value *ShrShadow = IRB.CreateLShr(WideShadow, 64 - DFS.ShadowWidth);
862     Value *RotShadow = IRB.CreateOr(ShlShadow, ShrShadow);
863     Value *ShadowsEq = IRB.CreateICmpEQ(WideShadow, RotShadow);
864
865     BasicBlock *Head = Pos->getParent();
866     BasicBlock *Tail = Head->splitBasicBlock(Pos);
867     // In the following code LastBr will refer to the previous basic block's
868     // conditional branch instruction, whose true successor is fixed up to point
869     // to the next block during the loop below or to the tail after the final
870     // iteration.
871     BranchInst *LastBr = BranchInst::Create(FallbackBB, FallbackBB, ShadowsEq);
872     ReplaceInstWithInst(Head->getTerminator(), LastBr);
873
874     for (uint64_t Ofs = 64 / DFS.ShadowWidth; Ofs != Size;
875          Ofs += 64 / DFS.ShadowWidth) {
876       BasicBlock *NextBB = BasicBlock::Create(*DFS.Ctx, "", F);
877       IRBuilder<> NextIRB(NextBB);
878       WideAddr = NextIRB.CreateGEP(WideAddr, ConstantInt::get(DFS.IntptrTy, 1));
879       Value *NextWideShadow = NextIRB.CreateAlignedLoad(WideAddr, ShadowAlign);
880       ShadowsEq = NextIRB.CreateICmpEQ(WideShadow, NextWideShadow);
881       LastBr->setSuccessor(0, NextBB);
882       LastBr = NextIRB.CreateCondBr(ShadowsEq, FallbackBB, FallbackBB);
883     }
884
885     LastBr->setSuccessor(0, Tail);
886     FallbackIRB.CreateBr(Tail);
887     PHINode *Shadow = PHINode::Create(DFS.ShadowTy, 2, "", &Tail->front());
888     Shadow->addIncoming(FallbackCall, FallbackBB);
889     Shadow->addIncoming(TruncShadow, LastBr->getParent());
890     return Shadow;
891   }
892
893   IRBuilder<> IRB(Pos);
894   CallInst *FallbackCall = IRB.CreateCall2(
895       DFS.DFSanUnionLoadFn, ShadowAddr, ConstantInt::get(DFS.IntptrTy, Size));
896   FallbackCall->addAttribute(AttributeSet::ReturnIndex, Attribute::ZExt);
897   return FallbackCall;
898 }
899
900 void DFSanVisitor::visitLoadInst(LoadInst &LI) {
901   uint64_t Size = DFSF.DFS.DL->getTypeStoreSize(LI.getType());
902   uint64_t Align;
903   if (ClPreserveAlignment) {
904     Align = LI.getAlignment();
905     if (Align == 0)
906       Align = DFSF.DFS.DL->getABITypeAlignment(LI.getType());
907   } else {
908     Align = 1;
909   }
910   IRBuilder<> IRB(&LI);
911   Value *LoadedShadow =
912       DFSF.loadShadow(LI.getPointerOperand(), Size, Align, &LI);
913   Value *PtrShadow = DFSF.getShadow(LI.getPointerOperand());
914   Value *CombinedShadow = DFSF.DFS.combineShadows(LoadedShadow, PtrShadow, &LI);
915   if (CombinedShadow != DFSF.DFS.ZeroShadow)
916     DFSF.NonZeroChecks.insert(CombinedShadow);
917
918   DFSF.setShadow(&LI, CombinedShadow);
919 }
920
921 void DFSanFunction::storeShadow(Value *Addr, uint64_t Size, uint64_t Align,
922                                 Value *Shadow, Instruction *Pos) {
923   if (AllocaInst *AI = dyn_cast<AllocaInst>(Addr)) {
924     llvm::DenseMap<AllocaInst *, AllocaInst *>::iterator i =
925         AllocaShadowMap.find(AI);
926     if (i != AllocaShadowMap.end()) {
927       IRBuilder<> IRB(Pos);
928       IRB.CreateStore(Shadow, i->second);
929       return;
930     }
931   }
932
933   uint64_t ShadowAlign = Align * DFS.ShadowWidth / 8;
934   IRBuilder<> IRB(Pos);
935   Value *ShadowAddr = DFS.getShadowAddress(Addr, Pos);
936   if (Shadow == DFS.ZeroShadow) {
937     IntegerType *ShadowTy = IntegerType::get(*DFS.Ctx, Size * DFS.ShadowWidth);
938     Value *ExtZeroShadow = ConstantInt::get(ShadowTy, 0);
939     Value *ExtShadowAddr =
940         IRB.CreateBitCast(ShadowAddr, PointerType::getUnqual(ShadowTy));
941     IRB.CreateAlignedStore(ExtZeroShadow, ExtShadowAddr, ShadowAlign);
942     return;
943   }
944
945   const unsigned ShadowVecSize = 128 / DFS.ShadowWidth;
946   uint64_t Offset = 0;
947   if (Size >= ShadowVecSize) {
948     VectorType *ShadowVecTy = VectorType::get(DFS.ShadowTy, ShadowVecSize);
949     Value *ShadowVec = UndefValue::get(ShadowVecTy);
950     for (unsigned i = 0; i != ShadowVecSize; ++i) {
951       ShadowVec = IRB.CreateInsertElement(
952           ShadowVec, Shadow, ConstantInt::get(Type::getInt32Ty(*DFS.Ctx), i));
953     }
954     Value *ShadowVecAddr =
955         IRB.CreateBitCast(ShadowAddr, PointerType::getUnqual(ShadowVecTy));
956     do {
957       Value *CurShadowVecAddr = IRB.CreateConstGEP1_32(ShadowVecAddr, Offset);
958       IRB.CreateAlignedStore(ShadowVec, CurShadowVecAddr, ShadowAlign);
959       Size -= ShadowVecSize;
960       ++Offset;
961     } while (Size >= ShadowVecSize);
962     Offset *= ShadowVecSize;
963   }
964   while (Size > 0) {
965     Value *CurShadowAddr = IRB.CreateConstGEP1_32(ShadowAddr, Offset);
966     IRB.CreateAlignedStore(Shadow, CurShadowAddr, ShadowAlign);
967     --Size;
968     ++Offset;
969   }
970 }
971
972 void DFSanVisitor::visitStoreInst(StoreInst &SI) {
973   uint64_t Size =
974       DFSF.DFS.DL->getTypeStoreSize(SI.getValueOperand()->getType());
975   uint64_t Align;
976   if (ClPreserveAlignment) {
977     Align = SI.getAlignment();
978     if (Align == 0)
979       Align = DFSF.DFS.DL->getABITypeAlignment(SI.getValueOperand()->getType());
980   } else {
981     Align = 1;
982   }
983   DFSF.storeShadow(SI.getPointerOperand(), Size, Align,
984                    DFSF.getShadow(SI.getValueOperand()), &SI);
985 }
986
987 void DFSanVisitor::visitBinaryOperator(BinaryOperator &BO) {
988   visitOperandShadowInst(BO);
989 }
990
991 void DFSanVisitor::visitCastInst(CastInst &CI) { visitOperandShadowInst(CI); }
992
993 void DFSanVisitor::visitCmpInst(CmpInst &CI) { visitOperandShadowInst(CI); }
994
995 void DFSanVisitor::visitGetElementPtrInst(GetElementPtrInst &GEPI) {
996   visitOperandShadowInst(GEPI);
997 }
998
999 void DFSanVisitor::visitExtractElementInst(ExtractElementInst &I) {
1000   visitOperandShadowInst(I);
1001 }
1002
1003 void DFSanVisitor::visitInsertElementInst(InsertElementInst &I) {
1004   visitOperandShadowInst(I);
1005 }
1006
1007 void DFSanVisitor::visitShuffleVectorInst(ShuffleVectorInst &I) {
1008   visitOperandShadowInst(I);
1009 }
1010
1011 void DFSanVisitor::visitExtractValueInst(ExtractValueInst &I) {
1012   visitOperandShadowInst(I);
1013 }
1014
1015 void DFSanVisitor::visitInsertValueInst(InsertValueInst &I) {
1016   visitOperandShadowInst(I);
1017 }
1018
1019 void DFSanVisitor::visitAllocaInst(AllocaInst &I) {
1020   bool AllLoadsStores = true;
1021   for (Instruction::use_iterator i = I.use_begin(), e = I.use_end(); i != e;
1022        ++i) {
1023     if (isa<LoadInst>(*i))
1024       continue;
1025
1026     if (StoreInst *SI = dyn_cast<StoreInst>(*i)) {
1027       if (SI->getPointerOperand() == &I)
1028         continue;
1029     }
1030
1031     AllLoadsStores = false;
1032     break;
1033   }
1034   if (AllLoadsStores) {
1035     IRBuilder<> IRB(&I);
1036     DFSF.AllocaShadowMap[&I] = IRB.CreateAlloca(DFSF.DFS.ShadowTy);
1037   }
1038   DFSF.setShadow(&I, DFSF.DFS.ZeroShadow);
1039 }
1040
1041 void DFSanVisitor::visitSelectInst(SelectInst &I) {
1042   Value *CondShadow = DFSF.getShadow(I.getCondition());
1043   Value *TrueShadow = DFSF.getShadow(I.getTrueValue());
1044   Value *FalseShadow = DFSF.getShadow(I.getFalseValue());
1045
1046   if (isa<VectorType>(I.getCondition()->getType())) {
1047     DFSF.setShadow(
1048         &I, DFSF.DFS.combineShadows(
1049                 CondShadow,
1050                 DFSF.DFS.combineShadows(TrueShadow, FalseShadow, &I), &I));
1051   } else {
1052     Value *ShadowSel;
1053     if (TrueShadow == FalseShadow) {
1054       ShadowSel = TrueShadow;
1055     } else {
1056       ShadowSel =
1057           SelectInst::Create(I.getCondition(), TrueShadow, FalseShadow, "", &I);
1058     }
1059     DFSF.setShadow(&I, DFSF.DFS.combineShadows(CondShadow, ShadowSel, &I));
1060   }
1061 }
1062
1063 void DFSanVisitor::visitMemSetInst(MemSetInst &I) {
1064   IRBuilder<> IRB(&I);
1065   Value *ValShadow = DFSF.getShadow(I.getValue());
1066   IRB.CreateCall3(
1067       DFSF.DFS.DFSanSetLabelFn, ValShadow,
1068       IRB.CreateBitCast(I.getDest(), Type::getInt8PtrTy(*DFSF.DFS.Ctx)),
1069       IRB.CreateZExtOrTrunc(I.getLength(), DFSF.DFS.IntptrTy));
1070 }
1071
1072 void DFSanVisitor::visitMemTransferInst(MemTransferInst &I) {
1073   IRBuilder<> IRB(&I);
1074   Value *DestShadow = DFSF.DFS.getShadowAddress(I.getDest(), &I);
1075   Value *SrcShadow = DFSF.DFS.getShadowAddress(I.getSource(), &I);
1076   Value *LenShadow = IRB.CreateMul(
1077       I.getLength(),
1078       ConstantInt::get(I.getLength()->getType(), DFSF.DFS.ShadowWidth / 8));
1079   Value *AlignShadow;
1080   if (ClPreserveAlignment) {
1081     AlignShadow = IRB.CreateMul(I.getAlignmentCst(),
1082                                 ConstantInt::get(I.getAlignmentCst()->getType(),
1083                                                  DFSF.DFS.ShadowWidth / 8));
1084   } else {
1085     AlignShadow = ConstantInt::get(I.getAlignmentCst()->getType(),
1086                                    DFSF.DFS.ShadowWidth / 8);
1087   }
1088   Type *Int8Ptr = Type::getInt8PtrTy(*DFSF.DFS.Ctx);
1089   DestShadow = IRB.CreateBitCast(DestShadow, Int8Ptr);
1090   SrcShadow = IRB.CreateBitCast(SrcShadow, Int8Ptr);
1091   IRB.CreateCall5(I.getCalledValue(), DestShadow, SrcShadow, LenShadow,
1092                   AlignShadow, I.getVolatileCst());
1093 }
1094
1095 void DFSanVisitor::visitReturnInst(ReturnInst &RI) {
1096   if (!DFSF.IsNativeABI && RI.getReturnValue()) {
1097     switch (DFSF.IA) {
1098     case DataFlowSanitizer::IA_TLS: {
1099       Value *S = DFSF.getShadow(RI.getReturnValue());
1100       IRBuilder<> IRB(&RI);
1101       IRB.CreateStore(S, DFSF.getRetvalTLS());
1102       break;
1103     }
1104     case DataFlowSanitizer::IA_Args: {
1105       IRBuilder<> IRB(&RI);
1106       Type *RT = DFSF.F->getFunctionType()->getReturnType();
1107       Value *InsVal =
1108           IRB.CreateInsertValue(UndefValue::get(RT), RI.getReturnValue(), 0);
1109       Value *InsShadow =
1110           IRB.CreateInsertValue(InsVal, DFSF.getShadow(RI.getReturnValue()), 1);
1111       RI.setOperand(0, InsShadow);
1112       break;
1113     }
1114     }
1115   }
1116 }
1117
1118 void DFSanVisitor::visitCallSite(CallSite CS) {
1119   Function *F = CS.getCalledFunction();
1120   if ((F && F->isIntrinsic()) || isa<InlineAsm>(CS.getCalledValue())) {
1121     visitOperandShadowInst(*CS.getInstruction());
1122     return;
1123   }
1124
1125   IRBuilder<> IRB(CS.getInstruction());
1126
1127   DenseMap<Value *, Function *>::iterator i =
1128       DFSF.DFS.UnwrappedFnMap.find(CS.getCalledValue());
1129   if (i != DFSF.DFS.UnwrappedFnMap.end()) {
1130     Function *F = i->second;
1131     switch (DFSF.DFS.getWrapperKind(F)) {
1132     case DataFlowSanitizer::WK_Warning: {
1133       CS.setCalledFunction(F);
1134       IRB.CreateCall(DFSF.DFS.DFSanUnimplementedFn,
1135                      IRB.CreateGlobalStringPtr(F->getName()));
1136       DFSF.setShadow(CS.getInstruction(), DFSF.DFS.ZeroShadow);
1137       return;
1138     }
1139     case DataFlowSanitizer::WK_Discard: {
1140       CS.setCalledFunction(F);
1141       DFSF.setShadow(CS.getInstruction(), DFSF.DFS.ZeroShadow);
1142       return;
1143     }
1144     case DataFlowSanitizer::WK_Functional: {
1145       CS.setCalledFunction(F);
1146       visitOperandShadowInst(*CS.getInstruction());
1147       return;
1148     }
1149     case DataFlowSanitizer::WK_Custom: {
1150       // Don't try to handle invokes of custom functions, it's too complicated.
1151       // Instead, invoke the dfsw$ wrapper, which will in turn call the __dfsw_
1152       // wrapper.
1153       if (CallInst *CI = dyn_cast<CallInst>(CS.getInstruction())) {
1154         FunctionType *FT = F->getFunctionType();
1155         FunctionType *CustomFT = DFSF.DFS.getCustomFunctionType(FT);
1156         std::string CustomFName = "__dfsw_";
1157         CustomFName += F->getName();
1158         Constant *CustomF =
1159             DFSF.DFS.Mod->getOrInsertFunction(CustomFName, CustomFT);
1160         if (Function *CustomFn = dyn_cast<Function>(CustomF)) {
1161           CustomFn->copyAttributesFrom(F);
1162
1163           // Custom functions returning non-void will write to the return label.
1164           if (!FT->getReturnType()->isVoidTy()) {
1165             CustomFn->removeAttributes(AttributeSet::FunctionIndex,
1166                                        DFSF.DFS.ReadOnlyNoneAttrs);
1167           }
1168         }
1169
1170         std::vector<Value *> Args;
1171
1172         CallSite::arg_iterator i = CS.arg_begin();
1173         for (unsigned n = FT->getNumParams(); n != 0; ++i, --n)
1174           Args.push_back(*i);
1175
1176         i = CS.arg_begin();
1177         for (unsigned n = FT->getNumParams(); n != 0; ++i, --n)
1178           Args.push_back(DFSF.getShadow(*i));
1179
1180         if (!FT->getReturnType()->isVoidTy()) {
1181           if (!DFSF.LabelReturnAlloca) {
1182             DFSF.LabelReturnAlloca =
1183                 new AllocaInst(DFSF.DFS.ShadowTy, "labelreturn",
1184                                DFSF.F->getEntryBlock().begin());
1185           }
1186           Args.push_back(DFSF.LabelReturnAlloca);
1187         }
1188
1189         CallInst *CustomCI = IRB.CreateCall(CustomF, Args);
1190         CustomCI->setCallingConv(CI->getCallingConv());
1191         CustomCI->setAttributes(CI->getAttributes());
1192
1193         if (!FT->getReturnType()->isVoidTy()) {
1194           LoadInst *LabelLoad = IRB.CreateLoad(DFSF.LabelReturnAlloca);
1195           DFSF.setShadow(CustomCI, LabelLoad);
1196         }
1197
1198         CI->replaceAllUsesWith(CustomCI);
1199         CI->eraseFromParent();
1200         return;
1201       }
1202       break;
1203     }
1204     }
1205   }
1206
1207   FunctionType *FT = cast<FunctionType>(
1208       CS.getCalledValue()->getType()->getPointerElementType());
1209   if (DFSF.DFS.getInstrumentedABI() == DataFlowSanitizer::IA_TLS) {
1210     for (unsigned i = 0, n = FT->getNumParams(); i != n; ++i) {
1211       IRB.CreateStore(DFSF.getShadow(CS.getArgument(i)),
1212                       DFSF.getArgTLS(i, CS.getInstruction()));
1213     }
1214   }
1215
1216   Instruction *Next = 0;
1217   if (!CS.getType()->isVoidTy()) {
1218     if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
1219       if (II->getNormalDest()->getSinglePredecessor()) {
1220         Next = II->getNormalDest()->begin();
1221       } else {
1222         BasicBlock *NewBB =
1223             SplitEdge(II->getParent(), II->getNormalDest(), &DFSF.DFS);
1224         Next = NewBB->begin();
1225       }
1226     } else {
1227       Next = CS->getNextNode();
1228     }
1229
1230     if (DFSF.DFS.getInstrumentedABI() == DataFlowSanitizer::IA_TLS) {
1231       IRBuilder<> NextIRB(Next);
1232       LoadInst *LI = NextIRB.CreateLoad(DFSF.getRetvalTLS());
1233       DFSF.SkipInsts.insert(LI);
1234       DFSF.setShadow(CS.getInstruction(), LI);
1235       DFSF.NonZeroChecks.insert(LI);
1236     }
1237   }
1238
1239   // Do all instrumentation for IA_Args down here to defer tampering with the
1240   // CFG in a way that SplitEdge may be able to detect.
1241   if (DFSF.DFS.getInstrumentedABI() == DataFlowSanitizer::IA_Args) {
1242     FunctionType *NewFT = DFSF.DFS.getArgsFunctionType(FT);
1243     Value *Func =
1244         IRB.CreateBitCast(CS.getCalledValue(), PointerType::getUnqual(NewFT));
1245     std::vector<Value *> Args;
1246
1247     CallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
1248     for (unsigned n = FT->getNumParams(); n != 0; ++i, --n)
1249       Args.push_back(*i);
1250
1251     i = CS.arg_begin();
1252     for (unsigned n = FT->getNumParams(); n != 0; ++i, --n)
1253       Args.push_back(DFSF.getShadow(*i));
1254
1255     if (FT->isVarArg()) {
1256       unsigned VarArgSize = CS.arg_size() - FT->getNumParams();
1257       ArrayType *VarArgArrayTy = ArrayType::get(DFSF.DFS.ShadowTy, VarArgSize);
1258       AllocaInst *VarArgShadow =
1259           new AllocaInst(VarArgArrayTy, "", DFSF.F->getEntryBlock().begin());
1260       Args.push_back(IRB.CreateConstGEP2_32(VarArgShadow, 0, 0));
1261       for (unsigned n = 0; i != e; ++i, ++n) {
1262         IRB.CreateStore(DFSF.getShadow(*i),
1263                         IRB.CreateConstGEP2_32(VarArgShadow, 0, n));
1264         Args.push_back(*i);
1265       }
1266     }
1267
1268     CallSite NewCS;
1269     if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
1270       NewCS = IRB.CreateInvoke(Func, II->getNormalDest(), II->getUnwindDest(),
1271                                Args);
1272     } else {
1273       NewCS = IRB.CreateCall(Func, Args);
1274     }
1275     NewCS.setCallingConv(CS.getCallingConv());
1276     NewCS.setAttributes(CS.getAttributes().removeAttributes(
1277         *DFSF.DFS.Ctx, AttributeSet::ReturnIndex,
1278         AttributeFuncs::typeIncompatible(NewCS.getInstruction()->getType(),
1279                                          AttributeSet::ReturnIndex)));
1280
1281     if (Next) {
1282       ExtractValueInst *ExVal =
1283           ExtractValueInst::Create(NewCS.getInstruction(), 0, "", Next);
1284       DFSF.SkipInsts.insert(ExVal);
1285       ExtractValueInst *ExShadow =
1286           ExtractValueInst::Create(NewCS.getInstruction(), 1, "", Next);
1287       DFSF.SkipInsts.insert(ExShadow);
1288       DFSF.setShadow(ExVal, ExShadow);
1289       DFSF.NonZeroChecks.insert(ExShadow);
1290
1291       CS.getInstruction()->replaceAllUsesWith(ExVal);
1292     }
1293
1294     CS.getInstruction()->eraseFromParent();
1295   }
1296 }
1297
1298 void DFSanVisitor::visitPHINode(PHINode &PN) {
1299   PHINode *ShadowPN =
1300       PHINode::Create(DFSF.DFS.ShadowTy, PN.getNumIncomingValues(), "", &PN);
1301
1302   // Give the shadow phi node valid predecessors to fool SplitEdge into working.
1303   Value *UndefShadow = UndefValue::get(DFSF.DFS.ShadowTy);
1304   for (PHINode::block_iterator i = PN.block_begin(), e = PN.block_end(); i != e;
1305        ++i) {
1306     ShadowPN->addIncoming(UndefShadow, *i);
1307   }
1308
1309   DFSF.PHIFixups.push_back(std::make_pair(&PN, ShadowPN));
1310   DFSF.setShadow(&PN, ShadowPN);
1311 }