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