[asan] do not treat inline asm calls as indirect calls
[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/ADT/StringExtras.h"
52 #include "llvm/Analysis/ValueTracking.h"
53 #include "llvm/IR/Dominators.h"
54 #include "llvm/IR/DebugInfo.h"
55 #include "llvm/IR/IRBuilder.h"
56 #include "llvm/IR/InlineAsm.h"
57 #include "llvm/IR/InstVisitor.h"
58 #include "llvm/IR/LLVMContext.h"
59 #include "llvm/IR/MDBuilder.h"
60 #include "llvm/IR/Type.h"
61 #include "llvm/IR/Value.h"
62 #include "llvm/Pass.h"
63 #include "llvm/Support/CommandLine.h"
64 #include "llvm/Support/SpecialCaseList.h"
65 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
66 #include "llvm/Transforms/Utils/Local.h"
67 #include <algorithm>
68 #include <iterator>
69 #include <set>
70 #include <utility>
71
72 using namespace llvm;
73
74 // The -dfsan-preserve-alignment flag controls whether this pass assumes that
75 // alignment requirements provided by the input IR are correct.  For example,
76 // if the input IR contains a load with alignment 8, this flag will cause
77 // the shadow load to have alignment 16.  This flag is disabled by default as
78 // we have unfortunately encountered too much code (including Clang itself;
79 // see PR14291) which performs misaligned access.
80 static cl::opt<bool> ClPreserveAlignment(
81     "dfsan-preserve-alignment",
82     cl::desc("respect alignment requirements provided by input IR"), cl::Hidden,
83     cl::init(false));
84
85 // The ABI list file controls how shadow parameters are passed.  The pass treats
86 // every function labelled "uninstrumented" in the ABI list file as conforming
87 // to the "native" (i.e. unsanitized) ABI.  Unless the ABI list contains
88 // additional annotations for those functions, a call to one of those functions
89 // will produce a warning message, as the labelling behaviour of the function is
90 // unknown.  The other supported annotations are "functional" and "discard",
91 // which are described below under DataFlowSanitizer::WrapperKind.
92 static cl::opt<std::string> ClABIListFile(
93     "dfsan-abilist",
94     cl::desc("File listing native ABI functions and how the pass treats them"),
95     cl::Hidden);
96
97 // Controls whether the pass uses IA_Args or IA_TLS as the ABI for instrumented
98 // functions (see DataFlowSanitizer::InstrumentedABI below).
99 static cl::opt<bool> ClArgsABI(
100     "dfsan-args-abi",
101     cl::desc("Use the argument ABI rather than the TLS ABI"),
102     cl::Hidden);
103
104 // Controls whether the pass includes or ignores the labels of pointers in load
105 // instructions.
106 static cl::opt<bool> ClCombinePointerLabelsOnLoad(
107     "dfsan-combine-pointer-labels-on-load",
108     cl::desc("Combine the label of the pointer with the label of the data when "
109              "loading from memory."),
110     cl::Hidden, cl::init(true));
111
112 // Controls whether the pass includes or ignores the labels of pointers in
113 // stores instructions.
114 static cl::opt<bool> ClCombinePointerLabelsOnStore(
115     "dfsan-combine-pointer-labels-on-store",
116     cl::desc("Combine the label of the pointer with the label of the data when "
117              "storing in memory."),
118     cl::Hidden, cl::init(false));
119
120 static cl::opt<bool> ClDebugNonzeroLabels(
121     "dfsan-debug-nonzero-labels",
122     cl::desc("Insert calls to __dfsan_nonzero_label on observing a parameter, "
123              "load or return with a nonzero label"),
124     cl::Hidden);
125
126 namespace {
127
128 StringRef GetGlobalTypeString(const GlobalValue &G) {
129   // Types of GlobalVariables are always pointer types.
130   Type *GType = G.getType()->getElementType();
131   // For now we support blacklisting struct types only.
132   if (StructType *SGType = dyn_cast<StructType>(GType)) {
133     if (!SGType->isLiteral())
134       return SGType->getName();
135   }
136   return "<unknown type>";
137 }
138
139 class DFSanABIList {
140   std::unique_ptr<SpecialCaseList> SCL;
141
142  public:
143   DFSanABIList(std::unique_ptr<SpecialCaseList> SCL) : SCL(std::move(SCL)) {}
144
145   /// Returns whether either this function or its source file are listed in the
146   /// given category.
147   bool isIn(const Function &F, StringRef Category) const {
148     return isIn(*F.getParent(), Category) ||
149            SCL->inSection("fun", F.getName(), Category);
150   }
151
152   /// Returns whether this global alias is listed in the given category.
153   ///
154   /// If GA aliases a function, the alias's name is matched as a function name
155   /// would be.  Similarly, aliases of globals are matched like globals.
156   bool isIn(const GlobalAlias &GA, StringRef Category) const {
157     if (isIn(*GA.getParent(), Category))
158       return true;
159
160     if (isa<FunctionType>(GA.getType()->getElementType()))
161       return SCL->inSection("fun", GA.getName(), Category);
162
163     return SCL->inSection("global", GA.getName(), Category) ||
164            SCL->inSection("type", GetGlobalTypeString(GA), Category);
165   }
166
167   /// Returns whether this module is listed in the given category.
168   bool isIn(const Module &M, StringRef Category) const {
169     return SCL->inSection("src", M.getModuleIdentifier(), Category);
170   }
171 };
172
173 class DataFlowSanitizer : public ModulePass {
174   friend struct DFSanFunction;
175   friend class DFSanVisitor;
176
177   enum {
178     ShadowWidth = 16
179   };
180
181   /// Which ABI should be used for instrumented functions?
182   enum InstrumentedABI {
183     /// Argument and return value labels are passed through additional
184     /// arguments and by modifying the return type.
185     IA_Args,
186
187     /// Argument and return value labels are passed through TLS variables
188     /// __dfsan_arg_tls and __dfsan_retval_tls.
189     IA_TLS
190   };
191
192   /// How should calls to uninstrumented functions be handled?
193   enum WrapperKind {
194     /// This function is present in an uninstrumented form but we don't know
195     /// how it should be handled.  Print a warning and call the function anyway.
196     /// Don't label the return value.
197     WK_Warning,
198
199     /// This function does not write to (user-accessible) memory, and its return
200     /// value is unlabelled.
201     WK_Discard,
202
203     /// This function does not write to (user-accessible) memory, and the label
204     /// of its return value is the union of the label of its arguments.
205     WK_Functional,
206
207     /// Instead of calling the function, a custom wrapper __dfsw_F is called,
208     /// where F is the name of the function.  This function may wrap the
209     /// original function or provide its own implementation.  This is similar to
210     /// the IA_Args ABI, except that IA_Args uses a struct return type to
211     /// pass the return value shadow in a register, while WK_Custom uses an
212     /// extra pointer argument to return the shadow.  This allows the wrapped
213     /// form of the function type to be expressed in C.
214     WK_Custom
215   };
216
217   const DataLayout *DL;
218   Module *Mod;
219   LLVMContext *Ctx;
220   IntegerType *ShadowTy;
221   PointerType *ShadowPtrTy;
222   IntegerType *IntptrTy;
223   ConstantInt *ZeroShadow;
224   ConstantInt *ShadowPtrMask;
225   ConstantInt *ShadowPtrMul;
226   Constant *ArgTLS;
227   Constant *RetvalTLS;
228   void *(*GetArgTLSPtr)();
229   void *(*GetRetvalTLSPtr)();
230   Constant *GetArgTLS;
231   Constant *GetRetvalTLS;
232   FunctionType *DFSanUnionFnTy;
233   FunctionType *DFSanUnionLoadFnTy;
234   FunctionType *DFSanUnimplementedFnTy;
235   FunctionType *DFSanSetLabelFnTy;
236   FunctionType *DFSanNonzeroLabelFnTy;
237   Constant *DFSanUnionFn;
238   Constant *DFSanCheckedUnionFn;
239   Constant *DFSanUnionLoadFn;
240   Constant *DFSanUnimplementedFn;
241   Constant *DFSanSetLabelFn;
242   Constant *DFSanNonzeroLabelFn;
243   MDNode *ColdCallWeights;
244   DFSanABIList ABIList;
245   DenseMap<Value *, Function *> UnwrappedFnMap;
246   AttributeSet ReadOnlyNoneAttrs;
247   DenseMap<const Function *, DISubprogram> FunctionDIs;
248
249   Value *getShadowAddress(Value *Addr, Instruction *Pos);
250   bool isInstrumented(const Function *F);
251   bool isInstrumented(const GlobalAlias *GA);
252   FunctionType *getArgsFunctionType(FunctionType *T);
253   FunctionType *getTrampolineFunctionType(FunctionType *T);
254   FunctionType *getCustomFunctionType(FunctionType *T);
255   InstrumentedABI getInstrumentedABI();
256   WrapperKind getWrapperKind(Function *F);
257   void addGlobalNamePrefix(GlobalValue *GV);
258   Function *buildWrapperFunction(Function *F, StringRef NewFName,
259                                  GlobalValue::LinkageTypes NewFLink,
260                                  FunctionType *NewFT);
261   Constant *getOrBuildTrampolineFunction(FunctionType *FT, StringRef FName);
262
263  public:
264   DataFlowSanitizer(StringRef ABIListFile = StringRef(),
265                     void *(*getArgTLS)() = nullptr,
266                     void *(*getRetValTLS)() = nullptr);
267   static char ID;
268   bool doInitialization(Module &M) override;
269   bool runOnModule(Module &M) override;
270 };
271
272 struct DFSanFunction {
273   DataFlowSanitizer &DFS;
274   Function *F;
275   DominatorTree DT;
276   DataFlowSanitizer::InstrumentedABI IA;
277   bool IsNativeABI;
278   Value *ArgTLSPtr;
279   Value *RetvalTLSPtr;
280   AllocaInst *LabelReturnAlloca;
281   DenseMap<Value *, Value *> ValShadowMap;
282   DenseMap<AllocaInst *, AllocaInst *> AllocaShadowMap;
283   std::vector<std::pair<PHINode *, PHINode *> > PHIFixups;
284   DenseSet<Instruction *> SkipInsts;
285   std::vector<Value *> NonZeroChecks;
286   bool AvoidNewBlocks;
287
288   struct CachedCombinedShadow {
289     BasicBlock *Block;
290     Value *Shadow;
291   };
292   DenseMap<std::pair<Value *, Value *>, CachedCombinedShadow>
293       CachedCombinedShadows;
294   DenseMap<Value *, std::set<Value *>> ShadowElements;
295
296   DFSanFunction(DataFlowSanitizer &DFS, Function *F, bool IsNativeABI)
297       : DFS(DFS), F(F), IA(DFS.getInstrumentedABI()),
298         IsNativeABI(IsNativeABI), ArgTLSPtr(nullptr), RetvalTLSPtr(nullptr),
299         LabelReturnAlloca(nullptr) {
300     DT.recalculate(*F);
301     // FIXME: Need to track down the register allocator issue which causes poor
302     // performance in pathological cases with large numbers of basic blocks.
303     AvoidNewBlocks = F->size() > 1000;
304   }
305   Value *getArgTLSPtr();
306   Value *getArgTLS(unsigned Index, Instruction *Pos);
307   Value *getRetvalTLS();
308   Value *getShadow(Value *V);
309   void setShadow(Instruction *I, Value *Shadow);
310   Value *combineShadows(Value *V1, Value *V2, Instruction *Pos);
311   Value *combineOperandShadows(Instruction *Inst);
312   Value *loadShadow(Value *ShadowAddr, uint64_t Size, uint64_t Align,
313                     Instruction *Pos);
314   void storeShadow(Value *Addr, uint64_t Size, uint64_t Align, Value *Shadow,
315                    Instruction *Pos);
316 };
317
318 class DFSanVisitor : public InstVisitor<DFSanVisitor> {
319  public:
320   DFSanFunction &DFSF;
321   DFSanVisitor(DFSanFunction &DFSF) : DFSF(DFSF) {}
322
323   void visitOperandShadowInst(Instruction &I);
324
325   void visitBinaryOperator(BinaryOperator &BO);
326   void visitCastInst(CastInst &CI);
327   void visitCmpInst(CmpInst &CI);
328   void visitGetElementPtrInst(GetElementPtrInst &GEPI);
329   void visitLoadInst(LoadInst &LI);
330   void visitStoreInst(StoreInst &SI);
331   void visitReturnInst(ReturnInst &RI);
332   void visitCallSite(CallSite CS);
333   void visitPHINode(PHINode &PN);
334   void visitExtractElementInst(ExtractElementInst &I);
335   void visitInsertElementInst(InsertElementInst &I);
336   void visitShuffleVectorInst(ShuffleVectorInst &I);
337   void visitExtractValueInst(ExtractValueInst &I);
338   void visitInsertValueInst(InsertValueInst &I);
339   void visitAllocaInst(AllocaInst &I);
340   void visitSelectInst(SelectInst &I);
341   void visitMemSetInst(MemSetInst &I);
342   void visitMemTransferInst(MemTransferInst &I);
343 };
344
345 }
346
347 char DataFlowSanitizer::ID;
348 INITIALIZE_PASS(DataFlowSanitizer, "dfsan",
349                 "DataFlowSanitizer: dynamic data flow analysis.", false, false)
350
351 ModulePass *llvm::createDataFlowSanitizerPass(StringRef ABIListFile,
352                                               void *(*getArgTLS)(),
353                                               void *(*getRetValTLS)()) {
354   return new DataFlowSanitizer(ABIListFile, getArgTLS, getRetValTLS);
355 }
356
357 DataFlowSanitizer::DataFlowSanitizer(StringRef ABIListFile,
358                                      void *(*getArgTLS)(),
359                                      void *(*getRetValTLS)())
360     : ModulePass(ID), GetArgTLSPtr(getArgTLS), GetRetvalTLSPtr(getRetValTLS),
361       ABIList(SpecialCaseList::createOrDie(ABIListFile.empty() ? ClABIListFile
362                                                                : ABIListFile)) {
363 }
364
365 FunctionType *DataFlowSanitizer::getArgsFunctionType(FunctionType *T) {
366   llvm::SmallVector<Type *, 4> ArgTypes;
367   std::copy(T->param_begin(), T->param_end(), std::back_inserter(ArgTypes));
368   for (unsigned i = 0, e = T->getNumParams(); i != e; ++i)
369     ArgTypes.push_back(ShadowTy);
370   if (T->isVarArg())
371     ArgTypes.push_back(ShadowPtrTy);
372   Type *RetType = T->getReturnType();
373   if (!RetType->isVoidTy())
374     RetType = StructType::get(RetType, ShadowTy, (Type *)nullptr);
375   return FunctionType::get(RetType, ArgTypes, T->isVarArg());
376 }
377
378 FunctionType *DataFlowSanitizer::getTrampolineFunctionType(FunctionType *T) {
379   assert(!T->isVarArg());
380   llvm::SmallVector<Type *, 4> ArgTypes;
381   ArgTypes.push_back(T->getPointerTo());
382   std::copy(T->param_begin(), T->param_end(), std::back_inserter(ArgTypes));
383   for (unsigned i = 0, e = T->getNumParams(); i != e; ++i)
384     ArgTypes.push_back(ShadowTy);
385   Type *RetType = T->getReturnType();
386   if (!RetType->isVoidTy())
387     ArgTypes.push_back(ShadowPtrTy);
388   return FunctionType::get(T->getReturnType(), ArgTypes, false);
389 }
390
391 FunctionType *DataFlowSanitizer::getCustomFunctionType(FunctionType *T) {
392   llvm::SmallVector<Type *, 4> ArgTypes;
393   for (FunctionType::param_iterator i = T->param_begin(), e = T->param_end();
394        i != e; ++i) {
395     FunctionType *FT;
396     if (isa<PointerType>(*i) && (FT = dyn_cast<FunctionType>(cast<PointerType>(
397                                      *i)->getElementType()))) {
398       ArgTypes.push_back(getTrampolineFunctionType(FT)->getPointerTo());
399       ArgTypes.push_back(Type::getInt8PtrTy(*Ctx));
400     } else {
401       ArgTypes.push_back(*i);
402     }
403   }
404   for (unsigned i = 0, e = T->getNumParams(); i != e; ++i)
405     ArgTypes.push_back(ShadowTy);
406   if (T->isVarArg())
407     ArgTypes.push_back(ShadowPtrTy);
408   Type *RetType = T->getReturnType();
409   if (!RetType->isVoidTy())
410     ArgTypes.push_back(ShadowPtrTy);
411   return FunctionType::get(T->getReturnType(), ArgTypes, T->isVarArg());
412 }
413
414 bool DataFlowSanitizer::doInitialization(Module &M) {
415   DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
416   if (!DLP)
417     report_fatal_error("data layout missing");
418   DL = &DLP->getDataLayout();
419
420   Mod = &M;
421   Ctx = &M.getContext();
422   ShadowTy = IntegerType::get(*Ctx, ShadowWidth);
423   ShadowPtrTy = PointerType::getUnqual(ShadowTy);
424   IntptrTy = DL->getIntPtrType(*Ctx);
425   ZeroShadow = ConstantInt::getSigned(ShadowTy, 0);
426   ShadowPtrMask = ConstantInt::getSigned(IntptrTy, ~0x700000000000LL);
427   ShadowPtrMul = ConstantInt::getSigned(IntptrTy, ShadowWidth / 8);
428
429   Type *DFSanUnionArgs[2] = { ShadowTy, ShadowTy };
430   DFSanUnionFnTy =
431       FunctionType::get(ShadowTy, DFSanUnionArgs, /*isVarArg=*/ false);
432   Type *DFSanUnionLoadArgs[2] = { ShadowPtrTy, IntptrTy };
433   DFSanUnionLoadFnTy =
434       FunctionType::get(ShadowTy, DFSanUnionLoadArgs, /*isVarArg=*/ false);
435   DFSanUnimplementedFnTy = FunctionType::get(
436       Type::getVoidTy(*Ctx), Type::getInt8PtrTy(*Ctx), /*isVarArg=*/false);
437   Type *DFSanSetLabelArgs[3] = { ShadowTy, Type::getInt8PtrTy(*Ctx), IntptrTy };
438   DFSanSetLabelFnTy = FunctionType::get(Type::getVoidTy(*Ctx),
439                                         DFSanSetLabelArgs, /*isVarArg=*/false);
440   DFSanNonzeroLabelFnTy = FunctionType::get(
441       Type::getVoidTy(*Ctx), None, /*isVarArg=*/false);
442
443   if (GetArgTLSPtr) {
444     Type *ArgTLSTy = ArrayType::get(ShadowTy, 64);
445     ArgTLS = nullptr;
446     GetArgTLS = ConstantExpr::getIntToPtr(
447         ConstantInt::get(IntptrTy, uintptr_t(GetArgTLSPtr)),
448         PointerType::getUnqual(
449             FunctionType::get(PointerType::getUnqual(ArgTLSTy),
450                               (Type *)nullptr)));
451   }
452   if (GetRetvalTLSPtr) {
453     RetvalTLS = nullptr;
454     GetRetvalTLS = ConstantExpr::getIntToPtr(
455         ConstantInt::get(IntptrTy, uintptr_t(GetRetvalTLSPtr)),
456         PointerType::getUnqual(
457             FunctionType::get(PointerType::getUnqual(ShadowTy),
458                               (Type *)nullptr)));
459   }
460
461   ColdCallWeights = MDBuilder(*Ctx).createBranchWeights(1, 1000);
462   return true;
463 }
464
465 bool DataFlowSanitizer::isInstrumented(const Function *F) {
466   return !ABIList.isIn(*F, "uninstrumented");
467 }
468
469 bool DataFlowSanitizer::isInstrumented(const GlobalAlias *GA) {
470   return !ABIList.isIn(*GA, "uninstrumented");
471 }
472
473 DataFlowSanitizer::InstrumentedABI DataFlowSanitizer::getInstrumentedABI() {
474   return ClArgsABI ? IA_Args : IA_TLS;
475 }
476
477 DataFlowSanitizer::WrapperKind DataFlowSanitizer::getWrapperKind(Function *F) {
478   if (ABIList.isIn(*F, "functional"))
479     return WK_Functional;
480   if (ABIList.isIn(*F, "discard"))
481     return WK_Discard;
482   if (ABIList.isIn(*F, "custom"))
483     return WK_Custom;
484
485   return WK_Warning;
486 }
487
488 void DataFlowSanitizer::addGlobalNamePrefix(GlobalValue *GV) {
489   std::string GVName = GV->getName(), Prefix = "dfs$";
490   GV->setName(Prefix + GVName);
491
492   // Try to change the name of the function in module inline asm.  We only do
493   // this for specific asm directives, currently only ".symver", to try to avoid
494   // corrupting asm which happens to contain the symbol name as a substring.
495   // Note that the substitution for .symver assumes that the versioned symbol
496   // also has an instrumented name.
497   std::string Asm = GV->getParent()->getModuleInlineAsm();
498   std::string SearchStr = ".symver " + GVName + ",";
499   size_t Pos = Asm.find(SearchStr);
500   if (Pos != std::string::npos) {
501     Asm.replace(Pos, SearchStr.size(),
502                 ".symver " + Prefix + GVName + "," + Prefix);
503     GV->getParent()->setModuleInlineAsm(Asm);
504   }
505 }
506
507 Function *
508 DataFlowSanitizer::buildWrapperFunction(Function *F, StringRef NewFName,
509                                         GlobalValue::LinkageTypes NewFLink,
510                                         FunctionType *NewFT) {
511   FunctionType *FT = F->getFunctionType();
512   Function *NewF = Function::Create(NewFT, NewFLink, NewFName,
513                                     F->getParent());
514   NewF->copyAttributesFrom(F);
515   NewF->removeAttributes(
516       AttributeSet::ReturnIndex,
517       AttributeFuncs::typeIncompatible(NewFT->getReturnType(),
518                                        AttributeSet::ReturnIndex));
519
520   BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", NewF);
521   std::vector<Value *> Args;
522   unsigned n = FT->getNumParams();
523   for (Function::arg_iterator ai = NewF->arg_begin(); n != 0; ++ai, --n)
524     Args.push_back(&*ai);
525   CallInst *CI = CallInst::Create(F, Args, "", BB);
526   if (FT->getReturnType()->isVoidTy())
527     ReturnInst::Create(*Ctx, BB);
528   else
529     ReturnInst::Create(*Ctx, CI, BB);
530
531   return NewF;
532 }
533
534 Constant *DataFlowSanitizer::getOrBuildTrampolineFunction(FunctionType *FT,
535                                                           StringRef FName) {
536   FunctionType *FTT = getTrampolineFunctionType(FT);
537   Constant *C = Mod->getOrInsertFunction(FName, FTT);
538   Function *F = dyn_cast<Function>(C);
539   if (F && F->isDeclaration()) {
540     F->setLinkage(GlobalValue::LinkOnceODRLinkage);
541     BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", F);
542     std::vector<Value *> Args;
543     Function::arg_iterator AI = F->arg_begin(); ++AI;
544     for (unsigned N = FT->getNumParams(); N != 0; ++AI, --N)
545       Args.push_back(&*AI);
546     CallInst *CI =
547         CallInst::Create(&F->getArgumentList().front(), Args, "", BB);
548     ReturnInst *RI;
549     if (FT->getReturnType()->isVoidTy())
550       RI = ReturnInst::Create(*Ctx, BB);
551     else
552       RI = ReturnInst::Create(*Ctx, CI, BB);
553
554     DFSanFunction DFSF(*this, F, /*IsNativeABI=*/true);
555     Function::arg_iterator ValAI = F->arg_begin(), ShadowAI = AI; ++ValAI;
556     for (unsigned N = FT->getNumParams(); N != 0; ++ValAI, ++ShadowAI, --N)
557       DFSF.ValShadowMap[ValAI] = ShadowAI;
558     DFSanVisitor(DFSF).visitCallInst(*CI);
559     if (!FT->getReturnType()->isVoidTy())
560       new StoreInst(DFSF.getShadow(RI->getReturnValue()),
561                     &F->getArgumentList().back(), RI);
562   }
563
564   return C;
565 }
566
567 bool DataFlowSanitizer::runOnModule(Module &M) {
568   if (!DL)
569     return false;
570
571   if (ABIList.isIn(M, "skip"))
572     return false;
573
574   FunctionDIs = makeSubprogramMap(M);
575
576   if (!GetArgTLSPtr) {
577     Type *ArgTLSTy = ArrayType::get(ShadowTy, 64);
578     ArgTLS = Mod->getOrInsertGlobal("__dfsan_arg_tls", ArgTLSTy);
579     if (GlobalVariable *G = dyn_cast<GlobalVariable>(ArgTLS))
580       G->setThreadLocalMode(GlobalVariable::InitialExecTLSModel);
581   }
582   if (!GetRetvalTLSPtr) {
583     RetvalTLS = Mod->getOrInsertGlobal("__dfsan_retval_tls", ShadowTy);
584     if (GlobalVariable *G = dyn_cast<GlobalVariable>(RetvalTLS))
585       G->setThreadLocalMode(GlobalVariable::InitialExecTLSModel);
586   }
587
588   DFSanUnionFn = Mod->getOrInsertFunction("__dfsan_union", DFSanUnionFnTy);
589   if (Function *F = dyn_cast<Function>(DFSanUnionFn)) {
590     F->addAttribute(AttributeSet::FunctionIndex, Attribute::NoUnwind);
591     F->addAttribute(AttributeSet::FunctionIndex, Attribute::ReadNone);
592     F->addAttribute(AttributeSet::ReturnIndex, Attribute::ZExt);
593     F->addAttribute(1, Attribute::ZExt);
594     F->addAttribute(2, Attribute::ZExt);
595   }
596   DFSanCheckedUnionFn = Mod->getOrInsertFunction("dfsan_union", DFSanUnionFnTy);
597   if (Function *F = dyn_cast<Function>(DFSanCheckedUnionFn)) {
598     F->addAttribute(AttributeSet::FunctionIndex, Attribute::NoUnwind);
599     F->addAttribute(AttributeSet::FunctionIndex, Attribute::ReadNone);
600     F->addAttribute(AttributeSet::ReturnIndex, Attribute::ZExt);
601     F->addAttribute(1, Attribute::ZExt);
602     F->addAttribute(2, Attribute::ZExt);
603   }
604   DFSanUnionLoadFn =
605       Mod->getOrInsertFunction("__dfsan_union_load", DFSanUnionLoadFnTy);
606   if (Function *F = dyn_cast<Function>(DFSanUnionLoadFn)) {
607     F->addAttribute(AttributeSet::FunctionIndex, Attribute::NoUnwind);
608     F->addAttribute(AttributeSet::FunctionIndex, Attribute::ReadOnly);
609     F->addAttribute(AttributeSet::ReturnIndex, Attribute::ZExt);
610   }
611   DFSanUnimplementedFn =
612       Mod->getOrInsertFunction("__dfsan_unimplemented", DFSanUnimplementedFnTy);
613   DFSanSetLabelFn =
614       Mod->getOrInsertFunction("__dfsan_set_label", DFSanSetLabelFnTy);
615   if (Function *F = dyn_cast<Function>(DFSanSetLabelFn)) {
616     F->addAttribute(1, Attribute::ZExt);
617   }
618   DFSanNonzeroLabelFn =
619       Mod->getOrInsertFunction("__dfsan_nonzero_label", DFSanNonzeroLabelFnTy);
620
621   std::vector<Function *> FnsToInstrument;
622   llvm::SmallPtrSet<Function *, 2> FnsWithNativeABI;
623   for (Module::iterator i = M.begin(), e = M.end(); i != e; ++i) {
624     if (!i->isIntrinsic() &&
625         i != DFSanUnionFn &&
626         i != DFSanCheckedUnionFn &&
627         i != DFSanUnionLoadFn &&
628         i != DFSanUnimplementedFn &&
629         i != DFSanSetLabelFn &&
630         i != DFSanNonzeroLabelFn)
631       FnsToInstrument.push_back(&*i);
632   }
633
634   // Give function aliases prefixes when necessary, and build wrappers where the
635   // instrumentedness is inconsistent.
636   for (Module::alias_iterator i = M.alias_begin(), e = M.alias_end(); i != e;) {
637     GlobalAlias *GA = &*i;
638     ++i;
639     // Don't stop on weak.  We assume people aren't playing games with the
640     // instrumentedness of overridden weak aliases.
641     if (auto F = dyn_cast<Function>(GA->getBaseObject())) {
642       bool GAInst = isInstrumented(GA), FInst = isInstrumented(F);
643       if (GAInst && FInst) {
644         addGlobalNamePrefix(GA);
645       } else if (GAInst != FInst) {
646         // Non-instrumented alias of an instrumented function, or vice versa.
647         // Replace the alias with a native-ABI wrapper of the aliasee.  The pass
648         // below will take care of instrumenting it.
649         Function *NewF =
650             buildWrapperFunction(F, "", GA->getLinkage(), F->getFunctionType());
651         GA->replaceAllUsesWith(ConstantExpr::getBitCast(NewF, GA->getType()));
652         NewF->takeName(GA);
653         GA->eraseFromParent();
654         FnsToInstrument.push_back(NewF);
655       }
656     }
657   }
658
659   AttrBuilder B;
660   B.addAttribute(Attribute::ReadOnly).addAttribute(Attribute::ReadNone);
661   ReadOnlyNoneAttrs = AttributeSet::get(*Ctx, AttributeSet::FunctionIndex, B);
662
663   // First, change the ABI of every function in the module.  ABI-listed
664   // functions keep their original ABI and get a wrapper function.
665   for (std::vector<Function *>::iterator i = FnsToInstrument.begin(),
666                                          e = FnsToInstrument.end();
667        i != e; ++i) {
668     Function &F = **i;
669     FunctionType *FT = F.getFunctionType();
670
671     bool IsZeroArgsVoidRet = (FT->getNumParams() == 0 && !FT->isVarArg() &&
672                               FT->getReturnType()->isVoidTy());
673
674     if (isInstrumented(&F)) {
675       // Instrumented functions get a 'dfs$' prefix.  This allows us to more
676       // easily identify cases of mismatching ABIs.
677       if (getInstrumentedABI() == IA_Args && !IsZeroArgsVoidRet) {
678         FunctionType *NewFT = getArgsFunctionType(FT);
679         Function *NewF = Function::Create(NewFT, F.getLinkage(), "", &M);
680         NewF->copyAttributesFrom(&F);
681         NewF->removeAttributes(
682             AttributeSet::ReturnIndex,
683             AttributeFuncs::typeIncompatible(NewFT->getReturnType(),
684                                              AttributeSet::ReturnIndex));
685         for (Function::arg_iterator FArg = F.arg_begin(),
686                                     NewFArg = NewF->arg_begin(),
687                                     FArgEnd = F.arg_end();
688              FArg != FArgEnd; ++FArg, ++NewFArg) {
689           FArg->replaceAllUsesWith(NewFArg);
690         }
691         NewF->getBasicBlockList().splice(NewF->begin(), F.getBasicBlockList());
692
693         for (Function::user_iterator UI = F.user_begin(), UE = F.user_end();
694              UI != UE;) {
695           BlockAddress *BA = dyn_cast<BlockAddress>(*UI);
696           ++UI;
697           if (BA) {
698             BA->replaceAllUsesWith(
699                 BlockAddress::get(NewF, BA->getBasicBlock()));
700             delete BA;
701           }
702         }
703         F.replaceAllUsesWith(
704             ConstantExpr::getBitCast(NewF, PointerType::getUnqual(FT)));
705         NewF->takeName(&F);
706         F.eraseFromParent();
707         *i = NewF;
708         addGlobalNamePrefix(NewF);
709       } else {
710         addGlobalNamePrefix(&F);
711       }
712     } else if (!IsZeroArgsVoidRet || getWrapperKind(&F) == WK_Custom) {
713       // Build a wrapper function for F.  The wrapper simply calls F, and is
714       // added to FnsToInstrument so that any instrumentation according to its
715       // WrapperKind is done in the second pass below.
716       FunctionType *NewFT = getInstrumentedABI() == IA_Args
717                                 ? getArgsFunctionType(FT)
718                                 : FT;
719       Function *NewF = buildWrapperFunction(
720           &F, std::string("dfsw$") + std::string(F.getName()),
721           GlobalValue::LinkOnceODRLinkage, NewFT);
722       if (getInstrumentedABI() == IA_TLS)
723         NewF->removeAttributes(AttributeSet::FunctionIndex, ReadOnlyNoneAttrs);
724
725       Value *WrappedFnCst =
726           ConstantExpr::getBitCast(NewF, PointerType::getUnqual(FT));
727       F.replaceAllUsesWith(WrappedFnCst);
728
729       // Patch the pointer to LLVM function in debug info descriptor.
730       auto DI = FunctionDIs.find(&F);
731       if (DI != FunctionDIs.end())
732         DI->second.replaceFunction(&F);
733
734       UnwrappedFnMap[WrappedFnCst] = &F;
735       *i = NewF;
736
737       if (!F.isDeclaration()) {
738         // This function is probably defining an interposition of an
739         // uninstrumented function and hence needs to keep the original ABI.
740         // But any functions it may call need to use the instrumented ABI, so
741         // we instrument it in a mode which preserves the original ABI.
742         FnsWithNativeABI.insert(&F);
743
744         // This code needs to rebuild the iterators, as they may be invalidated
745         // by the push_back, taking care that the new range does not include
746         // any functions added by this code.
747         size_t N = i - FnsToInstrument.begin(),
748                Count = e - FnsToInstrument.begin();
749         FnsToInstrument.push_back(&F);
750         i = FnsToInstrument.begin() + N;
751         e = FnsToInstrument.begin() + Count;
752       }
753                // Hopefully, nobody will try to indirectly call a vararg
754                // function... yet.
755     } else if (FT->isVarArg()) {
756       UnwrappedFnMap[&F] = &F;
757       *i = nullptr;
758     }
759   }
760
761   for (std::vector<Function *>::iterator i = FnsToInstrument.begin(),
762                                          e = FnsToInstrument.end();
763        i != e; ++i) {
764     if (!*i || (*i)->isDeclaration())
765       continue;
766
767     removeUnreachableBlocks(**i);
768
769     DFSanFunction DFSF(*this, *i, FnsWithNativeABI.count(*i));
770
771     // DFSanVisitor may create new basic blocks, which confuses df_iterator.
772     // Build a copy of the list before iterating over it.
773     llvm::SmallVector<BasicBlock *, 4> BBList(
774         depth_first(&(*i)->getEntryBlock()));
775
776     for (llvm::SmallVector<BasicBlock *, 4>::iterator i = BBList.begin(),
777                                                       e = BBList.end();
778          i != e; ++i) {
779       Instruction *Inst = &(*i)->front();
780       while (1) {
781         // DFSanVisitor may split the current basic block, changing the current
782         // instruction's next pointer and moving the next instruction to the
783         // tail block from which we should continue.
784         Instruction *Next = Inst->getNextNode();
785         // DFSanVisitor may delete Inst, so keep track of whether it was a
786         // terminator.
787         bool IsTerminator = isa<TerminatorInst>(Inst);
788         if (!DFSF.SkipInsts.count(Inst))
789           DFSanVisitor(DFSF).visit(Inst);
790         if (IsTerminator)
791           break;
792         Inst = Next;
793       }
794     }
795
796     // We will not necessarily be able to compute the shadow for every phi node
797     // until we have visited every block.  Therefore, the code that handles phi
798     // nodes adds them to the PHIFixups list so that they can be properly
799     // handled here.
800     for (std::vector<std::pair<PHINode *, PHINode *> >::iterator
801              i = DFSF.PHIFixups.begin(),
802              e = DFSF.PHIFixups.end();
803          i != e; ++i) {
804       for (unsigned val = 0, n = i->first->getNumIncomingValues(); val != n;
805            ++val) {
806         i->second->setIncomingValue(
807             val, DFSF.getShadow(i->first->getIncomingValue(val)));
808       }
809     }
810
811     // -dfsan-debug-nonzero-labels will split the CFG in all kinds of crazy
812     // places (i.e. instructions in basic blocks we haven't even begun visiting
813     // yet).  To make our life easier, do this work in a pass after the main
814     // instrumentation.
815     if (ClDebugNonzeroLabels) {
816       for (Value *V : DFSF.NonZeroChecks) {
817         Instruction *Pos;
818         if (Instruction *I = dyn_cast<Instruction>(V))
819           Pos = I->getNextNode();
820         else
821           Pos = DFSF.F->getEntryBlock().begin();
822         while (isa<PHINode>(Pos) || isa<AllocaInst>(Pos))
823           Pos = Pos->getNextNode();
824         IRBuilder<> IRB(Pos);
825         Value *Ne = IRB.CreateICmpNE(V, DFSF.DFS.ZeroShadow);
826         BranchInst *BI = cast<BranchInst>(SplitBlockAndInsertIfThen(
827             Ne, Pos, /*Unreachable=*/false, ColdCallWeights));
828         IRBuilder<> ThenIRB(BI);
829         ThenIRB.CreateCall(DFSF.DFS.DFSanNonzeroLabelFn);
830       }
831     }
832   }
833
834   return false;
835 }
836
837 Value *DFSanFunction::getArgTLSPtr() {
838   if (ArgTLSPtr)
839     return ArgTLSPtr;
840   if (DFS.ArgTLS)
841     return ArgTLSPtr = DFS.ArgTLS;
842
843   IRBuilder<> IRB(F->getEntryBlock().begin());
844   return ArgTLSPtr = IRB.CreateCall(DFS.GetArgTLS);
845 }
846
847 Value *DFSanFunction::getRetvalTLS() {
848   if (RetvalTLSPtr)
849     return RetvalTLSPtr;
850   if (DFS.RetvalTLS)
851     return RetvalTLSPtr = DFS.RetvalTLS;
852
853   IRBuilder<> IRB(F->getEntryBlock().begin());
854   return RetvalTLSPtr = IRB.CreateCall(DFS.GetRetvalTLS);
855 }
856
857 Value *DFSanFunction::getArgTLS(unsigned Idx, Instruction *Pos) {
858   IRBuilder<> IRB(Pos);
859   return IRB.CreateConstGEP2_64(getArgTLSPtr(), 0, Idx);
860 }
861
862 Value *DFSanFunction::getShadow(Value *V) {
863   if (!isa<Argument>(V) && !isa<Instruction>(V))
864     return DFS.ZeroShadow;
865   Value *&Shadow = ValShadowMap[V];
866   if (!Shadow) {
867     if (Argument *A = dyn_cast<Argument>(V)) {
868       if (IsNativeABI)
869         return DFS.ZeroShadow;
870       switch (IA) {
871       case DataFlowSanitizer::IA_TLS: {
872         Value *ArgTLSPtr = getArgTLSPtr();
873         Instruction *ArgTLSPos =
874             DFS.ArgTLS ? &*F->getEntryBlock().begin()
875                        : cast<Instruction>(ArgTLSPtr)->getNextNode();
876         IRBuilder<> IRB(ArgTLSPos);
877         Shadow = IRB.CreateLoad(getArgTLS(A->getArgNo(), ArgTLSPos));
878         break;
879       }
880       case DataFlowSanitizer::IA_Args: {
881         unsigned ArgIdx = A->getArgNo() + F->getArgumentList().size() / 2;
882         Function::arg_iterator i = F->arg_begin();
883         while (ArgIdx--)
884           ++i;
885         Shadow = i;
886         assert(Shadow->getType() == DFS.ShadowTy);
887         break;
888       }
889       }
890       NonZeroChecks.push_back(Shadow);
891     } else {
892       Shadow = DFS.ZeroShadow;
893     }
894   }
895   return Shadow;
896 }
897
898 void DFSanFunction::setShadow(Instruction *I, Value *Shadow) {
899   assert(!ValShadowMap.count(I));
900   assert(Shadow->getType() == DFS.ShadowTy);
901   ValShadowMap[I] = Shadow;
902 }
903
904 Value *DataFlowSanitizer::getShadowAddress(Value *Addr, Instruction *Pos) {
905   assert(Addr != RetvalTLS && "Reinstrumenting?");
906   IRBuilder<> IRB(Pos);
907   return IRB.CreateIntToPtr(
908       IRB.CreateMul(
909           IRB.CreateAnd(IRB.CreatePtrToInt(Addr, IntptrTy), ShadowPtrMask),
910           ShadowPtrMul),
911       ShadowPtrTy);
912 }
913
914 // Generates IR to compute the union of the two given shadows, inserting it
915 // before Pos.  Returns the computed union Value.
916 Value *DFSanFunction::combineShadows(Value *V1, Value *V2, Instruction *Pos) {
917   if (V1 == DFS.ZeroShadow)
918     return V2;
919   if (V2 == DFS.ZeroShadow)
920     return V1;
921   if (V1 == V2)
922     return V1;
923
924   auto V1Elems = ShadowElements.find(V1);
925   auto V2Elems = ShadowElements.find(V2);
926   if (V1Elems != ShadowElements.end() && V2Elems != ShadowElements.end()) {
927     if (std::includes(V1Elems->second.begin(), V1Elems->second.end(),
928                       V2Elems->second.begin(), V2Elems->second.end())) {
929       return V1;
930     } else if (std::includes(V2Elems->second.begin(), V2Elems->second.end(),
931                              V1Elems->second.begin(), V1Elems->second.end())) {
932       return V2;
933     }
934   } else if (V1Elems != ShadowElements.end()) {
935     if (V1Elems->second.count(V2))
936       return V1;
937   } else if (V2Elems != ShadowElements.end()) {
938     if (V2Elems->second.count(V1))
939       return V2;
940   }
941
942   auto Key = std::make_pair(V1, V2);
943   if (V1 > V2)
944     std::swap(Key.first, Key.second);
945   CachedCombinedShadow &CCS = CachedCombinedShadows[Key];
946   if (CCS.Block && DT.dominates(CCS.Block, Pos->getParent()))
947     return CCS.Shadow;
948
949   IRBuilder<> IRB(Pos);
950   if (AvoidNewBlocks) {
951     CallInst *Call = IRB.CreateCall2(DFS.DFSanCheckedUnionFn, V1, V2);
952     Call->addAttribute(AttributeSet::ReturnIndex, Attribute::ZExt);
953     Call->addAttribute(1, Attribute::ZExt);
954     Call->addAttribute(2, Attribute::ZExt);
955
956     CCS.Block = Pos->getParent();
957     CCS.Shadow = Call;
958   } else {
959     BasicBlock *Head = Pos->getParent();
960     Value *Ne = IRB.CreateICmpNE(V1, V2);
961     BranchInst *BI = cast<BranchInst>(SplitBlockAndInsertIfThen(
962         Ne, Pos, /*Unreachable=*/false, DFS.ColdCallWeights, &DT));
963     IRBuilder<> ThenIRB(BI);
964     CallInst *Call = ThenIRB.CreateCall2(DFS.DFSanUnionFn, V1, V2);
965     Call->addAttribute(AttributeSet::ReturnIndex, Attribute::ZExt);
966     Call->addAttribute(1, Attribute::ZExt);
967     Call->addAttribute(2, Attribute::ZExt);
968
969     BasicBlock *Tail = BI->getSuccessor(0);
970     PHINode *Phi = PHINode::Create(DFS.ShadowTy, 2, "", Tail->begin());
971     Phi->addIncoming(Call, Call->getParent());
972     Phi->addIncoming(V1, Head);
973
974     CCS.Block = Tail;
975     CCS.Shadow = Phi;
976   }
977
978   std::set<Value *> UnionElems;
979   if (V1Elems != ShadowElements.end()) {
980     UnionElems = V1Elems->second;
981   } else {
982     UnionElems.insert(V1);
983   }
984   if (V2Elems != ShadowElements.end()) {
985     UnionElems.insert(V2Elems->second.begin(), V2Elems->second.end());
986   } else {
987     UnionElems.insert(V2);
988   }
989   ShadowElements[CCS.Shadow] = std::move(UnionElems);
990
991   return CCS.Shadow;
992 }
993
994 // A convenience function which folds the shadows of each of the operands
995 // of the provided instruction Inst, inserting the IR before Inst.  Returns
996 // the computed union Value.
997 Value *DFSanFunction::combineOperandShadows(Instruction *Inst) {
998   if (Inst->getNumOperands() == 0)
999     return DFS.ZeroShadow;
1000
1001   Value *Shadow = getShadow(Inst->getOperand(0));
1002   for (unsigned i = 1, n = Inst->getNumOperands(); i != n; ++i) {
1003     Shadow = combineShadows(Shadow, getShadow(Inst->getOperand(i)), Inst);
1004   }
1005   return Shadow;
1006 }
1007
1008 void DFSanVisitor::visitOperandShadowInst(Instruction &I) {
1009   Value *CombinedShadow = DFSF.combineOperandShadows(&I);
1010   DFSF.setShadow(&I, CombinedShadow);
1011 }
1012
1013 // Generates IR to load shadow corresponding to bytes [Addr, Addr+Size), where
1014 // Addr has alignment Align, and take the union of each of those shadows.
1015 Value *DFSanFunction::loadShadow(Value *Addr, uint64_t Size, uint64_t Align,
1016                                  Instruction *Pos) {
1017   if (AllocaInst *AI = dyn_cast<AllocaInst>(Addr)) {
1018     llvm::DenseMap<AllocaInst *, AllocaInst *>::iterator i =
1019         AllocaShadowMap.find(AI);
1020     if (i != AllocaShadowMap.end()) {
1021       IRBuilder<> IRB(Pos);
1022       return IRB.CreateLoad(i->second);
1023     }
1024   }
1025
1026   uint64_t ShadowAlign = Align * DFS.ShadowWidth / 8;
1027   SmallVector<Value *, 2> Objs;
1028   GetUnderlyingObjects(Addr, Objs, DFS.DL);
1029   bool AllConstants = true;
1030   for (SmallVector<Value *, 2>::iterator i = Objs.begin(), e = Objs.end();
1031        i != e; ++i) {
1032     if (isa<Function>(*i) || isa<BlockAddress>(*i))
1033       continue;
1034     if (isa<GlobalVariable>(*i) && cast<GlobalVariable>(*i)->isConstant())
1035       continue;
1036
1037     AllConstants = false;
1038     break;
1039   }
1040   if (AllConstants)
1041     return DFS.ZeroShadow;
1042
1043   Value *ShadowAddr = DFS.getShadowAddress(Addr, Pos);
1044   switch (Size) {
1045   case 0:
1046     return DFS.ZeroShadow;
1047   case 1: {
1048     LoadInst *LI = new LoadInst(ShadowAddr, "", Pos);
1049     LI->setAlignment(ShadowAlign);
1050     return LI;
1051   }
1052   case 2: {
1053     IRBuilder<> IRB(Pos);
1054     Value *ShadowAddr1 =
1055         IRB.CreateGEP(ShadowAddr, ConstantInt::get(DFS.IntptrTy, 1));
1056     return combineShadows(IRB.CreateAlignedLoad(ShadowAddr, ShadowAlign),
1057                           IRB.CreateAlignedLoad(ShadowAddr1, ShadowAlign), Pos);
1058   }
1059   }
1060   if (!AvoidNewBlocks && Size % (64 / DFS.ShadowWidth) == 0) {
1061     // Fast path for the common case where each byte has identical shadow: load
1062     // shadow 64 bits at a time, fall out to a __dfsan_union_load call if any
1063     // shadow is non-equal.
1064     BasicBlock *FallbackBB = BasicBlock::Create(*DFS.Ctx, "", F);
1065     IRBuilder<> FallbackIRB(FallbackBB);
1066     CallInst *FallbackCall = FallbackIRB.CreateCall2(
1067         DFS.DFSanUnionLoadFn, ShadowAddr, ConstantInt::get(DFS.IntptrTy, Size));
1068     FallbackCall->addAttribute(AttributeSet::ReturnIndex, Attribute::ZExt);
1069
1070     // Compare each of the shadows stored in the loaded 64 bits to each other,
1071     // by computing (WideShadow rotl ShadowWidth) == WideShadow.
1072     IRBuilder<> IRB(Pos);
1073     Value *WideAddr =
1074         IRB.CreateBitCast(ShadowAddr, Type::getInt64PtrTy(*DFS.Ctx));
1075     Value *WideShadow = IRB.CreateAlignedLoad(WideAddr, ShadowAlign);
1076     Value *TruncShadow = IRB.CreateTrunc(WideShadow, DFS.ShadowTy);
1077     Value *ShlShadow = IRB.CreateShl(WideShadow, DFS.ShadowWidth);
1078     Value *ShrShadow = IRB.CreateLShr(WideShadow, 64 - DFS.ShadowWidth);
1079     Value *RotShadow = IRB.CreateOr(ShlShadow, ShrShadow);
1080     Value *ShadowsEq = IRB.CreateICmpEQ(WideShadow, RotShadow);
1081
1082     BasicBlock *Head = Pos->getParent();
1083     BasicBlock *Tail = Head->splitBasicBlock(Pos);
1084
1085     if (DomTreeNode *OldNode = DT.getNode(Head)) {
1086       std::vector<DomTreeNode *> Children(OldNode->begin(), OldNode->end());
1087
1088       DomTreeNode *NewNode = DT.addNewBlock(Tail, Head);
1089       for (auto Child : Children)
1090         DT.changeImmediateDominator(Child, NewNode);
1091     }
1092
1093     // In the following code LastBr will refer to the previous basic block's
1094     // conditional branch instruction, whose true successor is fixed up to point
1095     // to the next block during the loop below or to the tail after the final
1096     // iteration.
1097     BranchInst *LastBr = BranchInst::Create(FallbackBB, FallbackBB, ShadowsEq);
1098     ReplaceInstWithInst(Head->getTerminator(), LastBr);
1099     DT.addNewBlock(FallbackBB, Head);
1100
1101     for (uint64_t Ofs = 64 / DFS.ShadowWidth; Ofs != Size;
1102          Ofs += 64 / DFS.ShadowWidth) {
1103       BasicBlock *NextBB = BasicBlock::Create(*DFS.Ctx, "", F);
1104       DT.addNewBlock(NextBB, LastBr->getParent());
1105       IRBuilder<> NextIRB(NextBB);
1106       WideAddr = NextIRB.CreateGEP(WideAddr, ConstantInt::get(DFS.IntptrTy, 1));
1107       Value *NextWideShadow = NextIRB.CreateAlignedLoad(WideAddr, ShadowAlign);
1108       ShadowsEq = NextIRB.CreateICmpEQ(WideShadow, NextWideShadow);
1109       LastBr->setSuccessor(0, NextBB);
1110       LastBr = NextIRB.CreateCondBr(ShadowsEq, FallbackBB, FallbackBB);
1111     }
1112
1113     LastBr->setSuccessor(0, Tail);
1114     FallbackIRB.CreateBr(Tail);
1115     PHINode *Shadow = PHINode::Create(DFS.ShadowTy, 2, "", &Tail->front());
1116     Shadow->addIncoming(FallbackCall, FallbackBB);
1117     Shadow->addIncoming(TruncShadow, LastBr->getParent());
1118     return Shadow;
1119   }
1120
1121   IRBuilder<> IRB(Pos);
1122   CallInst *FallbackCall = IRB.CreateCall2(
1123       DFS.DFSanUnionLoadFn, ShadowAddr, ConstantInt::get(DFS.IntptrTy, Size));
1124   FallbackCall->addAttribute(AttributeSet::ReturnIndex, Attribute::ZExt);
1125   return FallbackCall;
1126 }
1127
1128 void DFSanVisitor::visitLoadInst(LoadInst &LI) {
1129   uint64_t Size = DFSF.DFS.DL->getTypeStoreSize(LI.getType());
1130   if (Size == 0) {
1131     DFSF.setShadow(&LI, DFSF.DFS.ZeroShadow);
1132     return;
1133   }
1134
1135   uint64_t Align;
1136   if (ClPreserveAlignment) {
1137     Align = LI.getAlignment();
1138     if (Align == 0)
1139       Align = DFSF.DFS.DL->getABITypeAlignment(LI.getType());
1140   } else {
1141     Align = 1;
1142   }
1143   IRBuilder<> IRB(&LI);
1144   Value *Shadow = DFSF.loadShadow(LI.getPointerOperand(), Size, Align, &LI);
1145   if (ClCombinePointerLabelsOnLoad) {
1146     Value *PtrShadow = DFSF.getShadow(LI.getPointerOperand());
1147     Shadow = DFSF.combineShadows(Shadow, PtrShadow, &LI);
1148   }
1149   if (Shadow != DFSF.DFS.ZeroShadow)
1150     DFSF.NonZeroChecks.push_back(Shadow);
1151
1152   DFSF.setShadow(&LI, Shadow);
1153 }
1154
1155 void DFSanFunction::storeShadow(Value *Addr, uint64_t Size, uint64_t Align,
1156                                 Value *Shadow, Instruction *Pos) {
1157   if (AllocaInst *AI = dyn_cast<AllocaInst>(Addr)) {
1158     llvm::DenseMap<AllocaInst *, AllocaInst *>::iterator i =
1159         AllocaShadowMap.find(AI);
1160     if (i != AllocaShadowMap.end()) {
1161       IRBuilder<> IRB(Pos);
1162       IRB.CreateStore(Shadow, i->second);
1163       return;
1164     }
1165   }
1166
1167   uint64_t ShadowAlign = Align * DFS.ShadowWidth / 8;
1168   IRBuilder<> IRB(Pos);
1169   Value *ShadowAddr = DFS.getShadowAddress(Addr, Pos);
1170   if (Shadow == DFS.ZeroShadow) {
1171     IntegerType *ShadowTy = IntegerType::get(*DFS.Ctx, Size * DFS.ShadowWidth);
1172     Value *ExtZeroShadow = ConstantInt::get(ShadowTy, 0);
1173     Value *ExtShadowAddr =
1174         IRB.CreateBitCast(ShadowAddr, PointerType::getUnqual(ShadowTy));
1175     IRB.CreateAlignedStore(ExtZeroShadow, ExtShadowAddr, ShadowAlign);
1176     return;
1177   }
1178
1179   const unsigned ShadowVecSize = 128 / DFS.ShadowWidth;
1180   uint64_t Offset = 0;
1181   if (Size >= ShadowVecSize) {
1182     VectorType *ShadowVecTy = VectorType::get(DFS.ShadowTy, ShadowVecSize);
1183     Value *ShadowVec = UndefValue::get(ShadowVecTy);
1184     for (unsigned i = 0; i != ShadowVecSize; ++i) {
1185       ShadowVec = IRB.CreateInsertElement(
1186           ShadowVec, Shadow, ConstantInt::get(Type::getInt32Ty(*DFS.Ctx), i));
1187     }
1188     Value *ShadowVecAddr =
1189         IRB.CreateBitCast(ShadowAddr, PointerType::getUnqual(ShadowVecTy));
1190     do {
1191       Value *CurShadowVecAddr = IRB.CreateConstGEP1_32(ShadowVecAddr, Offset);
1192       IRB.CreateAlignedStore(ShadowVec, CurShadowVecAddr, ShadowAlign);
1193       Size -= ShadowVecSize;
1194       ++Offset;
1195     } while (Size >= ShadowVecSize);
1196     Offset *= ShadowVecSize;
1197   }
1198   while (Size > 0) {
1199     Value *CurShadowAddr = IRB.CreateConstGEP1_32(ShadowAddr, Offset);
1200     IRB.CreateAlignedStore(Shadow, CurShadowAddr, ShadowAlign);
1201     --Size;
1202     ++Offset;
1203   }
1204 }
1205
1206 void DFSanVisitor::visitStoreInst(StoreInst &SI) {
1207   uint64_t Size =
1208       DFSF.DFS.DL->getTypeStoreSize(SI.getValueOperand()->getType());
1209   if (Size == 0)
1210     return;
1211
1212   uint64_t Align;
1213   if (ClPreserveAlignment) {
1214     Align = SI.getAlignment();
1215     if (Align == 0)
1216       Align = DFSF.DFS.DL->getABITypeAlignment(SI.getValueOperand()->getType());
1217   } else {
1218     Align = 1;
1219   }
1220
1221   Value* Shadow = DFSF.getShadow(SI.getValueOperand());
1222   if (ClCombinePointerLabelsOnStore) {
1223     Value *PtrShadow = DFSF.getShadow(SI.getPointerOperand());
1224     Shadow = DFSF.combineShadows(Shadow, PtrShadow, &SI);
1225   }
1226   DFSF.storeShadow(SI.getPointerOperand(), Size, Align, Shadow, &SI);
1227 }
1228
1229 void DFSanVisitor::visitBinaryOperator(BinaryOperator &BO) {
1230   visitOperandShadowInst(BO);
1231 }
1232
1233 void DFSanVisitor::visitCastInst(CastInst &CI) { visitOperandShadowInst(CI); }
1234
1235 void DFSanVisitor::visitCmpInst(CmpInst &CI) { visitOperandShadowInst(CI); }
1236
1237 void DFSanVisitor::visitGetElementPtrInst(GetElementPtrInst &GEPI) {
1238   visitOperandShadowInst(GEPI);
1239 }
1240
1241 void DFSanVisitor::visitExtractElementInst(ExtractElementInst &I) {
1242   visitOperandShadowInst(I);
1243 }
1244
1245 void DFSanVisitor::visitInsertElementInst(InsertElementInst &I) {
1246   visitOperandShadowInst(I);
1247 }
1248
1249 void DFSanVisitor::visitShuffleVectorInst(ShuffleVectorInst &I) {
1250   visitOperandShadowInst(I);
1251 }
1252
1253 void DFSanVisitor::visitExtractValueInst(ExtractValueInst &I) {
1254   visitOperandShadowInst(I);
1255 }
1256
1257 void DFSanVisitor::visitInsertValueInst(InsertValueInst &I) {
1258   visitOperandShadowInst(I);
1259 }
1260
1261 void DFSanVisitor::visitAllocaInst(AllocaInst &I) {
1262   bool AllLoadsStores = true;
1263   for (User *U : I.users()) {
1264     if (isa<LoadInst>(U))
1265       continue;
1266
1267     if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
1268       if (SI->getPointerOperand() == &I)
1269         continue;
1270     }
1271
1272     AllLoadsStores = false;
1273     break;
1274   }
1275   if (AllLoadsStores) {
1276     IRBuilder<> IRB(&I);
1277     DFSF.AllocaShadowMap[&I] = IRB.CreateAlloca(DFSF.DFS.ShadowTy);
1278   }
1279   DFSF.setShadow(&I, DFSF.DFS.ZeroShadow);
1280 }
1281
1282 void DFSanVisitor::visitSelectInst(SelectInst &I) {
1283   Value *CondShadow = DFSF.getShadow(I.getCondition());
1284   Value *TrueShadow = DFSF.getShadow(I.getTrueValue());
1285   Value *FalseShadow = DFSF.getShadow(I.getFalseValue());
1286
1287   if (isa<VectorType>(I.getCondition()->getType())) {
1288     DFSF.setShadow(
1289         &I,
1290         DFSF.combineShadows(
1291             CondShadow, DFSF.combineShadows(TrueShadow, FalseShadow, &I), &I));
1292   } else {
1293     Value *ShadowSel;
1294     if (TrueShadow == FalseShadow) {
1295       ShadowSel = TrueShadow;
1296     } else {
1297       ShadowSel =
1298           SelectInst::Create(I.getCondition(), TrueShadow, FalseShadow, "", &I);
1299     }
1300     DFSF.setShadow(&I, DFSF.combineShadows(CondShadow, ShadowSel, &I));
1301   }
1302 }
1303
1304 void DFSanVisitor::visitMemSetInst(MemSetInst &I) {
1305   IRBuilder<> IRB(&I);
1306   Value *ValShadow = DFSF.getShadow(I.getValue());
1307   IRB.CreateCall3(
1308       DFSF.DFS.DFSanSetLabelFn, ValShadow,
1309       IRB.CreateBitCast(I.getDest(), Type::getInt8PtrTy(*DFSF.DFS.Ctx)),
1310       IRB.CreateZExtOrTrunc(I.getLength(), DFSF.DFS.IntptrTy));
1311 }
1312
1313 void DFSanVisitor::visitMemTransferInst(MemTransferInst &I) {
1314   IRBuilder<> IRB(&I);
1315   Value *DestShadow = DFSF.DFS.getShadowAddress(I.getDest(), &I);
1316   Value *SrcShadow = DFSF.DFS.getShadowAddress(I.getSource(), &I);
1317   Value *LenShadow = IRB.CreateMul(
1318       I.getLength(),
1319       ConstantInt::get(I.getLength()->getType(), DFSF.DFS.ShadowWidth / 8));
1320   Value *AlignShadow;
1321   if (ClPreserveAlignment) {
1322     AlignShadow = IRB.CreateMul(I.getAlignmentCst(),
1323                                 ConstantInt::get(I.getAlignmentCst()->getType(),
1324                                                  DFSF.DFS.ShadowWidth / 8));
1325   } else {
1326     AlignShadow = ConstantInt::get(I.getAlignmentCst()->getType(),
1327                                    DFSF.DFS.ShadowWidth / 8);
1328   }
1329   Type *Int8Ptr = Type::getInt8PtrTy(*DFSF.DFS.Ctx);
1330   DestShadow = IRB.CreateBitCast(DestShadow, Int8Ptr);
1331   SrcShadow = IRB.CreateBitCast(SrcShadow, Int8Ptr);
1332   IRB.CreateCall5(I.getCalledValue(), DestShadow, SrcShadow, LenShadow,
1333                   AlignShadow, I.getVolatileCst());
1334 }
1335
1336 void DFSanVisitor::visitReturnInst(ReturnInst &RI) {
1337   if (!DFSF.IsNativeABI && RI.getReturnValue()) {
1338     switch (DFSF.IA) {
1339     case DataFlowSanitizer::IA_TLS: {
1340       Value *S = DFSF.getShadow(RI.getReturnValue());
1341       IRBuilder<> IRB(&RI);
1342       IRB.CreateStore(S, DFSF.getRetvalTLS());
1343       break;
1344     }
1345     case DataFlowSanitizer::IA_Args: {
1346       IRBuilder<> IRB(&RI);
1347       Type *RT = DFSF.F->getFunctionType()->getReturnType();
1348       Value *InsVal =
1349           IRB.CreateInsertValue(UndefValue::get(RT), RI.getReturnValue(), 0);
1350       Value *InsShadow =
1351           IRB.CreateInsertValue(InsVal, DFSF.getShadow(RI.getReturnValue()), 1);
1352       RI.setOperand(0, InsShadow);
1353       break;
1354     }
1355     }
1356   }
1357 }
1358
1359 void DFSanVisitor::visitCallSite(CallSite CS) {
1360   Function *F = CS.getCalledFunction();
1361   if ((F && F->isIntrinsic()) || isa<InlineAsm>(CS.getCalledValue())) {
1362     visitOperandShadowInst(*CS.getInstruction());
1363     return;
1364   }
1365
1366   assert(!(cast<FunctionType>(
1367       CS.getCalledValue()->getType()->getPointerElementType())->isVarArg() &&
1368            dyn_cast<InvokeInst>(CS.getInstruction())));
1369
1370   IRBuilder<> IRB(CS.getInstruction());
1371
1372   DenseMap<Value *, Function *>::iterator i =
1373       DFSF.DFS.UnwrappedFnMap.find(CS.getCalledValue());
1374   if (i != DFSF.DFS.UnwrappedFnMap.end()) {
1375     Function *F = i->second;
1376     switch (DFSF.DFS.getWrapperKind(F)) {
1377     case DataFlowSanitizer::WK_Warning: {
1378       CS.setCalledFunction(F);
1379       IRB.CreateCall(DFSF.DFS.DFSanUnimplementedFn,
1380                      IRB.CreateGlobalStringPtr(F->getName()));
1381       DFSF.setShadow(CS.getInstruction(), DFSF.DFS.ZeroShadow);
1382       return;
1383     }
1384     case DataFlowSanitizer::WK_Discard: {
1385       CS.setCalledFunction(F);
1386       DFSF.setShadow(CS.getInstruction(), DFSF.DFS.ZeroShadow);
1387       return;
1388     }
1389     case DataFlowSanitizer::WK_Functional: {
1390       CS.setCalledFunction(F);
1391       visitOperandShadowInst(*CS.getInstruction());
1392       return;
1393     }
1394     case DataFlowSanitizer::WK_Custom: {
1395       // Don't try to handle invokes of custom functions, it's too complicated.
1396       // Instead, invoke the dfsw$ wrapper, which will in turn call the __dfsw_
1397       // wrapper.
1398       if (CallInst *CI = dyn_cast<CallInst>(CS.getInstruction())) {
1399         FunctionType *FT = F->getFunctionType();
1400         FunctionType *CustomFT = DFSF.DFS.getCustomFunctionType(FT);
1401         std::string CustomFName = "__dfsw_";
1402         CustomFName += F->getName();
1403         Constant *CustomF =
1404             DFSF.DFS.Mod->getOrInsertFunction(CustomFName, CustomFT);
1405         if (Function *CustomFn = dyn_cast<Function>(CustomF)) {
1406           CustomFn->copyAttributesFrom(F);
1407
1408           // Custom functions returning non-void will write to the return label.
1409           if (!FT->getReturnType()->isVoidTy()) {
1410             CustomFn->removeAttributes(AttributeSet::FunctionIndex,
1411                                        DFSF.DFS.ReadOnlyNoneAttrs);
1412           }
1413         }
1414
1415         std::vector<Value *> Args;
1416
1417         CallSite::arg_iterator i = CS.arg_begin();
1418         for (unsigned n = FT->getNumParams(); n != 0; ++i, --n) {
1419           Type *T = (*i)->getType();
1420           FunctionType *ParamFT;
1421           if (isa<PointerType>(T) &&
1422               (ParamFT = dyn_cast<FunctionType>(
1423                    cast<PointerType>(T)->getElementType()))) {
1424             std::string TName = "dfst";
1425             TName += utostr(FT->getNumParams() - n);
1426             TName += "$";
1427             TName += F->getName();
1428             Constant *T = DFSF.DFS.getOrBuildTrampolineFunction(ParamFT, TName);
1429             Args.push_back(T);
1430             Args.push_back(
1431                 IRB.CreateBitCast(*i, Type::getInt8PtrTy(*DFSF.DFS.Ctx)));
1432           } else {
1433             Args.push_back(*i);
1434           }
1435         }
1436
1437         i = CS.arg_begin();
1438         for (unsigned n = FT->getNumParams(); n != 0; ++i, --n)
1439           Args.push_back(DFSF.getShadow(*i));
1440
1441         if (FT->isVarArg()) {
1442           auto LabelVAAlloca =
1443               new AllocaInst(ArrayType::get(DFSF.DFS.ShadowTy,
1444                                             CS.arg_size() - FT->getNumParams()),
1445                              "labelva", DFSF.F->getEntryBlock().begin());
1446
1447           for (unsigned n = 0; i != CS.arg_end(); ++i, ++n) {
1448             auto LabelVAPtr = IRB.CreateStructGEP(LabelVAAlloca, n);
1449             IRB.CreateStore(DFSF.getShadow(*i), LabelVAPtr);
1450           }
1451
1452           Args.push_back(IRB.CreateStructGEP(LabelVAAlloca, 0));
1453         }
1454
1455         if (!FT->getReturnType()->isVoidTy()) {
1456           if (!DFSF.LabelReturnAlloca) {
1457             DFSF.LabelReturnAlloca =
1458                 new AllocaInst(DFSF.DFS.ShadowTy, "labelreturn",
1459                                DFSF.F->getEntryBlock().begin());
1460           }
1461           Args.push_back(DFSF.LabelReturnAlloca);
1462         }
1463
1464         for (i = CS.arg_begin() + FT->getNumParams(); i != CS.arg_end(); ++i)
1465           Args.push_back(*i);
1466
1467         CallInst *CustomCI = IRB.CreateCall(CustomF, Args);
1468         CustomCI->setCallingConv(CI->getCallingConv());
1469         CustomCI->setAttributes(CI->getAttributes());
1470
1471         if (!FT->getReturnType()->isVoidTy()) {
1472           LoadInst *LabelLoad = IRB.CreateLoad(DFSF.LabelReturnAlloca);
1473           DFSF.setShadow(CustomCI, LabelLoad);
1474         }
1475
1476         CI->replaceAllUsesWith(CustomCI);
1477         CI->eraseFromParent();
1478         return;
1479       }
1480       break;
1481     }
1482     }
1483   }
1484
1485   FunctionType *FT = cast<FunctionType>(
1486       CS.getCalledValue()->getType()->getPointerElementType());
1487   if (DFSF.DFS.getInstrumentedABI() == DataFlowSanitizer::IA_TLS) {
1488     for (unsigned i = 0, n = FT->getNumParams(); i != n; ++i) {
1489       IRB.CreateStore(DFSF.getShadow(CS.getArgument(i)),
1490                       DFSF.getArgTLS(i, CS.getInstruction()));
1491     }
1492   }
1493
1494   Instruction *Next = nullptr;
1495   if (!CS.getType()->isVoidTy()) {
1496     if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
1497       if (II->getNormalDest()->getSinglePredecessor()) {
1498         Next = II->getNormalDest()->begin();
1499       } else {
1500         BasicBlock *NewBB =
1501             SplitEdge(II->getParent(), II->getNormalDest(), &DFSF.DFS);
1502         Next = NewBB->begin();
1503       }
1504     } else {
1505       Next = CS->getNextNode();
1506     }
1507
1508     if (DFSF.DFS.getInstrumentedABI() == DataFlowSanitizer::IA_TLS) {
1509       IRBuilder<> NextIRB(Next);
1510       LoadInst *LI = NextIRB.CreateLoad(DFSF.getRetvalTLS());
1511       DFSF.SkipInsts.insert(LI);
1512       DFSF.setShadow(CS.getInstruction(), LI);
1513       DFSF.NonZeroChecks.push_back(LI);
1514     }
1515   }
1516
1517   // Do all instrumentation for IA_Args down here to defer tampering with the
1518   // CFG in a way that SplitEdge may be able to detect.
1519   if (DFSF.DFS.getInstrumentedABI() == DataFlowSanitizer::IA_Args) {
1520     FunctionType *NewFT = DFSF.DFS.getArgsFunctionType(FT);
1521     Value *Func =
1522         IRB.CreateBitCast(CS.getCalledValue(), PointerType::getUnqual(NewFT));
1523     std::vector<Value *> Args;
1524
1525     CallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
1526     for (unsigned n = FT->getNumParams(); n != 0; ++i, --n)
1527       Args.push_back(*i);
1528
1529     i = CS.arg_begin();
1530     for (unsigned n = FT->getNumParams(); n != 0; ++i, --n)
1531       Args.push_back(DFSF.getShadow(*i));
1532
1533     if (FT->isVarArg()) {
1534       unsigned VarArgSize = CS.arg_size() - FT->getNumParams();
1535       ArrayType *VarArgArrayTy = ArrayType::get(DFSF.DFS.ShadowTy, VarArgSize);
1536       AllocaInst *VarArgShadow =
1537           new AllocaInst(VarArgArrayTy, "", DFSF.F->getEntryBlock().begin());
1538       Args.push_back(IRB.CreateConstGEP2_32(VarArgShadow, 0, 0));
1539       for (unsigned n = 0; i != e; ++i, ++n) {
1540         IRB.CreateStore(DFSF.getShadow(*i),
1541                         IRB.CreateConstGEP2_32(VarArgShadow, 0, n));
1542         Args.push_back(*i);
1543       }
1544     }
1545
1546     CallSite NewCS;
1547     if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
1548       NewCS = IRB.CreateInvoke(Func, II->getNormalDest(), II->getUnwindDest(),
1549                                Args);
1550     } else {
1551       NewCS = IRB.CreateCall(Func, Args);
1552     }
1553     NewCS.setCallingConv(CS.getCallingConv());
1554     NewCS.setAttributes(CS.getAttributes().removeAttributes(
1555         *DFSF.DFS.Ctx, AttributeSet::ReturnIndex,
1556         AttributeFuncs::typeIncompatible(NewCS.getInstruction()->getType(),
1557                                          AttributeSet::ReturnIndex)));
1558
1559     if (Next) {
1560       ExtractValueInst *ExVal =
1561           ExtractValueInst::Create(NewCS.getInstruction(), 0, "", Next);
1562       DFSF.SkipInsts.insert(ExVal);
1563       ExtractValueInst *ExShadow =
1564           ExtractValueInst::Create(NewCS.getInstruction(), 1, "", Next);
1565       DFSF.SkipInsts.insert(ExShadow);
1566       DFSF.setShadow(ExVal, ExShadow);
1567       DFSF.NonZeroChecks.push_back(ExShadow);
1568
1569       CS.getInstruction()->replaceAllUsesWith(ExVal);
1570     }
1571
1572     CS.getInstruction()->eraseFromParent();
1573   }
1574 }
1575
1576 void DFSanVisitor::visitPHINode(PHINode &PN) {
1577   PHINode *ShadowPN =
1578       PHINode::Create(DFSF.DFS.ShadowTy, PN.getNumIncomingValues(), "", &PN);
1579
1580   // Give the shadow phi node valid predecessors to fool SplitEdge into working.
1581   Value *UndefShadow = UndefValue::get(DFSF.DFS.ShadowTy);
1582   for (PHINode::block_iterator i = PN.block_begin(), e = PN.block_end(); i != e;
1583        ++i) {
1584     ShadowPN->addIncoming(UndefShadow, *i);
1585   }
1586
1587   DFSF.PHIFixups.push_back(std::make_pair(&PN, ShadowPN));
1588   DFSF.setShadow(&PN, ShadowPN);
1589 }