232893dac36a1b7c883737918a6250fc3889819f
[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, and build wrappers where the
474   // instrumentedness is inconsistent.
475   for (Module::alias_iterator i = M.alias_begin(), e = M.alias_end(); i != e;) {
476     GlobalAlias *GA = &*i;
477     ++i;
478     // Don't stop on weak.  We assume people aren't playing games with the
479     // instrumentedness of overridden weak aliases.
480     if (Function *F = dyn_cast<Function>(
481             GA->resolveAliasedGlobal(/*stopOnWeak=*/false))) {
482       bool GAInst = isInstrumented(GA), FInst = isInstrumented(F);
483       if (GAInst && FInst) {
484         addGlobalNamePrefix(GA);
485       } else if (GAInst != FInst) {
486         // Non-instrumented alias of an instrumented function, or vice versa.
487         // Replace the alias with a native-ABI wrapper of the aliasee.  The pass
488         // below will take care of instrumenting it.
489         Function *NewF =
490             buildWrapperFunction(F, "", GA->getLinkage(), F->getFunctionType());
491         GA->replaceAllUsesWith(NewF);
492         NewF->takeName(GA);
493         GA->eraseFromParent();
494         FnsToInstrument.push_back(NewF);
495       }
496     }
497   }
498
499   AttrBuilder B;
500   B.addAttribute(Attribute::ReadOnly).addAttribute(Attribute::ReadNone);
501   ReadOnlyNoneAttrs = AttributeSet::get(*Ctx, AttributeSet::FunctionIndex, B);
502
503   // First, change the ABI of every function in the module.  ABI-listed
504   // functions keep their original ABI and get a wrapper function.
505   for (std::vector<Function *>::iterator i = FnsToInstrument.begin(),
506                                          e = FnsToInstrument.end();
507        i != e; ++i) {
508     Function &F = **i;
509     FunctionType *FT = F.getFunctionType();
510
511     bool IsZeroArgsVoidRet = (FT->getNumParams() == 0 && !FT->isVarArg() &&
512                               FT->getReturnType()->isVoidTy());
513
514     if (isInstrumented(&F)) {
515       // Instrumented functions get a 'dfs$' prefix.  This allows us to more
516       // easily identify cases of mismatching ABIs.
517       if (getInstrumentedABI() == IA_Args && !IsZeroArgsVoidRet) {
518         FunctionType *NewFT = getArgsFunctionType(FT);
519         Function *NewF = Function::Create(NewFT, F.getLinkage(), "", &M);
520         NewF->copyAttributesFrom(&F);
521         NewF->removeAttributes(
522             AttributeSet::ReturnIndex,
523             AttributeFuncs::typeIncompatible(NewFT->getReturnType(),
524                                              AttributeSet::ReturnIndex));
525         for (Function::arg_iterator FArg = F.arg_begin(),
526                                     NewFArg = NewF->arg_begin(),
527                                     FArgEnd = F.arg_end();
528              FArg != FArgEnd; ++FArg, ++NewFArg) {
529           FArg->replaceAllUsesWith(NewFArg);
530         }
531         NewF->getBasicBlockList().splice(NewF->begin(), F.getBasicBlockList());
532
533         for (Function::use_iterator ui = F.use_begin(), ue = F.use_end();
534              ui != ue;) {
535           BlockAddress *BA = dyn_cast<BlockAddress>(ui.getUse().getUser());
536           ++ui;
537           if (BA) {
538             BA->replaceAllUsesWith(
539                 BlockAddress::get(NewF, BA->getBasicBlock()));
540             delete BA;
541           }
542         }
543         F.replaceAllUsesWith(
544             ConstantExpr::getBitCast(NewF, PointerType::getUnqual(FT)));
545         NewF->takeName(&F);
546         F.eraseFromParent();
547         *i = NewF;
548         addGlobalNamePrefix(NewF);
549       } else {
550         addGlobalNamePrefix(&F);
551       }
552                // Hopefully, nobody will try to indirectly call a vararg
553                // function... yet.
554     } else if (FT->isVarArg()) {
555       UnwrappedFnMap[&F] = &F;
556       *i = 0;
557     } else if (!IsZeroArgsVoidRet || getWrapperKind(&F) == WK_Custom) {
558       // Build a wrapper function for F.  The wrapper simply calls F, and is
559       // added to FnsToInstrument so that any instrumentation according to its
560       // WrapperKind is done in the second pass below.
561       FunctionType *NewFT = getInstrumentedABI() == IA_Args
562                                 ? getArgsFunctionType(FT)
563                                 : FT;
564       Function *NewF = buildWrapperFunction(
565           &F, std::string("dfsw$") + std::string(F.getName()),
566           GlobalValue::LinkOnceODRLinkage, NewFT);
567       if (getInstrumentedABI() == IA_TLS)
568         NewF->removeAttributes(AttributeSet::FunctionIndex, ReadOnlyNoneAttrs);
569
570       Value *WrappedFnCst =
571           ConstantExpr::getBitCast(NewF, PointerType::getUnqual(FT));
572       F.replaceAllUsesWith(WrappedFnCst);
573       UnwrappedFnMap[WrappedFnCst] = &F;
574       *i = NewF;
575
576       if (!F.isDeclaration()) {
577         // This function is probably defining an interposition of an
578         // uninstrumented function and hence needs to keep the original ABI.
579         // But any functions it may call need to use the instrumented ABI, so
580         // we instrument it in a mode which preserves the original ABI.
581         FnsWithNativeABI.insert(&F);
582
583         // This code needs to rebuild the iterators, as they may be invalidated
584         // by the push_back, taking care that the new range does not include
585         // any functions added by this code.
586         size_t N = i - FnsToInstrument.begin(),
587                Count = e - FnsToInstrument.begin();
588         FnsToInstrument.push_back(&F);
589         i = FnsToInstrument.begin() + N;
590         e = FnsToInstrument.begin() + Count;
591       }
592     }
593   }
594
595   for (std::vector<Function *>::iterator i = FnsToInstrument.begin(),
596                                          e = FnsToInstrument.end();
597        i != e; ++i) {
598     if (!*i || (*i)->isDeclaration())
599       continue;
600
601     removeUnreachableBlocks(**i);
602
603     DFSanFunction DFSF(*this, *i, FnsWithNativeABI.count(*i));
604
605     // DFSanVisitor may create new basic blocks, which confuses df_iterator.
606     // Build a copy of the list before iterating over it.
607     llvm::SmallVector<BasicBlock *, 4> BBList;
608     std::copy(df_begin(&(*i)->getEntryBlock()), df_end(&(*i)->getEntryBlock()),
609               std::back_inserter(BBList));
610
611     for (llvm::SmallVector<BasicBlock *, 4>::iterator i = BBList.begin(),
612                                                       e = BBList.end();
613          i != e; ++i) {
614       Instruction *Inst = &(*i)->front();
615       while (1) {
616         // DFSanVisitor may split the current basic block, changing the current
617         // instruction's next pointer and moving the next instruction to the
618         // tail block from which we should continue.
619         Instruction *Next = Inst->getNextNode();
620         // DFSanVisitor may delete Inst, so keep track of whether it was a
621         // terminator.
622         bool IsTerminator = isa<TerminatorInst>(Inst);
623         if (!DFSF.SkipInsts.count(Inst))
624           DFSanVisitor(DFSF).visit(Inst);
625         if (IsTerminator)
626           break;
627         Inst = Next;
628       }
629     }
630
631     // We will not necessarily be able to compute the shadow for every phi node
632     // until we have visited every block.  Therefore, the code that handles phi
633     // nodes adds them to the PHIFixups list so that they can be properly
634     // handled here.
635     for (std::vector<std::pair<PHINode *, PHINode *> >::iterator
636              i = DFSF.PHIFixups.begin(),
637              e = DFSF.PHIFixups.end();
638          i != e; ++i) {
639       for (unsigned val = 0, n = i->first->getNumIncomingValues(); val != n;
640            ++val) {
641         i->second->setIncomingValue(
642             val, DFSF.getShadow(i->first->getIncomingValue(val)));
643       }
644     }
645
646     // -dfsan-debug-nonzero-labels will split the CFG in all kinds of crazy
647     // places (i.e. instructions in basic blocks we haven't even begun visiting
648     // yet).  To make our life easier, do this work in a pass after the main
649     // instrumentation.
650     if (ClDebugNonzeroLabels) {
651       for (DenseSet<Value *>::iterator i = DFSF.NonZeroChecks.begin(),
652                                        e = DFSF.NonZeroChecks.end();
653            i != e; ++i) {
654         Instruction *Pos;
655         if (Instruction *I = dyn_cast<Instruction>(*i))
656           Pos = I->getNextNode();
657         else
658           Pos = DFSF.F->getEntryBlock().begin();
659         while (isa<PHINode>(Pos) || isa<AllocaInst>(Pos))
660           Pos = Pos->getNextNode();
661         IRBuilder<> IRB(Pos);
662         Instruction *NeInst = cast<Instruction>(
663             IRB.CreateICmpNE(*i, DFSF.DFS.ZeroShadow));
664         BranchInst *BI = cast<BranchInst>(SplitBlockAndInsertIfThen(
665             NeInst, /*Unreachable=*/ false, ColdCallWeights));
666         IRBuilder<> ThenIRB(BI);
667         ThenIRB.CreateCall(DFSF.DFS.DFSanNonzeroLabelFn);
668       }
669     }
670   }
671
672   return false;
673 }
674
675 Value *DFSanFunction::getArgTLSPtr() {
676   if (ArgTLSPtr)
677     return ArgTLSPtr;
678   if (DFS.ArgTLS)
679     return ArgTLSPtr = DFS.ArgTLS;
680
681   IRBuilder<> IRB(F->getEntryBlock().begin());
682   return ArgTLSPtr = IRB.CreateCall(DFS.GetArgTLS);
683 }
684
685 Value *DFSanFunction::getRetvalTLS() {
686   if (RetvalTLSPtr)
687     return RetvalTLSPtr;
688   if (DFS.RetvalTLS)
689     return RetvalTLSPtr = DFS.RetvalTLS;
690
691   IRBuilder<> IRB(F->getEntryBlock().begin());
692   return RetvalTLSPtr = IRB.CreateCall(DFS.GetRetvalTLS);
693 }
694
695 Value *DFSanFunction::getArgTLS(unsigned Idx, Instruction *Pos) {
696   IRBuilder<> IRB(Pos);
697   return IRB.CreateConstGEP2_64(getArgTLSPtr(), 0, Idx);
698 }
699
700 Value *DFSanFunction::getShadow(Value *V) {
701   if (!isa<Argument>(V) && !isa<Instruction>(V))
702     return DFS.ZeroShadow;
703   Value *&Shadow = ValShadowMap[V];
704   if (!Shadow) {
705     if (Argument *A = dyn_cast<Argument>(V)) {
706       if (IsNativeABI)
707         return DFS.ZeroShadow;
708       switch (IA) {
709       case DataFlowSanitizer::IA_TLS: {
710         Value *ArgTLSPtr = getArgTLSPtr();
711         Instruction *ArgTLSPos =
712             DFS.ArgTLS ? &*F->getEntryBlock().begin()
713                        : cast<Instruction>(ArgTLSPtr)->getNextNode();
714         IRBuilder<> IRB(ArgTLSPos);
715         Shadow = IRB.CreateLoad(getArgTLS(A->getArgNo(), ArgTLSPos));
716         break;
717       }
718       case DataFlowSanitizer::IA_Args: {
719         unsigned ArgIdx = A->getArgNo() + F->getArgumentList().size() / 2;
720         Function::arg_iterator i = F->arg_begin();
721         while (ArgIdx--)
722           ++i;
723         Shadow = i;
724         assert(Shadow->getType() == DFS.ShadowTy);
725         break;
726       }
727       }
728       NonZeroChecks.insert(Shadow);
729     } else {
730       Shadow = DFS.ZeroShadow;
731     }
732   }
733   return Shadow;
734 }
735
736 void DFSanFunction::setShadow(Instruction *I, Value *Shadow) {
737   assert(!ValShadowMap.count(I));
738   assert(Shadow->getType() == DFS.ShadowTy);
739   ValShadowMap[I] = Shadow;
740 }
741
742 Value *DataFlowSanitizer::getShadowAddress(Value *Addr, Instruction *Pos) {
743   assert(Addr != RetvalTLS && "Reinstrumenting?");
744   IRBuilder<> IRB(Pos);
745   return IRB.CreateIntToPtr(
746       IRB.CreateMul(
747           IRB.CreateAnd(IRB.CreatePtrToInt(Addr, IntptrTy), ShadowPtrMask),
748           ShadowPtrMul),
749       ShadowPtrTy);
750 }
751
752 // Generates IR to compute the union of the two given shadows, inserting it
753 // before Pos.  Returns the computed union Value.
754 Value *DataFlowSanitizer::combineShadows(Value *V1, Value *V2,
755                                          Instruction *Pos) {
756   if (V1 == ZeroShadow)
757     return V2;
758   if (V2 == ZeroShadow)
759     return V1;
760   if (V1 == V2)
761     return V1;
762   IRBuilder<> IRB(Pos);
763   BasicBlock *Head = Pos->getParent();
764   Value *Ne = IRB.CreateICmpNE(V1, V2);
765   Instruction *NeInst = dyn_cast<Instruction>(Ne);
766   if (NeInst) {
767     BranchInst *BI = cast<BranchInst>(SplitBlockAndInsertIfThen(
768         NeInst, /*Unreachable=*/ false, ColdCallWeights));
769     IRBuilder<> ThenIRB(BI);
770     CallInst *Call = ThenIRB.CreateCall2(DFSanUnionFn, V1, V2);
771     Call->addAttribute(AttributeSet::ReturnIndex, Attribute::ZExt);
772     Call->addAttribute(1, Attribute::ZExt);
773     Call->addAttribute(2, Attribute::ZExt);
774
775     BasicBlock *Tail = BI->getSuccessor(0);
776     PHINode *Phi = PHINode::Create(ShadowTy, 2, "", Tail->begin());
777     Phi->addIncoming(Call, Call->getParent());
778     Phi->addIncoming(ZeroShadow, Head);
779     Pos = Phi;
780     return Phi;
781   } else {
782     assert(0 && "todo");
783     return 0;
784   }
785 }
786
787 // A convenience function which folds the shadows of each of the operands
788 // of the provided instruction Inst, inserting the IR before Inst.  Returns
789 // the computed union Value.
790 Value *DFSanFunction::combineOperandShadows(Instruction *Inst) {
791   if (Inst->getNumOperands() == 0)
792     return DFS.ZeroShadow;
793
794   Value *Shadow = getShadow(Inst->getOperand(0));
795   for (unsigned i = 1, n = Inst->getNumOperands(); i != n; ++i) {
796     Shadow = DFS.combineShadows(Shadow, getShadow(Inst->getOperand(i)), Inst);
797   }
798   return Shadow;
799 }
800
801 void DFSanVisitor::visitOperandShadowInst(Instruction &I) {
802   Value *CombinedShadow = DFSF.combineOperandShadows(&I);
803   DFSF.setShadow(&I, CombinedShadow);
804 }
805
806 // Generates IR to load shadow corresponding to bytes [Addr, Addr+Size), where
807 // Addr has alignment Align, and take the union of each of those shadows.
808 Value *DFSanFunction::loadShadow(Value *Addr, uint64_t Size, uint64_t Align,
809                                  Instruction *Pos) {
810   if (AllocaInst *AI = dyn_cast<AllocaInst>(Addr)) {
811     llvm::DenseMap<AllocaInst *, AllocaInst *>::iterator i =
812         AllocaShadowMap.find(AI);
813     if (i != AllocaShadowMap.end()) {
814       IRBuilder<> IRB(Pos);
815       return IRB.CreateLoad(i->second);
816     }
817   }
818
819   uint64_t ShadowAlign = Align * DFS.ShadowWidth / 8;
820   SmallVector<Value *, 2> Objs;
821   GetUnderlyingObjects(Addr, Objs, DFS.DL);
822   bool AllConstants = true;
823   for (SmallVector<Value *, 2>::iterator i = Objs.begin(), e = Objs.end();
824        i != e; ++i) {
825     if (isa<Function>(*i) || isa<BlockAddress>(*i))
826       continue;
827     if (isa<GlobalVariable>(*i) && cast<GlobalVariable>(*i)->isConstant())
828       continue;
829
830     AllConstants = false;
831     break;
832   }
833   if (AllConstants)
834     return DFS.ZeroShadow;
835
836   Value *ShadowAddr = DFS.getShadowAddress(Addr, Pos);
837   switch (Size) {
838   case 0:
839     return DFS.ZeroShadow;
840   case 1: {
841     LoadInst *LI = new LoadInst(ShadowAddr, "", Pos);
842     LI->setAlignment(ShadowAlign);
843     return LI;
844   }
845   case 2: {
846     IRBuilder<> IRB(Pos);
847     Value *ShadowAddr1 =
848         IRB.CreateGEP(ShadowAddr, ConstantInt::get(DFS.IntptrTy, 1));
849     return DFS.combineShadows(IRB.CreateAlignedLoad(ShadowAddr, ShadowAlign),
850                               IRB.CreateAlignedLoad(ShadowAddr1, ShadowAlign),
851                               Pos);
852   }
853   }
854   if (Size % (64 / DFS.ShadowWidth) == 0) {
855     // Fast path for the common case where each byte has identical shadow: load
856     // shadow 64 bits at a time, fall out to a __dfsan_union_load call if any
857     // shadow is non-equal.
858     BasicBlock *FallbackBB = BasicBlock::Create(*DFS.Ctx, "", F);
859     IRBuilder<> FallbackIRB(FallbackBB);
860     CallInst *FallbackCall = FallbackIRB.CreateCall2(
861         DFS.DFSanUnionLoadFn, ShadowAddr, ConstantInt::get(DFS.IntptrTy, Size));
862     FallbackCall->addAttribute(AttributeSet::ReturnIndex, Attribute::ZExt);
863
864     // Compare each of the shadows stored in the loaded 64 bits to each other,
865     // by computing (WideShadow rotl ShadowWidth) == WideShadow.
866     IRBuilder<> IRB(Pos);
867     Value *WideAddr =
868         IRB.CreateBitCast(ShadowAddr, Type::getInt64PtrTy(*DFS.Ctx));
869     Value *WideShadow = IRB.CreateAlignedLoad(WideAddr, ShadowAlign);
870     Value *TruncShadow = IRB.CreateTrunc(WideShadow, DFS.ShadowTy);
871     Value *ShlShadow = IRB.CreateShl(WideShadow, DFS.ShadowWidth);
872     Value *ShrShadow = IRB.CreateLShr(WideShadow, 64 - DFS.ShadowWidth);
873     Value *RotShadow = IRB.CreateOr(ShlShadow, ShrShadow);
874     Value *ShadowsEq = IRB.CreateICmpEQ(WideShadow, RotShadow);
875
876     BasicBlock *Head = Pos->getParent();
877     BasicBlock *Tail = Head->splitBasicBlock(Pos);
878     // In the following code LastBr will refer to the previous basic block's
879     // conditional branch instruction, whose true successor is fixed up to point
880     // to the next block during the loop below or to the tail after the final
881     // iteration.
882     BranchInst *LastBr = BranchInst::Create(FallbackBB, FallbackBB, ShadowsEq);
883     ReplaceInstWithInst(Head->getTerminator(), LastBr);
884
885     for (uint64_t Ofs = 64 / DFS.ShadowWidth; Ofs != Size;
886          Ofs += 64 / DFS.ShadowWidth) {
887       BasicBlock *NextBB = BasicBlock::Create(*DFS.Ctx, "", F);
888       IRBuilder<> NextIRB(NextBB);
889       WideAddr = NextIRB.CreateGEP(WideAddr, ConstantInt::get(DFS.IntptrTy, 1));
890       Value *NextWideShadow = NextIRB.CreateAlignedLoad(WideAddr, ShadowAlign);
891       ShadowsEq = NextIRB.CreateICmpEQ(WideShadow, NextWideShadow);
892       LastBr->setSuccessor(0, NextBB);
893       LastBr = NextIRB.CreateCondBr(ShadowsEq, FallbackBB, FallbackBB);
894     }
895
896     LastBr->setSuccessor(0, Tail);
897     FallbackIRB.CreateBr(Tail);
898     PHINode *Shadow = PHINode::Create(DFS.ShadowTy, 2, "", &Tail->front());
899     Shadow->addIncoming(FallbackCall, FallbackBB);
900     Shadow->addIncoming(TruncShadow, LastBr->getParent());
901     return Shadow;
902   }
903
904   IRBuilder<> IRB(Pos);
905   CallInst *FallbackCall = IRB.CreateCall2(
906       DFS.DFSanUnionLoadFn, ShadowAddr, ConstantInt::get(DFS.IntptrTy, Size));
907   FallbackCall->addAttribute(AttributeSet::ReturnIndex, Attribute::ZExt);
908   return FallbackCall;
909 }
910
911 void DFSanVisitor::visitLoadInst(LoadInst &LI) {
912   uint64_t Size = DFSF.DFS.DL->getTypeStoreSize(LI.getType());
913   uint64_t Align;
914   if (ClPreserveAlignment) {
915     Align = LI.getAlignment();
916     if (Align == 0)
917       Align = DFSF.DFS.DL->getABITypeAlignment(LI.getType());
918   } else {
919     Align = 1;
920   }
921   IRBuilder<> IRB(&LI);
922   Value *LoadedShadow =
923       DFSF.loadShadow(LI.getPointerOperand(), Size, Align, &LI);
924   Value *PtrShadow = DFSF.getShadow(LI.getPointerOperand());
925   Value *CombinedShadow = DFSF.DFS.combineShadows(LoadedShadow, PtrShadow, &LI);
926   if (CombinedShadow != DFSF.DFS.ZeroShadow)
927     DFSF.NonZeroChecks.insert(CombinedShadow);
928
929   DFSF.setShadow(&LI, CombinedShadow);
930 }
931
932 void DFSanFunction::storeShadow(Value *Addr, uint64_t Size, uint64_t Align,
933                                 Value *Shadow, Instruction *Pos) {
934   if (AllocaInst *AI = dyn_cast<AllocaInst>(Addr)) {
935     llvm::DenseMap<AllocaInst *, AllocaInst *>::iterator i =
936         AllocaShadowMap.find(AI);
937     if (i != AllocaShadowMap.end()) {
938       IRBuilder<> IRB(Pos);
939       IRB.CreateStore(Shadow, i->second);
940       return;
941     }
942   }
943
944   uint64_t ShadowAlign = Align * DFS.ShadowWidth / 8;
945   IRBuilder<> IRB(Pos);
946   Value *ShadowAddr = DFS.getShadowAddress(Addr, Pos);
947   if (Shadow == DFS.ZeroShadow) {
948     IntegerType *ShadowTy = IntegerType::get(*DFS.Ctx, Size * DFS.ShadowWidth);
949     Value *ExtZeroShadow = ConstantInt::get(ShadowTy, 0);
950     Value *ExtShadowAddr =
951         IRB.CreateBitCast(ShadowAddr, PointerType::getUnqual(ShadowTy));
952     IRB.CreateAlignedStore(ExtZeroShadow, ExtShadowAddr, ShadowAlign);
953     return;
954   }
955
956   const unsigned ShadowVecSize = 128 / DFS.ShadowWidth;
957   uint64_t Offset = 0;
958   if (Size >= ShadowVecSize) {
959     VectorType *ShadowVecTy = VectorType::get(DFS.ShadowTy, ShadowVecSize);
960     Value *ShadowVec = UndefValue::get(ShadowVecTy);
961     for (unsigned i = 0; i != ShadowVecSize; ++i) {
962       ShadowVec = IRB.CreateInsertElement(
963           ShadowVec, Shadow, ConstantInt::get(Type::getInt32Ty(*DFS.Ctx), i));
964     }
965     Value *ShadowVecAddr =
966         IRB.CreateBitCast(ShadowAddr, PointerType::getUnqual(ShadowVecTy));
967     do {
968       Value *CurShadowVecAddr = IRB.CreateConstGEP1_32(ShadowVecAddr, Offset);
969       IRB.CreateAlignedStore(ShadowVec, CurShadowVecAddr, ShadowAlign);
970       Size -= ShadowVecSize;
971       ++Offset;
972     } while (Size >= ShadowVecSize);
973     Offset *= ShadowVecSize;
974   }
975   while (Size > 0) {
976     Value *CurShadowAddr = IRB.CreateConstGEP1_32(ShadowAddr, Offset);
977     IRB.CreateAlignedStore(Shadow, CurShadowAddr, ShadowAlign);
978     --Size;
979     ++Offset;
980   }
981 }
982
983 void DFSanVisitor::visitStoreInst(StoreInst &SI) {
984   uint64_t Size =
985       DFSF.DFS.DL->getTypeStoreSize(SI.getValueOperand()->getType());
986   uint64_t Align;
987   if (ClPreserveAlignment) {
988     Align = SI.getAlignment();
989     if (Align == 0)
990       Align = DFSF.DFS.DL->getABITypeAlignment(SI.getValueOperand()->getType());
991   } else {
992     Align = 1;
993   }
994   DFSF.storeShadow(SI.getPointerOperand(), Size, Align,
995                    DFSF.getShadow(SI.getValueOperand()), &SI);
996 }
997
998 void DFSanVisitor::visitBinaryOperator(BinaryOperator &BO) {
999   visitOperandShadowInst(BO);
1000 }
1001
1002 void DFSanVisitor::visitCastInst(CastInst &CI) { visitOperandShadowInst(CI); }
1003
1004 void DFSanVisitor::visitCmpInst(CmpInst &CI) { visitOperandShadowInst(CI); }
1005
1006 void DFSanVisitor::visitGetElementPtrInst(GetElementPtrInst &GEPI) {
1007   visitOperandShadowInst(GEPI);
1008 }
1009
1010 void DFSanVisitor::visitExtractElementInst(ExtractElementInst &I) {
1011   visitOperandShadowInst(I);
1012 }
1013
1014 void DFSanVisitor::visitInsertElementInst(InsertElementInst &I) {
1015   visitOperandShadowInst(I);
1016 }
1017
1018 void DFSanVisitor::visitShuffleVectorInst(ShuffleVectorInst &I) {
1019   visitOperandShadowInst(I);
1020 }
1021
1022 void DFSanVisitor::visitExtractValueInst(ExtractValueInst &I) {
1023   visitOperandShadowInst(I);
1024 }
1025
1026 void DFSanVisitor::visitInsertValueInst(InsertValueInst &I) {
1027   visitOperandShadowInst(I);
1028 }
1029
1030 void DFSanVisitor::visitAllocaInst(AllocaInst &I) {
1031   bool AllLoadsStores = true;
1032   for (Instruction::use_iterator i = I.use_begin(), e = I.use_end(); i != e;
1033        ++i) {
1034     if (isa<LoadInst>(*i))
1035       continue;
1036
1037     if (StoreInst *SI = dyn_cast<StoreInst>(*i)) {
1038       if (SI->getPointerOperand() == &I)
1039         continue;
1040     }
1041
1042     AllLoadsStores = false;
1043     break;
1044   }
1045   if (AllLoadsStores) {
1046     IRBuilder<> IRB(&I);
1047     DFSF.AllocaShadowMap[&I] = IRB.CreateAlloca(DFSF.DFS.ShadowTy);
1048   }
1049   DFSF.setShadow(&I, DFSF.DFS.ZeroShadow);
1050 }
1051
1052 void DFSanVisitor::visitSelectInst(SelectInst &I) {
1053   Value *CondShadow = DFSF.getShadow(I.getCondition());
1054   Value *TrueShadow = DFSF.getShadow(I.getTrueValue());
1055   Value *FalseShadow = DFSF.getShadow(I.getFalseValue());
1056
1057   if (isa<VectorType>(I.getCondition()->getType())) {
1058     DFSF.setShadow(
1059         &I, DFSF.DFS.combineShadows(
1060                 CondShadow,
1061                 DFSF.DFS.combineShadows(TrueShadow, FalseShadow, &I), &I));
1062   } else {
1063     Value *ShadowSel;
1064     if (TrueShadow == FalseShadow) {
1065       ShadowSel = TrueShadow;
1066     } else {
1067       ShadowSel =
1068           SelectInst::Create(I.getCondition(), TrueShadow, FalseShadow, "", &I);
1069     }
1070     DFSF.setShadow(&I, DFSF.DFS.combineShadows(CondShadow, ShadowSel, &I));
1071   }
1072 }
1073
1074 void DFSanVisitor::visitMemSetInst(MemSetInst &I) {
1075   IRBuilder<> IRB(&I);
1076   Value *ValShadow = DFSF.getShadow(I.getValue());
1077   IRB.CreateCall3(
1078       DFSF.DFS.DFSanSetLabelFn, ValShadow,
1079       IRB.CreateBitCast(I.getDest(), Type::getInt8PtrTy(*DFSF.DFS.Ctx)),
1080       IRB.CreateZExtOrTrunc(I.getLength(), DFSF.DFS.IntptrTy));
1081 }
1082
1083 void DFSanVisitor::visitMemTransferInst(MemTransferInst &I) {
1084   IRBuilder<> IRB(&I);
1085   Value *DestShadow = DFSF.DFS.getShadowAddress(I.getDest(), &I);
1086   Value *SrcShadow = DFSF.DFS.getShadowAddress(I.getSource(), &I);
1087   Value *LenShadow = IRB.CreateMul(
1088       I.getLength(),
1089       ConstantInt::get(I.getLength()->getType(), DFSF.DFS.ShadowWidth / 8));
1090   Value *AlignShadow;
1091   if (ClPreserveAlignment) {
1092     AlignShadow = IRB.CreateMul(I.getAlignmentCst(),
1093                                 ConstantInt::get(I.getAlignmentCst()->getType(),
1094                                                  DFSF.DFS.ShadowWidth / 8));
1095   } else {
1096     AlignShadow = ConstantInt::get(I.getAlignmentCst()->getType(),
1097                                    DFSF.DFS.ShadowWidth / 8);
1098   }
1099   Type *Int8Ptr = Type::getInt8PtrTy(*DFSF.DFS.Ctx);
1100   DestShadow = IRB.CreateBitCast(DestShadow, Int8Ptr);
1101   SrcShadow = IRB.CreateBitCast(SrcShadow, Int8Ptr);
1102   IRB.CreateCall5(I.getCalledValue(), DestShadow, SrcShadow, LenShadow,
1103                   AlignShadow, I.getVolatileCst());
1104 }
1105
1106 void DFSanVisitor::visitReturnInst(ReturnInst &RI) {
1107   if (!DFSF.IsNativeABI && RI.getReturnValue()) {
1108     switch (DFSF.IA) {
1109     case DataFlowSanitizer::IA_TLS: {
1110       Value *S = DFSF.getShadow(RI.getReturnValue());
1111       IRBuilder<> IRB(&RI);
1112       IRB.CreateStore(S, DFSF.getRetvalTLS());
1113       break;
1114     }
1115     case DataFlowSanitizer::IA_Args: {
1116       IRBuilder<> IRB(&RI);
1117       Type *RT = DFSF.F->getFunctionType()->getReturnType();
1118       Value *InsVal =
1119           IRB.CreateInsertValue(UndefValue::get(RT), RI.getReturnValue(), 0);
1120       Value *InsShadow =
1121           IRB.CreateInsertValue(InsVal, DFSF.getShadow(RI.getReturnValue()), 1);
1122       RI.setOperand(0, InsShadow);
1123       break;
1124     }
1125     }
1126   }
1127 }
1128
1129 void DFSanVisitor::visitCallSite(CallSite CS) {
1130   Function *F = CS.getCalledFunction();
1131   if ((F && F->isIntrinsic()) || isa<InlineAsm>(CS.getCalledValue())) {
1132     visitOperandShadowInst(*CS.getInstruction());
1133     return;
1134   }
1135
1136   IRBuilder<> IRB(CS.getInstruction());
1137
1138   DenseMap<Value *, Function *>::iterator i =
1139       DFSF.DFS.UnwrappedFnMap.find(CS.getCalledValue());
1140   if (i != DFSF.DFS.UnwrappedFnMap.end()) {
1141     Function *F = i->second;
1142     switch (DFSF.DFS.getWrapperKind(F)) {
1143     case DataFlowSanitizer::WK_Warning: {
1144       CS.setCalledFunction(F);
1145       IRB.CreateCall(DFSF.DFS.DFSanUnimplementedFn,
1146                      IRB.CreateGlobalStringPtr(F->getName()));
1147       DFSF.setShadow(CS.getInstruction(), DFSF.DFS.ZeroShadow);
1148       return;
1149     }
1150     case DataFlowSanitizer::WK_Discard: {
1151       CS.setCalledFunction(F);
1152       DFSF.setShadow(CS.getInstruction(), DFSF.DFS.ZeroShadow);
1153       return;
1154     }
1155     case DataFlowSanitizer::WK_Functional: {
1156       CS.setCalledFunction(F);
1157       visitOperandShadowInst(*CS.getInstruction());
1158       return;
1159     }
1160     case DataFlowSanitizer::WK_Custom: {
1161       // Don't try to handle invokes of custom functions, it's too complicated.
1162       // Instead, invoke the dfsw$ wrapper, which will in turn call the __dfsw_
1163       // wrapper.
1164       if (CallInst *CI = dyn_cast<CallInst>(CS.getInstruction())) {
1165         FunctionType *FT = F->getFunctionType();
1166         FunctionType *CustomFT = DFSF.DFS.getCustomFunctionType(FT);
1167         std::string CustomFName = "__dfsw_";
1168         CustomFName += F->getName();
1169         Constant *CustomF =
1170             DFSF.DFS.Mod->getOrInsertFunction(CustomFName, CustomFT);
1171         if (Function *CustomFn = dyn_cast<Function>(CustomF)) {
1172           CustomFn->copyAttributesFrom(F);
1173
1174           // Custom functions returning non-void will write to the return label.
1175           if (!FT->getReturnType()->isVoidTy()) {
1176             CustomFn->removeAttributes(AttributeSet::FunctionIndex,
1177                                        DFSF.DFS.ReadOnlyNoneAttrs);
1178           }
1179         }
1180
1181         std::vector<Value *> Args;
1182
1183         CallSite::arg_iterator i = CS.arg_begin();
1184         for (unsigned n = FT->getNumParams(); n != 0; ++i, --n)
1185           Args.push_back(*i);
1186
1187         i = CS.arg_begin();
1188         for (unsigned n = FT->getNumParams(); n != 0; ++i, --n)
1189           Args.push_back(DFSF.getShadow(*i));
1190
1191         if (!FT->getReturnType()->isVoidTy()) {
1192           if (!DFSF.LabelReturnAlloca) {
1193             DFSF.LabelReturnAlloca =
1194                 new AllocaInst(DFSF.DFS.ShadowTy, "labelreturn",
1195                                DFSF.F->getEntryBlock().begin());
1196           }
1197           Args.push_back(DFSF.LabelReturnAlloca);
1198         }
1199
1200         CallInst *CustomCI = IRB.CreateCall(CustomF, Args);
1201         CustomCI->setCallingConv(CI->getCallingConv());
1202         CustomCI->setAttributes(CI->getAttributes());
1203
1204         if (!FT->getReturnType()->isVoidTy()) {
1205           LoadInst *LabelLoad = IRB.CreateLoad(DFSF.LabelReturnAlloca);
1206           DFSF.setShadow(CustomCI, LabelLoad);
1207         }
1208
1209         CI->replaceAllUsesWith(CustomCI);
1210         CI->eraseFromParent();
1211         return;
1212       }
1213       break;
1214     }
1215     }
1216   }
1217
1218   FunctionType *FT = cast<FunctionType>(
1219       CS.getCalledValue()->getType()->getPointerElementType());
1220   if (DFSF.DFS.getInstrumentedABI() == DataFlowSanitizer::IA_TLS) {
1221     for (unsigned i = 0, n = FT->getNumParams(); i != n; ++i) {
1222       IRB.CreateStore(DFSF.getShadow(CS.getArgument(i)),
1223                       DFSF.getArgTLS(i, CS.getInstruction()));
1224     }
1225   }
1226
1227   Instruction *Next = 0;
1228   if (!CS.getType()->isVoidTy()) {
1229     if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
1230       if (II->getNormalDest()->getSinglePredecessor()) {
1231         Next = II->getNormalDest()->begin();
1232       } else {
1233         BasicBlock *NewBB =
1234             SplitEdge(II->getParent(), II->getNormalDest(), &DFSF.DFS);
1235         Next = NewBB->begin();
1236       }
1237     } else {
1238       Next = CS->getNextNode();
1239     }
1240
1241     if (DFSF.DFS.getInstrumentedABI() == DataFlowSanitizer::IA_TLS) {
1242       IRBuilder<> NextIRB(Next);
1243       LoadInst *LI = NextIRB.CreateLoad(DFSF.getRetvalTLS());
1244       DFSF.SkipInsts.insert(LI);
1245       DFSF.setShadow(CS.getInstruction(), LI);
1246       DFSF.NonZeroChecks.insert(LI);
1247     }
1248   }
1249
1250   // Do all instrumentation for IA_Args down here to defer tampering with the
1251   // CFG in a way that SplitEdge may be able to detect.
1252   if (DFSF.DFS.getInstrumentedABI() == DataFlowSanitizer::IA_Args) {
1253     FunctionType *NewFT = DFSF.DFS.getArgsFunctionType(FT);
1254     Value *Func =
1255         IRB.CreateBitCast(CS.getCalledValue(), PointerType::getUnqual(NewFT));
1256     std::vector<Value *> Args;
1257
1258     CallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
1259     for (unsigned n = FT->getNumParams(); n != 0; ++i, --n)
1260       Args.push_back(*i);
1261
1262     i = CS.arg_begin();
1263     for (unsigned n = FT->getNumParams(); n != 0; ++i, --n)
1264       Args.push_back(DFSF.getShadow(*i));
1265
1266     if (FT->isVarArg()) {
1267       unsigned VarArgSize = CS.arg_size() - FT->getNumParams();
1268       ArrayType *VarArgArrayTy = ArrayType::get(DFSF.DFS.ShadowTy, VarArgSize);
1269       AllocaInst *VarArgShadow =
1270           new AllocaInst(VarArgArrayTy, "", DFSF.F->getEntryBlock().begin());
1271       Args.push_back(IRB.CreateConstGEP2_32(VarArgShadow, 0, 0));
1272       for (unsigned n = 0; i != e; ++i, ++n) {
1273         IRB.CreateStore(DFSF.getShadow(*i),
1274                         IRB.CreateConstGEP2_32(VarArgShadow, 0, n));
1275         Args.push_back(*i);
1276       }
1277     }
1278
1279     CallSite NewCS;
1280     if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
1281       NewCS = IRB.CreateInvoke(Func, II->getNormalDest(), II->getUnwindDest(),
1282                                Args);
1283     } else {
1284       NewCS = IRB.CreateCall(Func, Args);
1285     }
1286     NewCS.setCallingConv(CS.getCallingConv());
1287     NewCS.setAttributes(CS.getAttributes().removeAttributes(
1288         *DFSF.DFS.Ctx, AttributeSet::ReturnIndex,
1289         AttributeFuncs::typeIncompatible(NewCS.getInstruction()->getType(),
1290                                          AttributeSet::ReturnIndex)));
1291
1292     if (Next) {
1293       ExtractValueInst *ExVal =
1294           ExtractValueInst::Create(NewCS.getInstruction(), 0, "", Next);
1295       DFSF.SkipInsts.insert(ExVal);
1296       ExtractValueInst *ExShadow =
1297           ExtractValueInst::Create(NewCS.getInstruction(), 1, "", Next);
1298       DFSF.SkipInsts.insert(ExShadow);
1299       DFSF.setShadow(ExVal, ExShadow);
1300       DFSF.NonZeroChecks.insert(ExShadow);
1301
1302       CS.getInstruction()->replaceAllUsesWith(ExVal);
1303     }
1304
1305     CS.getInstruction()->eraseFromParent();
1306   }
1307 }
1308
1309 void DFSanVisitor::visitPHINode(PHINode &PN) {
1310   PHINode *ShadowPN =
1311       PHINode::Create(DFSF.DFS.ShadowTy, PN.getNumIncomingValues(), "", &PN);
1312
1313   // Give the shadow phi node valid predecessors to fool SplitEdge into working.
1314   Value *UndefShadow = UndefValue::get(DFSF.DFS.ShadowTy);
1315   for (PHINode::block_iterator i = PN.block_begin(), e = PN.block_end(); i != e;
1316        ++i) {
1317     ShadowPN->addIncoming(UndefShadow, *i);
1318   }
1319
1320   DFSF.PHIFixups.push_back(std::make_pair(&PN, ShadowPN));
1321   DFSF.setShadow(&PN, ShadowPN);
1322 }