6adf0d24f8e5673d8bbd6f4e3345b628a1573cfa
[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   DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
426   if (!DLP)
427     report_fatal_error("data layout missing");
428   DL = &DLP->getDataLayout();
429
430   Mod = &M;
431   Ctx = &M.getContext();
432   ShadowTy = IntegerType::get(*Ctx, ShadowWidth);
433   ShadowPtrTy = PointerType::getUnqual(ShadowTy);
434   IntptrTy = DL->getIntPtrType(*Ctx);
435   ZeroShadow = ConstantInt::getSigned(ShadowTy, 0);
436   ShadowPtrMul = ConstantInt::getSigned(IntptrTy, ShadowWidth / 8);
437   if (IsX86_64)
438     ShadowPtrMask = ConstantInt::getSigned(IntptrTy, ~0x700000000000LL);
439   else if (IsMIPS64)
440     ShadowPtrMask = ConstantInt::getSigned(IntptrTy, ~0xF000000000LL);
441   else
442     report_fatal_error("unsupported triple");
443
444   Type *DFSanUnionArgs[2] = { ShadowTy, ShadowTy };
445   DFSanUnionFnTy =
446       FunctionType::get(ShadowTy, DFSanUnionArgs, /*isVarArg=*/ false);
447   Type *DFSanUnionLoadArgs[2] = { ShadowPtrTy, IntptrTy };
448   DFSanUnionLoadFnTy =
449       FunctionType::get(ShadowTy, DFSanUnionLoadArgs, /*isVarArg=*/ false);
450   DFSanUnimplementedFnTy = FunctionType::get(
451       Type::getVoidTy(*Ctx), Type::getInt8PtrTy(*Ctx), /*isVarArg=*/false);
452   Type *DFSanSetLabelArgs[3] = { ShadowTy, Type::getInt8PtrTy(*Ctx), IntptrTy };
453   DFSanSetLabelFnTy = FunctionType::get(Type::getVoidTy(*Ctx),
454                                         DFSanSetLabelArgs, /*isVarArg=*/false);
455   DFSanNonzeroLabelFnTy = FunctionType::get(
456       Type::getVoidTy(*Ctx), None, /*isVarArg=*/false);
457   DFSanVarargWrapperFnTy = FunctionType::get(
458       Type::getVoidTy(*Ctx), Type::getInt8PtrTy(*Ctx), /*isVarArg=*/false);
459
460   if (GetArgTLSPtr) {
461     Type *ArgTLSTy = ArrayType::get(ShadowTy, 64);
462     ArgTLS = nullptr;
463     GetArgTLS = ConstantExpr::getIntToPtr(
464         ConstantInt::get(IntptrTy, uintptr_t(GetArgTLSPtr)),
465         PointerType::getUnqual(
466             FunctionType::get(PointerType::getUnqual(ArgTLSTy),
467                               (Type *)nullptr)));
468   }
469   if (GetRetvalTLSPtr) {
470     RetvalTLS = nullptr;
471     GetRetvalTLS = ConstantExpr::getIntToPtr(
472         ConstantInt::get(IntptrTy, uintptr_t(GetRetvalTLSPtr)),
473         PointerType::getUnqual(
474             FunctionType::get(PointerType::getUnqual(ShadowTy),
475                               (Type *)nullptr)));
476   }
477
478   ColdCallWeights = MDBuilder(*Ctx).createBranchWeights(1, 1000);
479   return true;
480 }
481
482 bool DataFlowSanitizer::isInstrumented(const Function *F) {
483   return !ABIList.isIn(*F, "uninstrumented");
484 }
485
486 bool DataFlowSanitizer::isInstrumented(const GlobalAlias *GA) {
487   return !ABIList.isIn(*GA, "uninstrumented");
488 }
489
490 DataFlowSanitizer::InstrumentedABI DataFlowSanitizer::getInstrumentedABI() {
491   return ClArgsABI ? IA_Args : IA_TLS;
492 }
493
494 DataFlowSanitizer::WrapperKind DataFlowSanitizer::getWrapperKind(Function *F) {
495   if (ABIList.isIn(*F, "functional"))
496     return WK_Functional;
497   if (ABIList.isIn(*F, "discard"))
498     return WK_Discard;
499   if (ABIList.isIn(*F, "custom"))
500     return WK_Custom;
501
502   return WK_Warning;
503 }
504
505 void DataFlowSanitizer::addGlobalNamePrefix(GlobalValue *GV) {
506   std::string GVName = GV->getName(), Prefix = "dfs$";
507   GV->setName(Prefix + GVName);
508
509   // Try to change the name of the function in module inline asm.  We only do
510   // this for specific asm directives, currently only ".symver", to try to avoid
511   // corrupting asm which happens to contain the symbol name as a substring.
512   // Note that the substitution for .symver assumes that the versioned symbol
513   // also has an instrumented name.
514   std::string Asm = GV->getParent()->getModuleInlineAsm();
515   std::string SearchStr = ".symver " + GVName + ",";
516   size_t Pos = Asm.find(SearchStr);
517   if (Pos != std::string::npos) {
518     Asm.replace(Pos, SearchStr.size(),
519                 ".symver " + Prefix + GVName + "," + Prefix);
520     GV->getParent()->setModuleInlineAsm(Asm);
521   }
522 }
523
524 Function *
525 DataFlowSanitizer::buildWrapperFunction(Function *F, StringRef NewFName,
526                                         GlobalValue::LinkageTypes NewFLink,
527                                         FunctionType *NewFT) {
528   FunctionType *FT = F->getFunctionType();
529   Function *NewF = Function::Create(NewFT, NewFLink, NewFName,
530                                     F->getParent());
531   NewF->copyAttributesFrom(F);
532   NewF->removeAttributes(
533       AttributeSet::ReturnIndex,
534       AttributeFuncs::typeIncompatible(NewFT->getReturnType(),
535                                        AttributeSet::ReturnIndex));
536
537   BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", NewF);
538   if (F->isVarArg()) {
539     NewF->removeAttributes(
540         AttributeSet::FunctionIndex,
541         AttributeSet().addAttribute(*Ctx, AttributeSet::FunctionIndex,
542                                     "split-stack"));
543     CallInst::Create(DFSanVarargWrapperFn,
544                      IRBuilder<>(BB).CreateGlobalStringPtr(F->getName()), "",
545                      BB);
546     new UnreachableInst(*Ctx, BB);
547   } else {
548     std::vector<Value *> Args;
549     unsigned n = FT->getNumParams();
550     for (Function::arg_iterator ai = NewF->arg_begin(); n != 0; ++ai, --n)
551       Args.push_back(&*ai);
552     CallInst *CI = CallInst::Create(F, Args, "", BB);
553     if (FT->getReturnType()->isVoidTy())
554       ReturnInst::Create(*Ctx, BB);
555     else
556       ReturnInst::Create(*Ctx, CI, BB);
557   }
558
559   return NewF;
560 }
561
562 Constant *DataFlowSanitizer::getOrBuildTrampolineFunction(FunctionType *FT,
563                                                           StringRef FName) {
564   FunctionType *FTT = getTrampolineFunctionType(FT);
565   Constant *C = Mod->getOrInsertFunction(FName, FTT);
566   Function *F = dyn_cast<Function>(C);
567   if (F && F->isDeclaration()) {
568     F->setLinkage(GlobalValue::LinkOnceODRLinkage);
569     BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", F);
570     std::vector<Value *> Args;
571     Function::arg_iterator AI = F->arg_begin(); ++AI;
572     for (unsigned N = FT->getNumParams(); N != 0; ++AI, --N)
573       Args.push_back(&*AI);
574     CallInst *CI =
575         CallInst::Create(&F->getArgumentList().front(), Args, "", BB);
576     ReturnInst *RI;
577     if (FT->getReturnType()->isVoidTy())
578       RI = ReturnInst::Create(*Ctx, BB);
579     else
580       RI = ReturnInst::Create(*Ctx, CI, BB);
581
582     DFSanFunction DFSF(*this, F, /*IsNativeABI=*/true);
583     Function::arg_iterator ValAI = F->arg_begin(), ShadowAI = AI; ++ValAI;
584     for (unsigned N = FT->getNumParams(); N != 0; ++ValAI, ++ShadowAI, --N)
585       DFSF.ValShadowMap[ValAI] = ShadowAI;
586     DFSanVisitor(DFSF).visitCallInst(*CI);
587     if (!FT->getReturnType()->isVoidTy())
588       new StoreInst(DFSF.getShadow(RI->getReturnValue()),
589                     &F->getArgumentList().back(), RI);
590   }
591
592   return C;
593 }
594
595 bool DataFlowSanitizer::runOnModule(Module &M) {
596   if (!DL)
597     return false;
598
599   if (ABIList.isIn(M, "skip"))
600     return false;
601
602   FunctionDIs = makeSubprogramMap(M);
603
604   if (!GetArgTLSPtr) {
605     Type *ArgTLSTy = ArrayType::get(ShadowTy, 64);
606     ArgTLS = Mod->getOrInsertGlobal("__dfsan_arg_tls", ArgTLSTy);
607     if (GlobalVariable *G = dyn_cast<GlobalVariable>(ArgTLS))
608       G->setThreadLocalMode(GlobalVariable::InitialExecTLSModel);
609   }
610   if (!GetRetvalTLSPtr) {
611     RetvalTLS = Mod->getOrInsertGlobal("__dfsan_retval_tls", ShadowTy);
612     if (GlobalVariable *G = dyn_cast<GlobalVariable>(RetvalTLS))
613       G->setThreadLocalMode(GlobalVariable::InitialExecTLSModel);
614   }
615
616   DFSanUnionFn = Mod->getOrInsertFunction("__dfsan_union", DFSanUnionFnTy);
617   if (Function *F = dyn_cast<Function>(DFSanUnionFn)) {
618     F->addAttribute(AttributeSet::FunctionIndex, Attribute::NoUnwind);
619     F->addAttribute(AttributeSet::FunctionIndex, Attribute::ReadNone);
620     F->addAttribute(AttributeSet::ReturnIndex, Attribute::ZExt);
621     F->addAttribute(1, Attribute::ZExt);
622     F->addAttribute(2, Attribute::ZExt);
623   }
624   DFSanCheckedUnionFn = Mod->getOrInsertFunction("dfsan_union", DFSanUnionFnTy);
625   if (Function *F = dyn_cast<Function>(DFSanCheckedUnionFn)) {
626     F->addAttribute(AttributeSet::FunctionIndex, Attribute::NoUnwind);
627     F->addAttribute(AttributeSet::FunctionIndex, Attribute::ReadNone);
628     F->addAttribute(AttributeSet::ReturnIndex, Attribute::ZExt);
629     F->addAttribute(1, Attribute::ZExt);
630     F->addAttribute(2, Attribute::ZExt);
631   }
632   DFSanUnionLoadFn =
633       Mod->getOrInsertFunction("__dfsan_union_load", DFSanUnionLoadFnTy);
634   if (Function *F = dyn_cast<Function>(DFSanUnionLoadFn)) {
635     F->addAttribute(AttributeSet::FunctionIndex, Attribute::NoUnwind);
636     F->addAttribute(AttributeSet::FunctionIndex, Attribute::ReadOnly);
637     F->addAttribute(AttributeSet::ReturnIndex, Attribute::ZExt);
638   }
639   DFSanUnimplementedFn =
640       Mod->getOrInsertFunction("__dfsan_unimplemented", DFSanUnimplementedFnTy);
641   DFSanSetLabelFn =
642       Mod->getOrInsertFunction("__dfsan_set_label", DFSanSetLabelFnTy);
643   if (Function *F = dyn_cast<Function>(DFSanSetLabelFn)) {
644     F->addAttribute(1, Attribute::ZExt);
645   }
646   DFSanNonzeroLabelFn =
647       Mod->getOrInsertFunction("__dfsan_nonzero_label", DFSanNonzeroLabelFnTy);
648   DFSanVarargWrapperFn = Mod->getOrInsertFunction("__dfsan_vararg_wrapper",
649                                                   DFSanVarargWrapperFnTy);
650
651   std::vector<Function *> FnsToInstrument;
652   llvm::SmallPtrSet<Function *, 2> FnsWithNativeABI;
653   for (Module::iterator i = M.begin(), e = M.end(); i != e; ++i) {
654     if (!i->isIntrinsic() &&
655         i != DFSanUnionFn &&
656         i != DFSanCheckedUnionFn &&
657         i != DFSanUnionLoadFn &&
658         i != DFSanUnimplementedFn &&
659         i != DFSanSetLabelFn &&
660         i != DFSanNonzeroLabelFn &&
661         i != DFSanVarargWrapperFn)
662       FnsToInstrument.push_back(&*i);
663   }
664
665   // Give function aliases prefixes when necessary, and build wrappers where the
666   // instrumentedness is inconsistent.
667   for (Module::alias_iterator i = M.alias_begin(), e = M.alias_end(); i != e;) {
668     GlobalAlias *GA = &*i;
669     ++i;
670     // Don't stop on weak.  We assume people aren't playing games with the
671     // instrumentedness of overridden weak aliases.
672     if (auto F = dyn_cast<Function>(GA->getBaseObject())) {
673       bool GAInst = isInstrumented(GA), FInst = isInstrumented(F);
674       if (GAInst && FInst) {
675         addGlobalNamePrefix(GA);
676       } else if (GAInst != FInst) {
677         // Non-instrumented alias of an instrumented function, or vice versa.
678         // Replace the alias with a native-ABI wrapper of the aliasee.  The pass
679         // below will take care of instrumenting it.
680         Function *NewF =
681             buildWrapperFunction(F, "", GA->getLinkage(), F->getFunctionType());
682         GA->replaceAllUsesWith(ConstantExpr::getBitCast(NewF, GA->getType()));
683         NewF->takeName(GA);
684         GA->eraseFromParent();
685         FnsToInstrument.push_back(NewF);
686       }
687     }
688   }
689
690   AttrBuilder B;
691   B.addAttribute(Attribute::ReadOnly).addAttribute(Attribute::ReadNone);
692   ReadOnlyNoneAttrs = AttributeSet::get(*Ctx, AttributeSet::FunctionIndex, B);
693
694   // First, change the ABI of every function in the module.  ABI-listed
695   // functions keep their original ABI and get a wrapper function.
696   for (std::vector<Function *>::iterator i = FnsToInstrument.begin(),
697                                          e = FnsToInstrument.end();
698        i != e; ++i) {
699     Function &F = **i;
700     FunctionType *FT = F.getFunctionType();
701
702     bool IsZeroArgsVoidRet = (FT->getNumParams() == 0 && !FT->isVarArg() &&
703                               FT->getReturnType()->isVoidTy());
704
705     if (isInstrumented(&F)) {
706       // Instrumented functions get a 'dfs$' prefix.  This allows us to more
707       // easily identify cases of mismatching ABIs.
708       if (getInstrumentedABI() == IA_Args && !IsZeroArgsVoidRet) {
709         FunctionType *NewFT = getArgsFunctionType(FT);
710         Function *NewF = Function::Create(NewFT, F.getLinkage(), "", &M);
711         NewF->copyAttributesFrom(&F);
712         NewF->removeAttributes(
713             AttributeSet::ReturnIndex,
714             AttributeFuncs::typeIncompatible(NewFT->getReturnType(),
715                                              AttributeSet::ReturnIndex));
716         for (Function::arg_iterator FArg = F.arg_begin(),
717                                     NewFArg = NewF->arg_begin(),
718                                     FArgEnd = F.arg_end();
719              FArg != FArgEnd; ++FArg, ++NewFArg) {
720           FArg->replaceAllUsesWith(NewFArg);
721         }
722         NewF->getBasicBlockList().splice(NewF->begin(), F.getBasicBlockList());
723
724         for (Function::user_iterator UI = F.user_begin(), UE = F.user_end();
725              UI != UE;) {
726           BlockAddress *BA = dyn_cast<BlockAddress>(*UI);
727           ++UI;
728           if (BA) {
729             BA->replaceAllUsesWith(
730                 BlockAddress::get(NewF, BA->getBasicBlock()));
731             delete BA;
732           }
733         }
734         F.replaceAllUsesWith(
735             ConstantExpr::getBitCast(NewF, PointerType::getUnqual(FT)));
736         NewF->takeName(&F);
737         F.eraseFromParent();
738         *i = NewF;
739         addGlobalNamePrefix(NewF);
740       } else {
741         addGlobalNamePrefix(&F);
742       }
743     } else if (!IsZeroArgsVoidRet || getWrapperKind(&F) == WK_Custom) {
744       // Build a wrapper function for F.  The wrapper simply calls F, and is
745       // added to FnsToInstrument so that any instrumentation according to its
746       // WrapperKind is done in the second pass below.
747       FunctionType *NewFT = getInstrumentedABI() == IA_Args
748                                 ? getArgsFunctionType(FT)
749                                 : FT;
750       Function *NewF = buildWrapperFunction(
751           &F, std::string("dfsw$") + std::string(F.getName()),
752           GlobalValue::LinkOnceODRLinkage, NewFT);
753       if (getInstrumentedABI() == IA_TLS)
754         NewF->removeAttributes(AttributeSet::FunctionIndex, ReadOnlyNoneAttrs);
755
756       Value *WrappedFnCst =
757           ConstantExpr::getBitCast(NewF, PointerType::getUnqual(FT));
758       F.replaceAllUsesWith(WrappedFnCst);
759
760       // Patch the pointer to LLVM function in debug info descriptor.
761       auto DI = FunctionDIs.find(&F);
762       if (DI != FunctionDIs.end())
763         DI->second.replaceFunction(&F);
764
765       UnwrappedFnMap[WrappedFnCst] = &F;
766       *i = NewF;
767
768       if (!F.isDeclaration()) {
769         // This function is probably defining an interposition of an
770         // uninstrumented function and hence needs to keep the original ABI.
771         // But any functions it may call need to use the instrumented ABI, so
772         // we instrument it in a mode which preserves the original ABI.
773         FnsWithNativeABI.insert(&F);
774
775         // This code needs to rebuild the iterators, as they may be invalidated
776         // by the push_back, taking care that the new range does not include
777         // any functions added by this code.
778         size_t N = i - FnsToInstrument.begin(),
779                Count = e - FnsToInstrument.begin();
780         FnsToInstrument.push_back(&F);
781         i = FnsToInstrument.begin() + N;
782         e = FnsToInstrument.begin() + Count;
783       }
784                // Hopefully, nobody will try to indirectly call a vararg
785                // function... yet.
786     } else if (FT->isVarArg()) {
787       UnwrappedFnMap[&F] = &F;
788       *i = nullptr;
789     }
790   }
791
792   for (std::vector<Function *>::iterator i = FnsToInstrument.begin(),
793                                          e = FnsToInstrument.end();
794        i != e; ++i) {
795     if (!*i || (*i)->isDeclaration())
796       continue;
797
798     removeUnreachableBlocks(**i);
799
800     DFSanFunction DFSF(*this, *i, FnsWithNativeABI.count(*i));
801
802     // DFSanVisitor may create new basic blocks, which confuses df_iterator.
803     // Build a copy of the list before iterating over it.
804     llvm::SmallVector<BasicBlock *, 4> BBList(
805         depth_first(&(*i)->getEntryBlock()));
806
807     for (llvm::SmallVector<BasicBlock *, 4>::iterator i = BBList.begin(),
808                                                       e = BBList.end();
809          i != e; ++i) {
810       Instruction *Inst = &(*i)->front();
811       while (1) {
812         // DFSanVisitor may split the current basic block, changing the current
813         // instruction's next pointer and moving the next instruction to the
814         // tail block from which we should continue.
815         Instruction *Next = Inst->getNextNode();
816         // DFSanVisitor may delete Inst, so keep track of whether it was a
817         // terminator.
818         bool IsTerminator = isa<TerminatorInst>(Inst);
819         if (!DFSF.SkipInsts.count(Inst))
820           DFSanVisitor(DFSF).visit(Inst);
821         if (IsTerminator)
822           break;
823         Inst = Next;
824       }
825     }
826
827     // We will not necessarily be able to compute the shadow for every phi node
828     // until we have visited every block.  Therefore, the code that handles phi
829     // nodes adds them to the PHIFixups list so that they can be properly
830     // handled here.
831     for (std::vector<std::pair<PHINode *, PHINode *> >::iterator
832              i = DFSF.PHIFixups.begin(),
833              e = DFSF.PHIFixups.end();
834          i != e; ++i) {
835       for (unsigned val = 0, n = i->first->getNumIncomingValues(); val != n;
836            ++val) {
837         i->second->setIncomingValue(
838             val, DFSF.getShadow(i->first->getIncomingValue(val)));
839       }
840     }
841
842     // -dfsan-debug-nonzero-labels will split the CFG in all kinds of crazy
843     // places (i.e. instructions in basic blocks we haven't even begun visiting
844     // yet).  To make our life easier, do this work in a pass after the main
845     // instrumentation.
846     if (ClDebugNonzeroLabels) {
847       for (Value *V : DFSF.NonZeroChecks) {
848         Instruction *Pos;
849         if (Instruction *I = dyn_cast<Instruction>(V))
850           Pos = I->getNextNode();
851         else
852           Pos = DFSF.F->getEntryBlock().begin();
853         while (isa<PHINode>(Pos) || isa<AllocaInst>(Pos))
854           Pos = Pos->getNextNode();
855         IRBuilder<> IRB(Pos);
856         Value *Ne = IRB.CreateICmpNE(V, DFSF.DFS.ZeroShadow);
857         BranchInst *BI = cast<BranchInst>(SplitBlockAndInsertIfThen(
858             Ne, Pos, /*Unreachable=*/false, ColdCallWeights));
859         IRBuilder<> ThenIRB(BI);
860         ThenIRB.CreateCall(DFSF.DFS.DFSanNonzeroLabelFn);
861       }
862     }
863   }
864
865   return false;
866 }
867
868 Value *DFSanFunction::getArgTLSPtr() {
869   if (ArgTLSPtr)
870     return ArgTLSPtr;
871   if (DFS.ArgTLS)
872     return ArgTLSPtr = DFS.ArgTLS;
873
874   IRBuilder<> IRB(F->getEntryBlock().begin());
875   return ArgTLSPtr = IRB.CreateCall(DFS.GetArgTLS);
876 }
877
878 Value *DFSanFunction::getRetvalTLS() {
879   if (RetvalTLSPtr)
880     return RetvalTLSPtr;
881   if (DFS.RetvalTLS)
882     return RetvalTLSPtr = DFS.RetvalTLS;
883
884   IRBuilder<> IRB(F->getEntryBlock().begin());
885   return RetvalTLSPtr = IRB.CreateCall(DFS.GetRetvalTLS);
886 }
887
888 Value *DFSanFunction::getArgTLS(unsigned Idx, Instruction *Pos) {
889   IRBuilder<> IRB(Pos);
890   return IRB.CreateConstGEP2_64(getArgTLSPtr(), 0, Idx);
891 }
892
893 Value *DFSanFunction::getShadow(Value *V) {
894   if (!isa<Argument>(V) && !isa<Instruction>(V))
895     return DFS.ZeroShadow;
896   Value *&Shadow = ValShadowMap[V];
897   if (!Shadow) {
898     if (Argument *A = dyn_cast<Argument>(V)) {
899       if (IsNativeABI)
900         return DFS.ZeroShadow;
901       switch (IA) {
902       case DataFlowSanitizer::IA_TLS: {
903         Value *ArgTLSPtr = getArgTLSPtr();
904         Instruction *ArgTLSPos =
905             DFS.ArgTLS ? &*F->getEntryBlock().begin()
906                        : cast<Instruction>(ArgTLSPtr)->getNextNode();
907         IRBuilder<> IRB(ArgTLSPos);
908         Shadow = IRB.CreateLoad(getArgTLS(A->getArgNo(), ArgTLSPos));
909         break;
910       }
911       case DataFlowSanitizer::IA_Args: {
912         unsigned ArgIdx = A->getArgNo() + F->getArgumentList().size() / 2;
913         Function::arg_iterator i = F->arg_begin();
914         while (ArgIdx--)
915           ++i;
916         Shadow = i;
917         assert(Shadow->getType() == DFS.ShadowTy);
918         break;
919       }
920       }
921       NonZeroChecks.push_back(Shadow);
922     } else {
923       Shadow = DFS.ZeroShadow;
924     }
925   }
926   return Shadow;
927 }
928
929 void DFSanFunction::setShadow(Instruction *I, Value *Shadow) {
930   assert(!ValShadowMap.count(I));
931   assert(Shadow->getType() == DFS.ShadowTy);
932   ValShadowMap[I] = Shadow;
933 }
934
935 Value *DataFlowSanitizer::getShadowAddress(Value *Addr, Instruction *Pos) {
936   assert(Addr != RetvalTLS && "Reinstrumenting?");
937   IRBuilder<> IRB(Pos);
938   return IRB.CreateIntToPtr(
939       IRB.CreateMul(
940           IRB.CreateAnd(IRB.CreatePtrToInt(Addr, IntptrTy), ShadowPtrMask),
941           ShadowPtrMul),
942       ShadowPtrTy);
943 }
944
945 // Generates IR to compute the union of the two given shadows, inserting it
946 // before Pos.  Returns the computed union Value.
947 Value *DFSanFunction::combineShadows(Value *V1, Value *V2, Instruction *Pos) {
948   if (V1 == DFS.ZeroShadow)
949     return V2;
950   if (V2 == DFS.ZeroShadow)
951     return V1;
952   if (V1 == V2)
953     return V1;
954
955   auto V1Elems = ShadowElements.find(V1);
956   auto V2Elems = ShadowElements.find(V2);
957   if (V1Elems != ShadowElements.end() && V2Elems != ShadowElements.end()) {
958     if (std::includes(V1Elems->second.begin(), V1Elems->second.end(),
959                       V2Elems->second.begin(), V2Elems->second.end())) {
960       return V1;
961     } else if (std::includes(V2Elems->second.begin(), V2Elems->second.end(),
962                              V1Elems->second.begin(), V1Elems->second.end())) {
963       return V2;
964     }
965   } else if (V1Elems != ShadowElements.end()) {
966     if (V1Elems->second.count(V2))
967       return V1;
968   } else if (V2Elems != ShadowElements.end()) {
969     if (V2Elems->second.count(V1))
970       return V2;
971   }
972
973   auto Key = std::make_pair(V1, V2);
974   if (V1 > V2)
975     std::swap(Key.first, Key.second);
976   CachedCombinedShadow &CCS = CachedCombinedShadows[Key];
977   if (CCS.Block && DT.dominates(CCS.Block, Pos->getParent()))
978     return CCS.Shadow;
979
980   IRBuilder<> IRB(Pos);
981   if (AvoidNewBlocks) {
982     CallInst *Call = IRB.CreateCall2(DFS.DFSanCheckedUnionFn, V1, V2);
983     Call->addAttribute(AttributeSet::ReturnIndex, Attribute::ZExt);
984     Call->addAttribute(1, Attribute::ZExt);
985     Call->addAttribute(2, Attribute::ZExt);
986
987     CCS.Block = Pos->getParent();
988     CCS.Shadow = Call;
989   } else {
990     BasicBlock *Head = Pos->getParent();
991     Value *Ne = IRB.CreateICmpNE(V1, V2);
992     BranchInst *BI = cast<BranchInst>(SplitBlockAndInsertIfThen(
993         Ne, Pos, /*Unreachable=*/false, DFS.ColdCallWeights, &DT));
994     IRBuilder<> ThenIRB(BI);
995     CallInst *Call = ThenIRB.CreateCall2(DFS.DFSanUnionFn, V1, V2);
996     Call->addAttribute(AttributeSet::ReturnIndex, Attribute::ZExt);
997     Call->addAttribute(1, Attribute::ZExt);
998     Call->addAttribute(2, Attribute::ZExt);
999
1000     BasicBlock *Tail = BI->getSuccessor(0);
1001     PHINode *Phi = PHINode::Create(DFS.ShadowTy, 2, "", Tail->begin());
1002     Phi->addIncoming(Call, Call->getParent());
1003     Phi->addIncoming(V1, Head);
1004
1005     CCS.Block = Tail;
1006     CCS.Shadow = Phi;
1007   }
1008
1009   std::set<Value *> UnionElems;
1010   if (V1Elems != ShadowElements.end()) {
1011     UnionElems = V1Elems->second;
1012   } else {
1013     UnionElems.insert(V1);
1014   }
1015   if (V2Elems != ShadowElements.end()) {
1016     UnionElems.insert(V2Elems->second.begin(), V2Elems->second.end());
1017   } else {
1018     UnionElems.insert(V2);
1019   }
1020   ShadowElements[CCS.Shadow] = std::move(UnionElems);
1021
1022   return CCS.Shadow;
1023 }
1024
1025 // A convenience function which folds the shadows of each of the operands
1026 // of the provided instruction Inst, inserting the IR before Inst.  Returns
1027 // the computed union Value.
1028 Value *DFSanFunction::combineOperandShadows(Instruction *Inst) {
1029   if (Inst->getNumOperands() == 0)
1030     return DFS.ZeroShadow;
1031
1032   Value *Shadow = getShadow(Inst->getOperand(0));
1033   for (unsigned i = 1, n = Inst->getNumOperands(); i != n; ++i) {
1034     Shadow = combineShadows(Shadow, getShadow(Inst->getOperand(i)), Inst);
1035   }
1036   return Shadow;
1037 }
1038
1039 void DFSanVisitor::visitOperandShadowInst(Instruction &I) {
1040   Value *CombinedShadow = DFSF.combineOperandShadows(&I);
1041   DFSF.setShadow(&I, CombinedShadow);
1042 }
1043
1044 // Generates IR to load shadow corresponding to bytes [Addr, Addr+Size), where
1045 // Addr has alignment Align, and take the union of each of those shadows.
1046 Value *DFSanFunction::loadShadow(Value *Addr, uint64_t Size, uint64_t Align,
1047                                  Instruction *Pos) {
1048   if (AllocaInst *AI = dyn_cast<AllocaInst>(Addr)) {
1049     llvm::DenseMap<AllocaInst *, AllocaInst *>::iterator i =
1050         AllocaShadowMap.find(AI);
1051     if (i != AllocaShadowMap.end()) {
1052       IRBuilder<> IRB(Pos);
1053       return IRB.CreateLoad(i->second);
1054     }
1055   }
1056
1057   uint64_t ShadowAlign = Align * DFS.ShadowWidth / 8;
1058   SmallVector<Value *, 2> Objs;
1059   GetUnderlyingObjects(Addr, Objs, DFS.DL);
1060   bool AllConstants = true;
1061   for (SmallVector<Value *, 2>::iterator i = Objs.begin(), e = Objs.end();
1062        i != e; ++i) {
1063     if (isa<Function>(*i) || isa<BlockAddress>(*i))
1064       continue;
1065     if (isa<GlobalVariable>(*i) && cast<GlobalVariable>(*i)->isConstant())
1066       continue;
1067
1068     AllConstants = false;
1069     break;
1070   }
1071   if (AllConstants)
1072     return DFS.ZeroShadow;
1073
1074   Value *ShadowAddr = DFS.getShadowAddress(Addr, Pos);
1075   switch (Size) {
1076   case 0:
1077     return DFS.ZeroShadow;
1078   case 1: {
1079     LoadInst *LI = new LoadInst(ShadowAddr, "", Pos);
1080     LI->setAlignment(ShadowAlign);
1081     return LI;
1082   }
1083   case 2: {
1084     IRBuilder<> IRB(Pos);
1085     Value *ShadowAddr1 =
1086         IRB.CreateGEP(ShadowAddr, ConstantInt::get(DFS.IntptrTy, 1));
1087     return combineShadows(IRB.CreateAlignedLoad(ShadowAddr, ShadowAlign),
1088                           IRB.CreateAlignedLoad(ShadowAddr1, ShadowAlign), Pos);
1089   }
1090   }
1091   if (!AvoidNewBlocks && Size % (64 / DFS.ShadowWidth) == 0) {
1092     // Fast path for the common case where each byte has identical shadow: load
1093     // shadow 64 bits at a time, fall out to a __dfsan_union_load call if any
1094     // shadow is non-equal.
1095     BasicBlock *FallbackBB = BasicBlock::Create(*DFS.Ctx, "", F);
1096     IRBuilder<> FallbackIRB(FallbackBB);
1097     CallInst *FallbackCall = FallbackIRB.CreateCall2(
1098         DFS.DFSanUnionLoadFn, ShadowAddr, ConstantInt::get(DFS.IntptrTy, Size));
1099     FallbackCall->addAttribute(AttributeSet::ReturnIndex, Attribute::ZExt);
1100
1101     // Compare each of the shadows stored in the loaded 64 bits to each other,
1102     // by computing (WideShadow rotl ShadowWidth) == WideShadow.
1103     IRBuilder<> IRB(Pos);
1104     Value *WideAddr =
1105         IRB.CreateBitCast(ShadowAddr, Type::getInt64PtrTy(*DFS.Ctx));
1106     Value *WideShadow = IRB.CreateAlignedLoad(WideAddr, ShadowAlign);
1107     Value *TruncShadow = IRB.CreateTrunc(WideShadow, DFS.ShadowTy);
1108     Value *ShlShadow = IRB.CreateShl(WideShadow, DFS.ShadowWidth);
1109     Value *ShrShadow = IRB.CreateLShr(WideShadow, 64 - DFS.ShadowWidth);
1110     Value *RotShadow = IRB.CreateOr(ShlShadow, ShrShadow);
1111     Value *ShadowsEq = IRB.CreateICmpEQ(WideShadow, RotShadow);
1112
1113     BasicBlock *Head = Pos->getParent();
1114     BasicBlock *Tail = Head->splitBasicBlock(Pos);
1115
1116     if (DomTreeNode *OldNode = DT.getNode(Head)) {
1117       std::vector<DomTreeNode *> Children(OldNode->begin(), OldNode->end());
1118
1119       DomTreeNode *NewNode = DT.addNewBlock(Tail, Head);
1120       for (auto Child : Children)
1121         DT.changeImmediateDominator(Child, NewNode);
1122     }
1123
1124     // In the following code LastBr will refer to the previous basic block's
1125     // conditional branch instruction, whose true successor is fixed up to point
1126     // to the next block during the loop below or to the tail after the final
1127     // iteration.
1128     BranchInst *LastBr = BranchInst::Create(FallbackBB, FallbackBB, ShadowsEq);
1129     ReplaceInstWithInst(Head->getTerminator(), LastBr);
1130     DT.addNewBlock(FallbackBB, Head);
1131
1132     for (uint64_t Ofs = 64 / DFS.ShadowWidth; Ofs != Size;
1133          Ofs += 64 / DFS.ShadowWidth) {
1134       BasicBlock *NextBB = BasicBlock::Create(*DFS.Ctx, "", F);
1135       DT.addNewBlock(NextBB, LastBr->getParent());
1136       IRBuilder<> NextIRB(NextBB);
1137       WideAddr = NextIRB.CreateGEP(WideAddr, ConstantInt::get(DFS.IntptrTy, 1));
1138       Value *NextWideShadow = NextIRB.CreateAlignedLoad(WideAddr, ShadowAlign);
1139       ShadowsEq = NextIRB.CreateICmpEQ(WideShadow, NextWideShadow);
1140       LastBr->setSuccessor(0, NextBB);
1141       LastBr = NextIRB.CreateCondBr(ShadowsEq, FallbackBB, FallbackBB);
1142     }
1143
1144     LastBr->setSuccessor(0, Tail);
1145     FallbackIRB.CreateBr(Tail);
1146     PHINode *Shadow = PHINode::Create(DFS.ShadowTy, 2, "", &Tail->front());
1147     Shadow->addIncoming(FallbackCall, FallbackBB);
1148     Shadow->addIncoming(TruncShadow, LastBr->getParent());
1149     return Shadow;
1150   }
1151
1152   IRBuilder<> IRB(Pos);
1153   CallInst *FallbackCall = IRB.CreateCall2(
1154       DFS.DFSanUnionLoadFn, ShadowAddr, ConstantInt::get(DFS.IntptrTy, Size));
1155   FallbackCall->addAttribute(AttributeSet::ReturnIndex, Attribute::ZExt);
1156   return FallbackCall;
1157 }
1158
1159 void DFSanVisitor::visitLoadInst(LoadInst &LI) {
1160   uint64_t Size = DFSF.DFS.DL->getTypeStoreSize(LI.getType());
1161   if (Size == 0) {
1162     DFSF.setShadow(&LI, DFSF.DFS.ZeroShadow);
1163     return;
1164   }
1165
1166   uint64_t Align;
1167   if (ClPreserveAlignment) {
1168     Align = LI.getAlignment();
1169     if (Align == 0)
1170       Align = DFSF.DFS.DL->getABITypeAlignment(LI.getType());
1171   } else {
1172     Align = 1;
1173   }
1174   IRBuilder<> IRB(&LI);
1175   Value *Shadow = DFSF.loadShadow(LI.getPointerOperand(), Size, Align, &LI);
1176   if (ClCombinePointerLabelsOnLoad) {
1177     Value *PtrShadow = DFSF.getShadow(LI.getPointerOperand());
1178     Shadow = DFSF.combineShadows(Shadow, PtrShadow, &LI);
1179   }
1180   if (Shadow != DFSF.DFS.ZeroShadow)
1181     DFSF.NonZeroChecks.push_back(Shadow);
1182
1183   DFSF.setShadow(&LI, Shadow);
1184 }
1185
1186 void DFSanFunction::storeShadow(Value *Addr, uint64_t Size, uint64_t Align,
1187                                 Value *Shadow, Instruction *Pos) {
1188   if (AllocaInst *AI = dyn_cast<AllocaInst>(Addr)) {
1189     llvm::DenseMap<AllocaInst *, AllocaInst *>::iterator i =
1190         AllocaShadowMap.find(AI);
1191     if (i != AllocaShadowMap.end()) {
1192       IRBuilder<> IRB(Pos);
1193       IRB.CreateStore(Shadow, i->second);
1194       return;
1195     }
1196   }
1197
1198   uint64_t ShadowAlign = Align * DFS.ShadowWidth / 8;
1199   IRBuilder<> IRB(Pos);
1200   Value *ShadowAddr = DFS.getShadowAddress(Addr, Pos);
1201   if (Shadow == DFS.ZeroShadow) {
1202     IntegerType *ShadowTy = IntegerType::get(*DFS.Ctx, Size * DFS.ShadowWidth);
1203     Value *ExtZeroShadow = ConstantInt::get(ShadowTy, 0);
1204     Value *ExtShadowAddr =
1205         IRB.CreateBitCast(ShadowAddr, PointerType::getUnqual(ShadowTy));
1206     IRB.CreateAlignedStore(ExtZeroShadow, ExtShadowAddr, ShadowAlign);
1207     return;
1208   }
1209
1210   const unsigned ShadowVecSize = 128 / DFS.ShadowWidth;
1211   uint64_t Offset = 0;
1212   if (Size >= ShadowVecSize) {
1213     VectorType *ShadowVecTy = VectorType::get(DFS.ShadowTy, ShadowVecSize);
1214     Value *ShadowVec = UndefValue::get(ShadowVecTy);
1215     for (unsigned i = 0; i != ShadowVecSize; ++i) {
1216       ShadowVec = IRB.CreateInsertElement(
1217           ShadowVec, Shadow, ConstantInt::get(Type::getInt32Ty(*DFS.Ctx), i));
1218     }
1219     Value *ShadowVecAddr =
1220         IRB.CreateBitCast(ShadowAddr, PointerType::getUnqual(ShadowVecTy));
1221     do {
1222       Value *CurShadowVecAddr = IRB.CreateConstGEP1_32(ShadowVecAddr, Offset);
1223       IRB.CreateAlignedStore(ShadowVec, CurShadowVecAddr, ShadowAlign);
1224       Size -= ShadowVecSize;
1225       ++Offset;
1226     } while (Size >= ShadowVecSize);
1227     Offset *= ShadowVecSize;
1228   }
1229   while (Size > 0) {
1230     Value *CurShadowAddr = IRB.CreateConstGEP1_32(ShadowAddr, Offset);
1231     IRB.CreateAlignedStore(Shadow, CurShadowAddr, ShadowAlign);
1232     --Size;
1233     ++Offset;
1234   }
1235 }
1236
1237 void DFSanVisitor::visitStoreInst(StoreInst &SI) {
1238   uint64_t Size =
1239       DFSF.DFS.DL->getTypeStoreSize(SI.getValueOperand()->getType());
1240   if (Size == 0)
1241     return;
1242
1243   uint64_t Align;
1244   if (ClPreserveAlignment) {
1245     Align = SI.getAlignment();
1246     if (Align == 0)
1247       Align = DFSF.DFS.DL->getABITypeAlignment(SI.getValueOperand()->getType());
1248   } else {
1249     Align = 1;
1250   }
1251
1252   Value* Shadow = DFSF.getShadow(SI.getValueOperand());
1253   if (ClCombinePointerLabelsOnStore) {
1254     Value *PtrShadow = DFSF.getShadow(SI.getPointerOperand());
1255     Shadow = DFSF.combineShadows(Shadow, PtrShadow, &SI);
1256   }
1257   DFSF.storeShadow(SI.getPointerOperand(), Size, Align, Shadow, &SI);
1258 }
1259
1260 void DFSanVisitor::visitBinaryOperator(BinaryOperator &BO) {
1261   visitOperandShadowInst(BO);
1262 }
1263
1264 void DFSanVisitor::visitCastInst(CastInst &CI) { visitOperandShadowInst(CI); }
1265
1266 void DFSanVisitor::visitCmpInst(CmpInst &CI) { visitOperandShadowInst(CI); }
1267
1268 void DFSanVisitor::visitGetElementPtrInst(GetElementPtrInst &GEPI) {
1269   visitOperandShadowInst(GEPI);
1270 }
1271
1272 void DFSanVisitor::visitExtractElementInst(ExtractElementInst &I) {
1273   visitOperandShadowInst(I);
1274 }
1275
1276 void DFSanVisitor::visitInsertElementInst(InsertElementInst &I) {
1277   visitOperandShadowInst(I);
1278 }
1279
1280 void DFSanVisitor::visitShuffleVectorInst(ShuffleVectorInst &I) {
1281   visitOperandShadowInst(I);
1282 }
1283
1284 void DFSanVisitor::visitExtractValueInst(ExtractValueInst &I) {
1285   visitOperandShadowInst(I);
1286 }
1287
1288 void DFSanVisitor::visitInsertValueInst(InsertValueInst &I) {
1289   visitOperandShadowInst(I);
1290 }
1291
1292 void DFSanVisitor::visitAllocaInst(AllocaInst &I) {
1293   bool AllLoadsStores = true;
1294   for (User *U : I.users()) {
1295     if (isa<LoadInst>(U))
1296       continue;
1297
1298     if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
1299       if (SI->getPointerOperand() == &I)
1300         continue;
1301     }
1302
1303     AllLoadsStores = false;
1304     break;
1305   }
1306   if (AllLoadsStores) {
1307     IRBuilder<> IRB(&I);
1308     DFSF.AllocaShadowMap[&I] = IRB.CreateAlloca(DFSF.DFS.ShadowTy);
1309   }
1310   DFSF.setShadow(&I, DFSF.DFS.ZeroShadow);
1311 }
1312
1313 void DFSanVisitor::visitSelectInst(SelectInst &I) {
1314   Value *CondShadow = DFSF.getShadow(I.getCondition());
1315   Value *TrueShadow = DFSF.getShadow(I.getTrueValue());
1316   Value *FalseShadow = DFSF.getShadow(I.getFalseValue());
1317
1318   if (isa<VectorType>(I.getCondition()->getType())) {
1319     DFSF.setShadow(
1320         &I,
1321         DFSF.combineShadows(
1322             CondShadow, DFSF.combineShadows(TrueShadow, FalseShadow, &I), &I));
1323   } else {
1324     Value *ShadowSel;
1325     if (TrueShadow == FalseShadow) {
1326       ShadowSel = TrueShadow;
1327     } else {
1328       ShadowSel =
1329           SelectInst::Create(I.getCondition(), TrueShadow, FalseShadow, "", &I);
1330     }
1331     DFSF.setShadow(&I, DFSF.combineShadows(CondShadow, ShadowSel, &I));
1332   }
1333 }
1334
1335 void DFSanVisitor::visitMemSetInst(MemSetInst &I) {
1336   IRBuilder<> IRB(&I);
1337   Value *ValShadow = DFSF.getShadow(I.getValue());
1338   IRB.CreateCall3(
1339       DFSF.DFS.DFSanSetLabelFn, ValShadow,
1340       IRB.CreateBitCast(I.getDest(), Type::getInt8PtrTy(*DFSF.DFS.Ctx)),
1341       IRB.CreateZExtOrTrunc(I.getLength(), DFSF.DFS.IntptrTy));
1342 }
1343
1344 void DFSanVisitor::visitMemTransferInst(MemTransferInst &I) {
1345   IRBuilder<> IRB(&I);
1346   Value *DestShadow = DFSF.DFS.getShadowAddress(I.getDest(), &I);
1347   Value *SrcShadow = DFSF.DFS.getShadowAddress(I.getSource(), &I);
1348   Value *LenShadow = IRB.CreateMul(
1349       I.getLength(),
1350       ConstantInt::get(I.getLength()->getType(), DFSF.DFS.ShadowWidth / 8));
1351   Value *AlignShadow;
1352   if (ClPreserveAlignment) {
1353     AlignShadow = IRB.CreateMul(I.getAlignmentCst(),
1354                                 ConstantInt::get(I.getAlignmentCst()->getType(),
1355                                                  DFSF.DFS.ShadowWidth / 8));
1356   } else {
1357     AlignShadow = ConstantInt::get(I.getAlignmentCst()->getType(),
1358                                    DFSF.DFS.ShadowWidth / 8);
1359   }
1360   Type *Int8Ptr = Type::getInt8PtrTy(*DFSF.DFS.Ctx);
1361   DestShadow = IRB.CreateBitCast(DestShadow, Int8Ptr);
1362   SrcShadow = IRB.CreateBitCast(SrcShadow, Int8Ptr);
1363   IRB.CreateCall5(I.getCalledValue(), DestShadow, SrcShadow, LenShadow,
1364                   AlignShadow, I.getVolatileCst());
1365 }
1366
1367 void DFSanVisitor::visitReturnInst(ReturnInst &RI) {
1368   if (!DFSF.IsNativeABI && RI.getReturnValue()) {
1369     switch (DFSF.IA) {
1370     case DataFlowSanitizer::IA_TLS: {
1371       Value *S = DFSF.getShadow(RI.getReturnValue());
1372       IRBuilder<> IRB(&RI);
1373       IRB.CreateStore(S, DFSF.getRetvalTLS());
1374       break;
1375     }
1376     case DataFlowSanitizer::IA_Args: {
1377       IRBuilder<> IRB(&RI);
1378       Type *RT = DFSF.F->getFunctionType()->getReturnType();
1379       Value *InsVal =
1380           IRB.CreateInsertValue(UndefValue::get(RT), RI.getReturnValue(), 0);
1381       Value *InsShadow =
1382           IRB.CreateInsertValue(InsVal, DFSF.getShadow(RI.getReturnValue()), 1);
1383       RI.setOperand(0, InsShadow);
1384       break;
1385     }
1386     }
1387   }
1388 }
1389
1390 void DFSanVisitor::visitCallSite(CallSite CS) {
1391   Function *F = CS.getCalledFunction();
1392   if ((F && F->isIntrinsic()) || isa<InlineAsm>(CS.getCalledValue())) {
1393     visitOperandShadowInst(*CS.getInstruction());
1394     return;
1395   }
1396
1397   // Calls to this function are synthesized in wrappers, and we shouldn't
1398   // instrument them.
1399   if (F == DFSF.DFS.DFSanVarargWrapperFn)
1400     return;
1401
1402   assert(!(cast<FunctionType>(
1403       CS.getCalledValue()->getType()->getPointerElementType())->isVarArg() &&
1404            dyn_cast<InvokeInst>(CS.getInstruction())));
1405
1406   IRBuilder<> IRB(CS.getInstruction());
1407
1408   DenseMap<Value *, Function *>::iterator i =
1409       DFSF.DFS.UnwrappedFnMap.find(CS.getCalledValue());
1410   if (i != DFSF.DFS.UnwrappedFnMap.end()) {
1411     Function *F = i->second;
1412     switch (DFSF.DFS.getWrapperKind(F)) {
1413     case DataFlowSanitizer::WK_Warning: {
1414       CS.setCalledFunction(F);
1415       IRB.CreateCall(DFSF.DFS.DFSanUnimplementedFn,
1416                      IRB.CreateGlobalStringPtr(F->getName()));
1417       DFSF.setShadow(CS.getInstruction(), DFSF.DFS.ZeroShadow);
1418       return;
1419     }
1420     case DataFlowSanitizer::WK_Discard: {
1421       CS.setCalledFunction(F);
1422       DFSF.setShadow(CS.getInstruction(), DFSF.DFS.ZeroShadow);
1423       return;
1424     }
1425     case DataFlowSanitizer::WK_Functional: {
1426       CS.setCalledFunction(F);
1427       visitOperandShadowInst(*CS.getInstruction());
1428       return;
1429     }
1430     case DataFlowSanitizer::WK_Custom: {
1431       // Don't try to handle invokes of custom functions, it's too complicated.
1432       // Instead, invoke the dfsw$ wrapper, which will in turn call the __dfsw_
1433       // wrapper.
1434       if (CallInst *CI = dyn_cast<CallInst>(CS.getInstruction())) {
1435         FunctionType *FT = F->getFunctionType();
1436         FunctionType *CustomFT = DFSF.DFS.getCustomFunctionType(FT);
1437         std::string CustomFName = "__dfsw_";
1438         CustomFName += F->getName();
1439         Constant *CustomF =
1440             DFSF.DFS.Mod->getOrInsertFunction(CustomFName, CustomFT);
1441         if (Function *CustomFn = dyn_cast<Function>(CustomF)) {
1442           CustomFn->copyAttributesFrom(F);
1443
1444           // Custom functions returning non-void will write to the return label.
1445           if (!FT->getReturnType()->isVoidTy()) {
1446             CustomFn->removeAttributes(AttributeSet::FunctionIndex,
1447                                        DFSF.DFS.ReadOnlyNoneAttrs);
1448           }
1449         }
1450
1451         std::vector<Value *> Args;
1452
1453         CallSite::arg_iterator i = CS.arg_begin();
1454         for (unsigned n = FT->getNumParams(); n != 0; ++i, --n) {
1455           Type *T = (*i)->getType();
1456           FunctionType *ParamFT;
1457           if (isa<PointerType>(T) &&
1458               (ParamFT = dyn_cast<FunctionType>(
1459                    cast<PointerType>(T)->getElementType()))) {
1460             std::string TName = "dfst";
1461             TName += utostr(FT->getNumParams() - n);
1462             TName += "$";
1463             TName += F->getName();
1464             Constant *T = DFSF.DFS.getOrBuildTrampolineFunction(ParamFT, TName);
1465             Args.push_back(T);
1466             Args.push_back(
1467                 IRB.CreateBitCast(*i, Type::getInt8PtrTy(*DFSF.DFS.Ctx)));
1468           } else {
1469             Args.push_back(*i);
1470           }
1471         }
1472
1473         i = CS.arg_begin();
1474         for (unsigned n = FT->getNumParams(); n != 0; ++i, --n)
1475           Args.push_back(DFSF.getShadow(*i));
1476
1477         if (FT->isVarArg()) {
1478           auto LabelVAAlloca =
1479               new AllocaInst(ArrayType::get(DFSF.DFS.ShadowTy,
1480                                             CS.arg_size() - FT->getNumParams()),
1481                              "labelva", DFSF.F->getEntryBlock().begin());
1482
1483           for (unsigned n = 0; i != CS.arg_end(); ++i, ++n) {
1484             auto LabelVAPtr = IRB.CreateStructGEP(LabelVAAlloca, n);
1485             IRB.CreateStore(DFSF.getShadow(*i), LabelVAPtr);
1486           }
1487
1488           Args.push_back(IRB.CreateStructGEP(LabelVAAlloca, 0));
1489         }
1490
1491         if (!FT->getReturnType()->isVoidTy()) {
1492           if (!DFSF.LabelReturnAlloca) {
1493             DFSF.LabelReturnAlloca =
1494                 new AllocaInst(DFSF.DFS.ShadowTy, "labelreturn",
1495                                DFSF.F->getEntryBlock().begin());
1496           }
1497           Args.push_back(DFSF.LabelReturnAlloca);
1498         }
1499
1500         for (i = CS.arg_begin() + FT->getNumParams(); i != CS.arg_end(); ++i)
1501           Args.push_back(*i);
1502
1503         CallInst *CustomCI = IRB.CreateCall(CustomF, Args);
1504         CustomCI->setCallingConv(CI->getCallingConv());
1505         CustomCI->setAttributes(CI->getAttributes());
1506
1507         if (!FT->getReturnType()->isVoidTy()) {
1508           LoadInst *LabelLoad = IRB.CreateLoad(DFSF.LabelReturnAlloca);
1509           DFSF.setShadow(CustomCI, LabelLoad);
1510         }
1511
1512         CI->replaceAllUsesWith(CustomCI);
1513         CI->eraseFromParent();
1514         return;
1515       }
1516       break;
1517     }
1518     }
1519   }
1520
1521   FunctionType *FT = cast<FunctionType>(
1522       CS.getCalledValue()->getType()->getPointerElementType());
1523   if (DFSF.DFS.getInstrumentedABI() == DataFlowSanitizer::IA_TLS) {
1524     for (unsigned i = 0, n = FT->getNumParams(); i != n; ++i) {
1525       IRB.CreateStore(DFSF.getShadow(CS.getArgument(i)),
1526                       DFSF.getArgTLS(i, CS.getInstruction()));
1527     }
1528   }
1529
1530   Instruction *Next = nullptr;
1531   if (!CS.getType()->isVoidTy()) {
1532     if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
1533       if (II->getNormalDest()->getSinglePredecessor()) {
1534         Next = II->getNormalDest()->begin();
1535       } else {
1536         BasicBlock *NewBB =
1537             SplitEdge(II->getParent(), II->getNormalDest(), &DFSF.DT);
1538         Next = NewBB->begin();
1539       }
1540     } else {
1541       Next = CS->getNextNode();
1542     }
1543
1544     if (DFSF.DFS.getInstrumentedABI() == DataFlowSanitizer::IA_TLS) {
1545       IRBuilder<> NextIRB(Next);
1546       LoadInst *LI = NextIRB.CreateLoad(DFSF.getRetvalTLS());
1547       DFSF.SkipInsts.insert(LI);
1548       DFSF.setShadow(CS.getInstruction(), LI);
1549       DFSF.NonZeroChecks.push_back(LI);
1550     }
1551   }
1552
1553   // Do all instrumentation for IA_Args down here to defer tampering with the
1554   // CFG in a way that SplitEdge may be able to detect.
1555   if (DFSF.DFS.getInstrumentedABI() == DataFlowSanitizer::IA_Args) {
1556     FunctionType *NewFT = DFSF.DFS.getArgsFunctionType(FT);
1557     Value *Func =
1558         IRB.CreateBitCast(CS.getCalledValue(), PointerType::getUnqual(NewFT));
1559     std::vector<Value *> Args;
1560
1561     CallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
1562     for (unsigned n = FT->getNumParams(); n != 0; ++i, --n)
1563       Args.push_back(*i);
1564
1565     i = CS.arg_begin();
1566     for (unsigned n = FT->getNumParams(); n != 0; ++i, --n)
1567       Args.push_back(DFSF.getShadow(*i));
1568
1569     if (FT->isVarArg()) {
1570       unsigned VarArgSize = CS.arg_size() - FT->getNumParams();
1571       ArrayType *VarArgArrayTy = ArrayType::get(DFSF.DFS.ShadowTy, VarArgSize);
1572       AllocaInst *VarArgShadow =
1573           new AllocaInst(VarArgArrayTy, "", DFSF.F->getEntryBlock().begin());
1574       Args.push_back(IRB.CreateConstGEP2_32(VarArgShadow, 0, 0));
1575       for (unsigned n = 0; i != e; ++i, ++n) {
1576         IRB.CreateStore(DFSF.getShadow(*i),
1577                         IRB.CreateConstGEP2_32(VarArgShadow, 0, n));
1578         Args.push_back(*i);
1579       }
1580     }
1581
1582     CallSite NewCS;
1583     if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
1584       NewCS = IRB.CreateInvoke(Func, II->getNormalDest(), II->getUnwindDest(),
1585                                Args);
1586     } else {
1587       NewCS = IRB.CreateCall(Func, Args);
1588     }
1589     NewCS.setCallingConv(CS.getCallingConv());
1590     NewCS.setAttributes(CS.getAttributes().removeAttributes(
1591         *DFSF.DFS.Ctx, AttributeSet::ReturnIndex,
1592         AttributeFuncs::typeIncompatible(NewCS.getInstruction()->getType(),
1593                                          AttributeSet::ReturnIndex)));
1594
1595     if (Next) {
1596       ExtractValueInst *ExVal =
1597           ExtractValueInst::Create(NewCS.getInstruction(), 0, "", Next);
1598       DFSF.SkipInsts.insert(ExVal);
1599       ExtractValueInst *ExShadow =
1600           ExtractValueInst::Create(NewCS.getInstruction(), 1, "", Next);
1601       DFSF.SkipInsts.insert(ExShadow);
1602       DFSF.setShadow(ExVal, ExShadow);
1603       DFSF.NonZeroChecks.push_back(ExShadow);
1604
1605       CS.getInstruction()->replaceAllUsesWith(ExVal);
1606     }
1607
1608     CS.getInstruction()->eraseFromParent();
1609   }
1610 }
1611
1612 void DFSanVisitor::visitPHINode(PHINode &PN) {
1613   PHINode *ShadowPN =
1614       PHINode::Create(DFSF.DFS.ShadowTy, PN.getNumIncomingValues(), "", &PN);
1615
1616   // Give the shadow phi node valid predecessors to fool SplitEdge into working.
1617   Value *UndefShadow = UndefValue::get(DFSF.DFS.ShadowTy);
1618   for (PHINode::block_iterator i = PN.block_begin(), e = PN.block_end(); i != e;
1619        ++i) {
1620     ShadowPN->addIncoming(UndefShadow, *i);
1621   }
1622
1623   DFSF.PHIFixups.push_back(std::make_pair(&PN, ShadowPN));
1624   DFSF.setShadow(&PN, ShadowPN);
1625 }