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