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