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