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