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 /// +--------------------+ 0x300200000000 (kUnusedAddr)
30 /// |    union table     |
31 /// +--------------------+ 0x300000000000 (kUnionTableAddr)
32 /// |       origin       |
33 /// +--------------------+ 0x200000008000 (kOriginAddr)
34 /// |   shadow memory    |
35 /// +--------------------+ 0x000000010000 (kShadowAddr)
36 /// | reserved by kernel |
37 /// +--------------------+ 0x000000000000
38 ///
39 /// To derive a shadow memory address from an application memory address,
40 /// bits 44-46 are cleared to bring the address into the range
41 /// [0x000000008000,0x100000000000).  Then the address is shifted left by 1 to
42 /// account for the double byte representation of shadow labels and move the
43 /// address into the shadow memory range.  See the function
44 /// DataFlowSanitizer::getShadowAddress below.
45 ///
46 /// For more information, please refer to the design document:
47 /// http://clang.llvm.org/docs/DataFlowSanitizerDesign.html
48 //
49 //===----------------------------------------------------------------------===//
50 
51 #include "llvm/Transforms/Instrumentation/DataFlowSanitizer.h"
52 #include "llvm/ADT/DenseMap.h"
53 #include "llvm/ADT/DenseSet.h"
54 #include "llvm/ADT/DepthFirstIterator.h"
55 #include "llvm/ADT/None.h"
56 #include "llvm/ADT/SmallPtrSet.h"
57 #include "llvm/ADT/SmallVector.h"
58 #include "llvm/ADT/StringExtras.h"
59 #include "llvm/ADT/StringRef.h"
60 #include "llvm/ADT/Triple.h"
61 #include "llvm/Analysis/ValueTracking.h"
62 #include "llvm/IR/Argument.h"
63 #include "llvm/IR/Attributes.h"
64 #include "llvm/IR/BasicBlock.h"
65 #include "llvm/IR/Constant.h"
66 #include "llvm/IR/Constants.h"
67 #include "llvm/IR/DataLayout.h"
68 #include "llvm/IR/DerivedTypes.h"
69 #include "llvm/IR/Dominators.h"
70 #include "llvm/IR/Function.h"
71 #include "llvm/IR/GlobalAlias.h"
72 #include "llvm/IR/GlobalValue.h"
73 #include "llvm/IR/GlobalVariable.h"
74 #include "llvm/IR/IRBuilder.h"
75 #include "llvm/IR/InlineAsm.h"
76 #include "llvm/IR/InstVisitor.h"
77 #include "llvm/IR/InstrTypes.h"
78 #include "llvm/IR/Instruction.h"
79 #include "llvm/IR/Instructions.h"
80 #include "llvm/IR/IntrinsicInst.h"
81 #include "llvm/IR/LLVMContext.h"
82 #include "llvm/IR/MDBuilder.h"
83 #include "llvm/IR/Module.h"
84 #include "llvm/IR/PassManager.h"
85 #include "llvm/IR/Type.h"
86 #include "llvm/IR/User.h"
87 #include "llvm/IR/Value.h"
88 #include "llvm/InitializePasses.h"
89 #include "llvm/Pass.h"
90 #include "llvm/Support/Casting.h"
91 #include "llvm/Support/CommandLine.h"
92 #include "llvm/Support/ErrorHandling.h"
93 #include "llvm/Support/SpecialCaseList.h"
94 #include "llvm/Support/VirtualFileSystem.h"
95 #include "llvm/Transforms/Instrumentation.h"
96 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
97 #include "llvm/Transforms/Utils/Local.h"
98 #include <algorithm>
99 #include <cassert>
100 #include <cstddef>
101 #include <cstdint>
102 #include <iterator>
103 #include <memory>
104 #include <set>
105 #include <string>
106 #include <utility>
107 #include <vector>
108 
109 using namespace llvm;
110 
111 // This must be consistent with ShadowWidthBits.
112 static const Align kShadowTLSAlignment = Align(2);
113 
114 static const Align kMinOriginAlignment = Align(4);
115 
116 // The size of TLS variables. These constants must be kept in sync with the ones
117 // in dfsan.cpp.
118 static const unsigned kArgTLSSize = 800;
119 static const unsigned kRetvalTLSSize = 800;
120 
121 // External symbol to be used when generating the shadow address for
122 // architectures with multiple VMAs. Instead of using a constant integer
123 // the runtime will set the external mask based on the VMA range.
124 const char kDFSanExternShadowPtrMask[] = "__dfsan_shadow_ptr_mask";
125 
126 // The -dfsan-preserve-alignment flag controls whether this pass assumes that
127 // alignment requirements provided by the input IR are correct.  For example,
128 // if the input IR contains a load with alignment 8, this flag will cause
129 // the shadow load to have alignment 16.  This flag is disabled by default as
130 // we have unfortunately encountered too much code (including Clang itself;
131 // see PR14291) which performs misaligned access.
132 static cl::opt<bool> ClPreserveAlignment(
133     "dfsan-preserve-alignment",
134     cl::desc("respect alignment requirements provided by input IR"), cl::Hidden,
135     cl::init(false));
136 
137 // The ABI list files control how shadow parameters are passed. The pass treats
138 // every function labelled "uninstrumented" in the ABI list file as conforming
139 // to the "native" (i.e. unsanitized) ABI.  Unless the ABI list contains
140 // additional annotations for those functions, a call to one of those functions
141 // will produce a warning message, as the labelling behaviour of the function is
142 // unknown.  The other supported annotations are "functional" and "discard",
143 // which are described below under DataFlowSanitizer::WrapperKind.
144 static cl::list<std::string> ClABIListFiles(
145     "dfsan-abilist",
146     cl::desc("File listing native ABI functions and how the pass treats them"),
147     cl::Hidden);
148 
149 // Controls whether the pass uses IA_Args or IA_TLS as the ABI for instrumented
150 // functions (see DataFlowSanitizer::InstrumentedABI below).
151 static cl::opt<bool> ClArgsABI(
152     "dfsan-args-abi",
153     cl::desc("Use the argument ABI rather than the TLS ABI"),
154     cl::Hidden);
155 
156 // Controls whether the pass includes or ignores the labels of pointers in load
157 // instructions.
158 static cl::opt<bool> ClCombinePointerLabelsOnLoad(
159     "dfsan-combine-pointer-labels-on-load",
160     cl::desc("Combine the label of the pointer with the label of the data when "
161              "loading from memory."),
162     cl::Hidden, cl::init(true));
163 
164 // Controls whether the pass includes or ignores the labels of pointers in
165 // stores instructions.
166 static cl::opt<bool> ClCombinePointerLabelsOnStore(
167     "dfsan-combine-pointer-labels-on-store",
168     cl::desc("Combine the label of the pointer with the label of the data when "
169              "storing in memory."),
170     cl::Hidden, cl::init(false));
171 
172 static cl::opt<bool> ClDebugNonzeroLabels(
173     "dfsan-debug-nonzero-labels",
174     cl::desc("Insert calls to __dfsan_nonzero_label on observing a parameter, "
175              "load or return with a nonzero label"),
176     cl::Hidden);
177 
178 // Experimental feature that inserts callbacks for certain data events.
179 // Currently callbacks are only inserted for loads, stores, memory transfers
180 // (i.e. memcpy and memmove), and comparisons.
181 //
182 // If this flag is set to true, the user must provide definitions for the
183 // following callback functions:
184 //   void __dfsan_load_callback(dfsan_label Label, void* addr);
185 //   void __dfsan_store_callback(dfsan_label Label, void* addr);
186 //   void __dfsan_mem_transfer_callback(dfsan_label *Start, size_t Len);
187 //   void __dfsan_cmp_callback(dfsan_label CombinedLabel);
188 static cl::opt<bool> ClEventCallbacks(
189     "dfsan-event-callbacks",
190     cl::desc("Insert calls to __dfsan_*_callback functions on data events."),
191     cl::Hidden, cl::init(false));
192 
193 // Use a distinct bit for each base label, enabling faster unions with less
194 // instrumentation.  Limits the max number of base labels to 16.
195 static cl::opt<bool> ClFast16Labels(
196     "dfsan-fast-16-labels",
197     cl::desc("Use more efficient instrumentation, limiting the number of "
198              "labels to 16."),
199     cl::Hidden, cl::init(false));
200 
201 // Controls whether the pass tracks the control flow of select instructions.
202 static cl::opt<bool> ClTrackSelectControlFlow(
203     "dfsan-track-select-control-flow",
204     cl::desc("Propagate labels from condition values of select instructions "
205              "to results."),
206     cl::Hidden, cl::init(true));
207 
208 // Controls how to track origins.
209 // * 0: do not track origins.
210 // * 1: track origins at memory store operations.
211 // * 2: TODO: track origins at memory store operations and callsites.
212 static cl::opt<int> ClTrackOrigins("dfsan-track-origins",
213                                    cl::desc("Track origins of labels"),
214                                    cl::Hidden, cl::init(0));
215 
216 static StringRef GetGlobalTypeString(const GlobalValue &G) {
217   // Types of GlobalVariables are always pointer types.
218   Type *GType = G.getValueType();
219   // For now we support excluding struct types only.
220   if (StructType *SGType = dyn_cast<StructType>(GType)) {
221     if (!SGType->isLiteral())
222       return SGType->getName();
223   }
224   return "<unknown type>";
225 }
226 
227 namespace {
228 
229 class DFSanABIList {
230   std::unique_ptr<SpecialCaseList> SCL;
231 
232  public:
233   DFSanABIList() = default;
234 
235   void set(std::unique_ptr<SpecialCaseList> List) { SCL = std::move(List); }
236 
237   /// Returns whether either this function or its source file are listed in the
238   /// given category.
239   bool isIn(const Function &F, StringRef Category) const {
240     return isIn(*F.getParent(), Category) ||
241            SCL->inSection("dataflow", "fun", F.getName(), Category);
242   }
243 
244   /// Returns whether this global alias is listed in the given category.
245   ///
246   /// If GA aliases a function, the alias's name is matched as a function name
247   /// would be.  Similarly, aliases of globals are matched like globals.
248   bool isIn(const GlobalAlias &GA, StringRef Category) const {
249     if (isIn(*GA.getParent(), Category))
250       return true;
251 
252     if (isa<FunctionType>(GA.getValueType()))
253       return SCL->inSection("dataflow", "fun", GA.getName(), Category);
254 
255     return SCL->inSection("dataflow", "global", GA.getName(), Category) ||
256            SCL->inSection("dataflow", "type", GetGlobalTypeString(GA),
257                           Category);
258   }
259 
260   /// Returns whether this module is listed in the given category.
261   bool isIn(const Module &M, StringRef Category) const {
262     return SCL->inSection("dataflow", "src", M.getModuleIdentifier(), Category);
263   }
264 };
265 
266 /// TransformedFunction is used to express the result of transforming one
267 /// function type into another.  This struct is immutable.  It holds metadata
268 /// useful for updating calls of the old function to the new type.
269 struct TransformedFunction {
270   TransformedFunction(FunctionType* OriginalType,
271                       FunctionType* TransformedType,
272                       std::vector<unsigned> ArgumentIndexMapping)
273       : OriginalType(OriginalType),
274         TransformedType(TransformedType),
275         ArgumentIndexMapping(ArgumentIndexMapping) {}
276 
277   // Disallow copies.
278   TransformedFunction(const TransformedFunction&) = delete;
279   TransformedFunction& operator=(const TransformedFunction&) = delete;
280 
281   // Allow moves.
282   TransformedFunction(TransformedFunction&&) = default;
283   TransformedFunction& operator=(TransformedFunction&&) = default;
284 
285   /// Type of the function before the transformation.
286   FunctionType *OriginalType;
287 
288   /// Type of the function after the transformation.
289   FunctionType *TransformedType;
290 
291   /// Transforming a function may change the position of arguments.  This
292   /// member records the mapping from each argument's old position to its new
293   /// position.  Argument positions are zero-indexed.  If the transformation
294   /// from F to F' made the first argument of F into the third argument of F',
295   /// then ArgumentIndexMapping[0] will equal 2.
296   std::vector<unsigned> ArgumentIndexMapping;
297 };
298 
299 /// Given function attributes from a call site for the original function,
300 /// return function attributes appropriate for a call to the transformed
301 /// function.
302 AttributeList TransformFunctionAttributes(
303     const TransformedFunction& TransformedFunction,
304     LLVMContext& Ctx, AttributeList CallSiteAttrs) {
305 
306   // Construct a vector of AttributeSet for each function argument.
307   std::vector<llvm::AttributeSet> ArgumentAttributes(
308       TransformedFunction.TransformedType->getNumParams());
309 
310   // Copy attributes from the parameter of the original function to the
311   // transformed version.  'ArgumentIndexMapping' holds the mapping from
312   // old argument position to new.
313   for (unsigned i=0, ie = TransformedFunction.ArgumentIndexMapping.size();
314        i < ie; ++i) {
315     unsigned TransformedIndex = TransformedFunction.ArgumentIndexMapping[i];
316     ArgumentAttributes[TransformedIndex] = CallSiteAttrs.getParamAttributes(i);
317   }
318 
319   // Copy annotations on varargs arguments.
320   for (unsigned i = TransformedFunction.OriginalType->getNumParams(),
321        ie = CallSiteAttrs.getNumAttrSets(); i<ie; ++i) {
322     ArgumentAttributes.push_back(CallSiteAttrs.getParamAttributes(i));
323   }
324 
325   return AttributeList::get(
326       Ctx,
327       CallSiteAttrs.getFnAttributes(),
328       CallSiteAttrs.getRetAttributes(),
329       llvm::makeArrayRef(ArgumentAttributes));
330 }
331 
332 class DataFlowSanitizer {
333   friend struct DFSanFunction;
334   friend class DFSanVisitor;
335 
336   enum {
337     ShadowWidthBits = 16,
338     ShadowWidthBytes = ShadowWidthBits / 8,
339     OriginWidthBits = 32,
340     OriginWidthBytes = OriginWidthBits / 8
341   };
342 
343   /// Which ABI should be used for instrumented functions?
344   enum InstrumentedABI {
345     /// Argument and return value labels are passed through additional
346     /// arguments and by modifying the return type.
347     IA_Args,
348 
349     /// Argument and return value labels are passed through TLS variables
350     /// __dfsan_arg_tls and __dfsan_retval_tls.
351     IA_TLS
352   };
353 
354   /// How should calls to uninstrumented functions be handled?
355   enum WrapperKind {
356     /// This function is present in an uninstrumented form but we don't know
357     /// how it should be handled.  Print a warning and call the function anyway.
358     /// Don't label the return value.
359     WK_Warning,
360 
361     /// This function does not write to (user-accessible) memory, and its return
362     /// value is unlabelled.
363     WK_Discard,
364 
365     /// This function does not write to (user-accessible) memory, and the label
366     /// of its return value is the union of the label of its arguments.
367     WK_Functional,
368 
369     /// Instead of calling the function, a custom wrapper __dfsw_F is called,
370     /// where F is the name of the function.  This function may wrap the
371     /// original function or provide its own implementation.  This is similar to
372     /// the IA_Args ABI, except that IA_Args uses a struct return type to
373     /// pass the return value shadow in a register, while WK_Custom uses an
374     /// extra pointer argument to return the shadow.  This allows the wrapped
375     /// form of the function type to be expressed in C.
376     WK_Custom
377   };
378 
379   Module *Mod;
380   LLVMContext *Ctx;
381   Type *Int8Ptr;
382   IntegerType *OriginTy;
383   PointerType *OriginPtrTy;
384   ConstantInt *OriginBase;
385   ConstantInt *ZeroOrigin;
386   /// The shadow type for all primitive types and vector types.
387   IntegerType *PrimitiveShadowTy;
388   PointerType *PrimitiveShadowPtrTy;
389   IntegerType *IntptrTy;
390   ConstantInt *ZeroPrimitiveShadow;
391   ConstantInt *ShadowPtrMask;
392   ConstantInt *ShadowPtrMul;
393   Constant *ArgTLS;
394   ArrayType *ArgOriginTLSTy;
395   Constant *ArgOriginTLS;
396   Constant *RetvalTLS;
397   Constant *RetvalOriginTLS;
398   Constant *ExternalShadowMask;
399   FunctionType *DFSanUnionFnTy;
400   FunctionType *DFSanUnionLoadFnTy;
401   FunctionType *DFSanLoadLabelAndOriginFnTy;
402   FunctionType *DFSanUnimplementedFnTy;
403   FunctionType *DFSanSetLabelFnTy;
404   FunctionType *DFSanNonzeroLabelFnTy;
405   FunctionType *DFSanVarargWrapperFnTy;
406   FunctionType *DFSanCmpCallbackFnTy;
407   FunctionType *DFSanLoadStoreCallbackFnTy;
408   FunctionType *DFSanMemTransferCallbackFnTy;
409   FunctionType *DFSanChainOriginFnTy;
410   FunctionType *DFSanMemOriginTransferFnTy;
411   FunctionType *DFSanMaybeStoreOriginFnTy;
412   FunctionCallee DFSanUnionFn;
413   FunctionCallee DFSanCheckedUnionFn;
414   FunctionCallee DFSanUnionLoadFn;
415   FunctionCallee DFSanUnionLoadFast16LabelsFn;
416   FunctionCallee DFSanLoadLabelAndOriginFn;
417   FunctionCallee DFSanUnimplementedFn;
418   FunctionCallee DFSanSetLabelFn;
419   FunctionCallee DFSanNonzeroLabelFn;
420   FunctionCallee DFSanVarargWrapperFn;
421   FunctionCallee DFSanLoadCallbackFn;
422   FunctionCallee DFSanStoreCallbackFn;
423   FunctionCallee DFSanMemTransferCallbackFn;
424   FunctionCallee DFSanCmpCallbackFn;
425   FunctionCallee DFSanChainOriginFn;
426   FunctionCallee DFSanMemOriginTransferFn;
427   FunctionCallee DFSanMaybeStoreOriginFn;
428   SmallPtrSet<Value *, 16> DFSanRuntimeFunctions;
429   MDNode *ColdCallWeights;
430   DFSanABIList ABIList;
431   DenseMap<Value *, Function *> UnwrappedFnMap;
432   AttrBuilder ReadOnlyNoneAttrs;
433   bool DFSanRuntimeShadowMask = false;
434 
435   Value *getShadowOffset(Value *Addr, IRBuilder<> &IRB);
436   Value *getShadowAddress(Value *Addr, Instruction *Pos);
437   // std::pair<Value *, Value *>
438   // getShadowOriginAddress(Value *Addr, Align InstAlignment, Instruction *Pos);
439   bool isInstrumented(const Function *F);
440   bool isInstrumented(const GlobalAlias *GA);
441   FunctionType *getArgsFunctionType(FunctionType *T);
442   FunctionType *getTrampolineFunctionType(FunctionType *T);
443   TransformedFunction getCustomFunctionType(FunctionType *T);
444   InstrumentedABI getInstrumentedABI();
445   WrapperKind getWrapperKind(Function *F);
446   void addGlobalNamePrefix(GlobalValue *GV);
447   Function *buildWrapperFunction(Function *F, StringRef NewFName,
448                                  GlobalValue::LinkageTypes NewFLink,
449                                  FunctionType *NewFT);
450   Constant *getOrBuildTrampolineFunction(FunctionType *FT, StringRef FName);
451   void initializeCallbackFunctions(Module &M);
452   void initializeRuntimeFunctions(Module &M);
453 
454   bool init(Module &M);
455 
456   /// Returns whether the pass tracks origins. Support only fast16 mode in TLS
457   /// ABI mode.
458   bool shouldTrackOrigins();
459 
460   /// Returns whether the pass tracks labels for struct fields and array
461   /// indices. Support only fast16 mode in TLS ABI mode.
462   bool shouldTrackFieldsAndIndices();
463 
464   /// Returns a zero constant with the shadow type of OrigTy.
465   ///
466   /// getZeroShadow({T1,T2,...}) = {getZeroShadow(T1),getZeroShadow(T2,...}
467   /// getZeroShadow([n x T]) = [n x getZeroShadow(T)]
468   /// getZeroShadow(other type) = i16(0)
469   ///
470   /// Note that a zero shadow is always i16(0) when shouldTrackFieldsAndIndices
471   /// returns false.
472   Constant *getZeroShadow(Type *OrigTy);
473   /// Returns a zero constant with the shadow type of V's type.
474   Constant *getZeroShadow(Value *V);
475 
476   /// Checks if V is a zero shadow.
477   bool isZeroShadow(Value *V);
478 
479   /// Returns the shadow type of OrigTy.
480   ///
481   /// getShadowTy({T1,T2,...}) = {getShadowTy(T1),getShadowTy(T2),...}
482   /// getShadowTy([n x T]) = [n x getShadowTy(T)]
483   /// getShadowTy(other type) = i16
484   ///
485   /// Note that a shadow type is always i16 when shouldTrackFieldsAndIndices
486   /// returns false.
487   Type *getShadowTy(Type *OrigTy);
488   /// Returns the shadow type of of V's type.
489   Type *getShadowTy(Value *V);
490 
491   const uint64_t kNumOfElementsInArgOrgTLS = kArgTLSSize / OriginWidthBytes;
492 
493 public:
494   DataFlowSanitizer(const std::vector<std::string> &ABIListFiles);
495 
496   bool runImpl(Module &M);
497 };
498 
499 struct DFSanFunction {
500   DataFlowSanitizer &DFS;
501   Function *F;
502   DominatorTree DT;
503   DataFlowSanitizer::InstrumentedABI IA;
504   bool IsNativeABI;
505   AllocaInst *LabelReturnAlloca = nullptr;
506   DenseMap<Value *, Value *> ValShadowMap;
507   DenseMap<Value *, Value *> ValOriginMap;
508   DenseMap<AllocaInst *, AllocaInst *> AllocaShadowMap;
509   std::vector<std::pair<PHINode *, PHINode *>> PHIFixups;
510   DenseSet<Instruction *> SkipInsts;
511   std::vector<Value *> NonZeroChecks;
512   bool AvoidNewBlocks;
513 
514   struct CachedShadow {
515     BasicBlock *Block; // The block where Shadow is defined.
516     Value *Shadow;
517   };
518   /// Maps a value to its latest shadow value in terms of domination tree.
519   DenseMap<std::pair<Value *, Value *>, CachedShadow> CachedShadows;
520   /// Maps a value to its latest collapsed shadow value it was converted to in
521   /// terms of domination tree. When ClDebugNonzeroLabels is on, this cache is
522   /// used at a post process where CFG blocks are split. So it does not cache
523   /// BasicBlock like CachedShadows, but uses domination between values.
524   DenseMap<Value *, Value *> CachedCollapsedShadows;
525   DenseMap<Value *, std::set<Value *>> ShadowElements;
526 
527   DFSanFunction(DataFlowSanitizer &DFS, Function *F, bool IsNativeABI)
528       : DFS(DFS), F(F), IA(DFS.getInstrumentedABI()), IsNativeABI(IsNativeABI) {
529     DT.recalculate(*F);
530     // FIXME: Need to track down the register allocator issue which causes poor
531     // performance in pathological cases with large numbers of basic blocks.
532     AvoidNewBlocks = F->size() > 1000;
533   }
534 
535   /// Computes the shadow address for a given function argument.
536   ///
537   /// Shadow = ArgTLS+ArgOffset.
538   Value *getArgTLS(Type *T, unsigned ArgOffset, IRBuilder<> &IRB);
539 
540   /// Computes the shadow address for a return value.
541   Value *getRetvalTLS(Type *T, IRBuilder<> &IRB);
542 
543   /// Computes the origin address for a given function argument.
544   ///
545   /// Origin = ArgOriginTLS[ArgNo].
546   Value *getArgOriginTLS(unsigned ArgNo, IRBuilder<> &IRB);
547 
548   /// Computes the origin address for a return value.
549   Value *getRetvalOriginTLS();
550 
551   Value *getOrigin(Value *V);
552   void setOrigin(Instruction *I, Value *Origin);
553   /// Generates IR to compute the origin of the last operand with a taint label.
554   Value *combineOperandOrigins(Instruction *Inst);
555   /// Before the instruction Pos, generates IR to compute the last origin with a
556   /// taint label. Labels and origins are from vectors Shadows and Origins
557   /// correspondingly. The generated IR is like
558   ///   Sn-1 != Zero ? On-1: ... S2 != Zero ? O2: S1 != Zero ? O1: O0
559   /// When Zero is nullptr, it uses ZeroPrimitiveShadow. Otherwise it can be
560   /// zeros with other bitwidths.
561   Value *combineOrigins(const std::vector<Value *> &Shadows,
562                         const std::vector<Value *> &Origins, Instruction *Pos,
563                         ConstantInt *Zero = nullptr);
564 
565   Value *getShadow(Value *V);
566   void setShadow(Instruction *I, Value *Shadow);
567   /// Generates IR to compute the union of the two given shadows, inserting it
568   /// before Pos. The combined value is with primitive type.
569   Value *combineShadows(Value *V1, Value *V2, Instruction *Pos);
570   /// Combines the shadow values of V1 and V2, then converts the combined value
571   /// with primitive type into a shadow value with the original type T.
572   Value *combineShadowsThenConvert(Type *T, Value *V1, Value *V2,
573                                    Instruction *Pos);
574   Value *combineOperandShadows(Instruction *Inst);
575   Value *loadShadow(Value *ShadowAddr, uint64_t Size, uint64_t Align,
576                     Instruction *Pos);
577   void storePrimitiveShadow(Value *Addr, uint64_t Size, Align Alignment,
578                             Value *PrimitiveShadow, Instruction *Pos);
579   /// Applies PrimitiveShadow to all primitive subtypes of T, returning
580   /// the expanded shadow value.
581   ///
582   /// EFP({T1,T2, ...}, PS) = {EFP(T1,PS),EFP(T2,PS),...}
583   /// EFP([n x T], PS) = [n x EFP(T,PS)]
584   /// EFP(other types, PS) = PS
585   Value *expandFromPrimitiveShadow(Type *T, Value *PrimitiveShadow,
586                                    Instruction *Pos);
587   /// Collapses Shadow into a single primitive shadow value, unioning all
588   /// primitive shadow values in the process. Returns the final primitive
589   /// shadow value.
590   ///
591   /// CTP({V1,V2, ...}) = UNION(CFP(V1,PS),CFP(V2,PS),...)
592   /// CTP([V1,V2,...]) = UNION(CFP(V1,PS),CFP(V2,PS),...)
593   /// CTP(other types, PS) = PS
594   Value *collapseToPrimitiveShadow(Value *Shadow, Instruction *Pos);
595 
596 private:
597   /// Collapses the shadow with aggregate type into a single primitive shadow
598   /// value.
599   template <class AggregateType>
600   Value *collapseAggregateShadow(AggregateType *AT, Value *Shadow,
601                                  IRBuilder<> &IRB);
602 
603   Value *collapseToPrimitiveShadow(Value *Shadow, IRBuilder<> &IRB);
604 
605   /// Returns the shadow value of an argument A.
606   Value *getShadowForTLSArgument(Argument *A);
607 
608   /// The fast path of loading shadow in legacy mode.
609   Value *loadLegacyShadowFast(Value *ShadowAddr, uint64_t Size,
610                               Align ShadowAlign, Instruction *Pos);
611 
612   /// The fast path of loading shadow in fast-16-label mode.
613   Value *loadFast16ShadowFast(Value *ShadowAddr, uint64_t Size,
614                               Align ShadowAlign, Instruction *Pos);
615 };
616 
617 class DFSanVisitor : public InstVisitor<DFSanVisitor> {
618 public:
619   DFSanFunction &DFSF;
620 
621   DFSanVisitor(DFSanFunction &DFSF) : DFSF(DFSF) {}
622 
623   const DataLayout &getDataLayout() const {
624     return DFSF.F->getParent()->getDataLayout();
625   }
626 
627   // Combines shadow values and origins for all of I's operands.
628   void visitInstOperands(Instruction &I);
629 
630   void visitUnaryOperator(UnaryOperator &UO);
631   void visitBinaryOperator(BinaryOperator &BO);
632   void visitCastInst(CastInst &CI);
633   void visitCmpInst(CmpInst &CI);
634   void visitGetElementPtrInst(GetElementPtrInst &GEPI);
635   void visitLoadInst(LoadInst &LI);
636   void visitStoreInst(StoreInst &SI);
637   void visitReturnInst(ReturnInst &RI);
638   void visitCallBase(CallBase &CB);
639   void visitPHINode(PHINode &PN);
640   void visitExtractElementInst(ExtractElementInst &I);
641   void visitInsertElementInst(InsertElementInst &I);
642   void visitShuffleVectorInst(ShuffleVectorInst &I);
643   void visitExtractValueInst(ExtractValueInst &I);
644   void visitInsertValueInst(InsertValueInst &I);
645   void visitAllocaInst(AllocaInst &I);
646   void visitSelectInst(SelectInst &I);
647   void visitMemSetInst(MemSetInst &I);
648   void visitMemTransferInst(MemTransferInst &I);
649 
650 private:
651   // Returns false when this is an invoke of a custom function.
652   bool visitWrappedCallBase(Function &F, CallBase &CB);
653 
654   // Combines origins for all of I's operands.
655   void visitInstOperandOrigins(Instruction &I);
656 };
657 
658 } // end anonymous namespace
659 
660 DataFlowSanitizer::DataFlowSanitizer(
661     const std::vector<std::string> &ABIListFiles) {
662   std::vector<std::string> AllABIListFiles(std::move(ABIListFiles));
663   llvm::append_range(AllABIListFiles, ClABIListFiles);
664   // FIXME: should we propagate vfs::FileSystem to this constructor?
665   ABIList.set(
666       SpecialCaseList::createOrDie(AllABIListFiles, *vfs::getRealFileSystem()));
667 }
668 
669 FunctionType *DataFlowSanitizer::getArgsFunctionType(FunctionType *T) {
670   SmallVector<Type *, 4> ArgTypes(T->param_begin(), T->param_end());
671   ArgTypes.append(T->getNumParams(), PrimitiveShadowTy);
672   if (T->isVarArg())
673     ArgTypes.push_back(PrimitiveShadowPtrTy);
674   Type *RetType = T->getReturnType();
675   if (!RetType->isVoidTy())
676     RetType = StructType::get(RetType, PrimitiveShadowTy);
677   return FunctionType::get(RetType, ArgTypes, T->isVarArg());
678 }
679 
680 FunctionType *DataFlowSanitizer::getTrampolineFunctionType(FunctionType *T) {
681   assert(!T->isVarArg());
682   SmallVector<Type *, 4> ArgTypes;
683   ArgTypes.push_back(T->getPointerTo());
684   ArgTypes.append(T->param_begin(), T->param_end());
685   ArgTypes.append(T->getNumParams(), PrimitiveShadowTy);
686   Type *RetType = T->getReturnType();
687   if (!RetType->isVoidTy())
688     ArgTypes.push_back(PrimitiveShadowPtrTy);
689   return FunctionType::get(T->getReturnType(), ArgTypes, false);
690 }
691 
692 TransformedFunction DataFlowSanitizer::getCustomFunctionType(FunctionType *T) {
693   SmallVector<Type *, 4> ArgTypes;
694 
695   // Some parameters of the custom function being constructed are
696   // parameters of T.  Record the mapping from parameters of T to
697   // parameters of the custom function, so that parameter attributes
698   // at call sites can be updated.
699   std::vector<unsigned> ArgumentIndexMapping;
700   for (unsigned i = 0, ie = T->getNumParams(); i != ie; ++i) {
701     Type* param_type = T->getParamType(i);
702     FunctionType *FT;
703     if (isa<PointerType>(param_type) && (FT = dyn_cast<FunctionType>(
704             cast<PointerType>(param_type)->getElementType()))) {
705       ArgumentIndexMapping.push_back(ArgTypes.size());
706       ArgTypes.push_back(getTrampolineFunctionType(FT)->getPointerTo());
707       ArgTypes.push_back(Type::getInt8PtrTy(*Ctx));
708     } else {
709       ArgumentIndexMapping.push_back(ArgTypes.size());
710       ArgTypes.push_back(param_type);
711     }
712   }
713   for (unsigned i = 0, e = T->getNumParams(); i != e; ++i)
714     ArgTypes.push_back(PrimitiveShadowTy);
715   if (T->isVarArg())
716     ArgTypes.push_back(PrimitiveShadowPtrTy);
717   Type *RetType = T->getReturnType();
718   if (!RetType->isVoidTy())
719     ArgTypes.push_back(PrimitiveShadowPtrTy);
720   return TransformedFunction(
721       T, FunctionType::get(T->getReturnType(), ArgTypes, T->isVarArg()),
722       ArgumentIndexMapping);
723 }
724 
725 bool DataFlowSanitizer::isZeroShadow(Value *V) {
726   if (!shouldTrackFieldsAndIndices())
727     return ZeroPrimitiveShadow == V;
728 
729   Type *T = V->getType();
730   if (!isa<ArrayType>(T) && !isa<StructType>(T)) {
731     if (const ConstantInt *CI = dyn_cast<ConstantInt>(V))
732       return CI->isZero();
733     return false;
734   }
735 
736   return isa<ConstantAggregateZero>(V);
737 }
738 
739 bool DataFlowSanitizer::shouldTrackOrigins() {
740   return ClTrackOrigins && getInstrumentedABI() == DataFlowSanitizer::IA_TLS &&
741          ClFast16Labels;
742 }
743 
744 bool DataFlowSanitizer::shouldTrackFieldsAndIndices() {
745   return getInstrumentedABI() == DataFlowSanitizer::IA_TLS && ClFast16Labels;
746 }
747 
748 Constant *DataFlowSanitizer::getZeroShadow(Type *OrigTy) {
749   if (!shouldTrackFieldsAndIndices())
750     return ZeroPrimitiveShadow;
751 
752   if (!isa<ArrayType>(OrigTy) && !isa<StructType>(OrigTy))
753     return ZeroPrimitiveShadow;
754   Type *ShadowTy = getShadowTy(OrigTy);
755   return ConstantAggregateZero::get(ShadowTy);
756 }
757 
758 Constant *DataFlowSanitizer::getZeroShadow(Value *V) {
759   return getZeroShadow(V->getType());
760 }
761 
762 static Value *expandFromPrimitiveShadowRecursive(
763     Value *Shadow, SmallVector<unsigned, 4> &Indices, Type *SubShadowTy,
764     Value *PrimitiveShadow, IRBuilder<> &IRB) {
765   if (!isa<ArrayType>(SubShadowTy) && !isa<StructType>(SubShadowTy))
766     return IRB.CreateInsertValue(Shadow, PrimitiveShadow, Indices);
767 
768   if (ArrayType *AT = dyn_cast<ArrayType>(SubShadowTy)) {
769     for (unsigned Idx = 0; Idx < AT->getNumElements(); Idx++) {
770       Indices.push_back(Idx);
771       Shadow = expandFromPrimitiveShadowRecursive(
772           Shadow, Indices, AT->getElementType(), PrimitiveShadow, IRB);
773       Indices.pop_back();
774     }
775     return Shadow;
776   }
777 
778   if (StructType *ST = dyn_cast<StructType>(SubShadowTy)) {
779     for (unsigned Idx = 0; Idx < ST->getNumElements(); Idx++) {
780       Indices.push_back(Idx);
781       Shadow = expandFromPrimitiveShadowRecursive(
782           Shadow, Indices, ST->getElementType(Idx), PrimitiveShadow, IRB);
783       Indices.pop_back();
784     }
785     return Shadow;
786   }
787   llvm_unreachable("Unexpected shadow type");
788 }
789 
790 Value *DFSanFunction::expandFromPrimitiveShadow(Type *T, Value *PrimitiveShadow,
791                                                 Instruction *Pos) {
792   Type *ShadowTy = DFS.getShadowTy(T);
793 
794   if (!isa<ArrayType>(ShadowTy) && !isa<StructType>(ShadowTy))
795     return PrimitiveShadow;
796 
797   if (DFS.isZeroShadow(PrimitiveShadow))
798     return DFS.getZeroShadow(ShadowTy);
799 
800   IRBuilder<> IRB(Pos);
801   SmallVector<unsigned, 4> Indices;
802   Value *Shadow = UndefValue::get(ShadowTy);
803   Shadow = expandFromPrimitiveShadowRecursive(Shadow, Indices, ShadowTy,
804                                               PrimitiveShadow, IRB);
805 
806   // Caches the primitive shadow value that built the shadow value.
807   CachedCollapsedShadows[Shadow] = PrimitiveShadow;
808   return Shadow;
809 }
810 
811 template <class AggregateType>
812 Value *DFSanFunction::collapseAggregateShadow(AggregateType *AT, Value *Shadow,
813                                               IRBuilder<> &IRB) {
814   if (!AT->getNumElements())
815     return DFS.ZeroPrimitiveShadow;
816 
817   Value *FirstItem = IRB.CreateExtractValue(Shadow, 0);
818   Value *Aggregator = collapseToPrimitiveShadow(FirstItem, IRB);
819 
820   for (unsigned Idx = 1; Idx < AT->getNumElements(); Idx++) {
821     Value *ShadowItem = IRB.CreateExtractValue(Shadow, Idx);
822     Value *ShadowInner = collapseToPrimitiveShadow(ShadowItem, IRB);
823     Aggregator = IRB.CreateOr(Aggregator, ShadowInner);
824   }
825   return Aggregator;
826 }
827 
828 Value *DFSanFunction::collapseToPrimitiveShadow(Value *Shadow,
829                                                 IRBuilder<> &IRB) {
830   Type *ShadowTy = Shadow->getType();
831   if (!isa<ArrayType>(ShadowTy) && !isa<StructType>(ShadowTy))
832     return Shadow;
833   if (ArrayType *AT = dyn_cast<ArrayType>(ShadowTy))
834     return collapseAggregateShadow<>(AT, Shadow, IRB);
835   if (StructType *ST = dyn_cast<StructType>(ShadowTy))
836     return collapseAggregateShadow<>(ST, Shadow, IRB);
837   llvm_unreachable("Unexpected shadow type");
838 }
839 
840 Value *DFSanFunction::collapseToPrimitiveShadow(Value *Shadow,
841                                                 Instruction *Pos) {
842   Type *ShadowTy = Shadow->getType();
843   if (!isa<ArrayType>(ShadowTy) && !isa<StructType>(ShadowTy))
844     return Shadow;
845 
846   assert(DFS.shouldTrackFieldsAndIndices());
847 
848   // Checks if the cached collapsed shadow value dominates Pos.
849   Value *&CS = CachedCollapsedShadows[Shadow];
850   if (CS && DT.dominates(CS, Pos))
851     return CS;
852 
853   IRBuilder<> IRB(Pos);
854   Value *PrimitiveShadow = collapseToPrimitiveShadow(Shadow, IRB);
855   // Caches the converted primitive shadow value.
856   CS = PrimitiveShadow;
857   return PrimitiveShadow;
858 }
859 
860 Type *DataFlowSanitizer::getShadowTy(Type *OrigTy) {
861   if (!shouldTrackFieldsAndIndices())
862     return PrimitiveShadowTy;
863 
864   if (!OrigTy->isSized())
865     return PrimitiveShadowTy;
866   if (isa<IntegerType>(OrigTy))
867     return PrimitiveShadowTy;
868   if (isa<VectorType>(OrigTy))
869     return PrimitiveShadowTy;
870   if (ArrayType *AT = dyn_cast<ArrayType>(OrigTy))
871     return ArrayType::get(getShadowTy(AT->getElementType()),
872                           AT->getNumElements());
873   if (StructType *ST = dyn_cast<StructType>(OrigTy)) {
874     SmallVector<Type *, 4> Elements;
875     for (unsigned I = 0, N = ST->getNumElements(); I < N; ++I)
876       Elements.push_back(getShadowTy(ST->getElementType(I)));
877     return StructType::get(*Ctx, Elements);
878   }
879   return PrimitiveShadowTy;
880 }
881 
882 Type *DataFlowSanitizer::getShadowTy(Value *V) {
883   return getShadowTy(V->getType());
884 }
885 
886 bool DataFlowSanitizer::init(Module &M) {
887   Triple TargetTriple(M.getTargetTriple());
888   bool IsX86_64 = TargetTriple.getArch() == Triple::x86_64;
889   bool IsMIPS64 = TargetTriple.isMIPS64();
890   bool IsAArch64 = TargetTriple.getArch() == Triple::aarch64 ||
891                    TargetTriple.getArch() == Triple::aarch64_be;
892 
893   const DataLayout &DL = M.getDataLayout();
894 
895   Mod = &M;
896   Ctx = &M.getContext();
897   Int8Ptr = Type::getInt8PtrTy(*Ctx);
898   OriginTy = IntegerType::get(*Ctx, OriginWidthBits);
899   OriginPtrTy = PointerType::getUnqual(OriginTy);
900   PrimitiveShadowTy = IntegerType::get(*Ctx, ShadowWidthBits);
901   PrimitiveShadowPtrTy = PointerType::getUnqual(PrimitiveShadowTy);
902   IntptrTy = DL.getIntPtrType(*Ctx);
903   ZeroPrimitiveShadow = ConstantInt::getSigned(PrimitiveShadowTy, 0);
904   ShadowPtrMul = ConstantInt::getSigned(IntptrTy, ShadowWidthBytes);
905   OriginBase = ConstantInt::get(IntptrTy, 0x200000000000LL);
906   ZeroOrigin = ConstantInt::getSigned(OriginTy, 0);
907   if (IsX86_64)
908     ShadowPtrMask = ConstantInt::getSigned(IntptrTy, ~0x700000000000LL);
909   else if (IsMIPS64)
910     ShadowPtrMask = ConstantInt::getSigned(IntptrTy, ~0xF000000000LL);
911   // AArch64 supports multiple VMAs and the shadow mask is set at runtime.
912   else if (IsAArch64)
913     DFSanRuntimeShadowMask = true;
914   else
915     report_fatal_error("unsupported triple");
916 
917   Type *DFSanUnionArgs[2] = {PrimitiveShadowTy, PrimitiveShadowTy};
918   DFSanUnionFnTy =
919       FunctionType::get(PrimitiveShadowTy, DFSanUnionArgs, /*isVarArg=*/false);
920   Type *DFSanUnionLoadArgs[2] = {PrimitiveShadowPtrTy, IntptrTy};
921   DFSanUnionLoadFnTy = FunctionType::get(PrimitiveShadowTy, DFSanUnionLoadArgs,
922                                          /*isVarArg=*/false);
923   Type *DFSanLoadLabelAndOriginArgs[2] = {Int8Ptr, IntptrTy};
924   DFSanLoadLabelAndOriginFnTy =
925       FunctionType::get(IntegerType::get(*Ctx, 64), DFSanLoadLabelAndOriginArgs,
926                         /*isVarArg=*/false);
927   DFSanUnimplementedFnTy = FunctionType::get(
928       Type::getVoidTy(*Ctx), Type::getInt8PtrTy(*Ctx), /*isVarArg=*/false);
929   Type *DFSanSetLabelArgs[3] = {PrimitiveShadowTy, Type::getInt8PtrTy(*Ctx),
930                                 IntptrTy};
931   DFSanSetLabelFnTy = FunctionType::get(Type::getVoidTy(*Ctx),
932                                         DFSanSetLabelArgs, /*isVarArg=*/false);
933   DFSanNonzeroLabelFnTy =
934       FunctionType::get(Type::getVoidTy(*Ctx), None, /*isVarArg=*/false);
935   DFSanVarargWrapperFnTy = FunctionType::get(
936       Type::getVoidTy(*Ctx), Type::getInt8PtrTy(*Ctx), /*isVarArg=*/false);
937   DFSanCmpCallbackFnTy =
938       FunctionType::get(Type::getVoidTy(*Ctx), PrimitiveShadowTy,
939                         /*isVarArg=*/false);
940   DFSanChainOriginFnTy =
941       FunctionType::get(OriginTy, OriginTy, /*isVarArg=*/false);
942   Type *DFSanMaybeStoreOriginArgs[4] = {IntegerType::get(*Ctx, ShadowWidthBits),
943                                         Int8Ptr, IntptrTy, OriginTy};
944   DFSanMaybeStoreOriginFnTy = FunctionType::get(
945       Type::getVoidTy(*Ctx), DFSanMaybeStoreOriginArgs, /*isVarArg=*/false);
946   Type *DFSanMemOriginTransferArgs[3] = {Int8Ptr, Int8Ptr, IntptrTy};
947   DFSanMemOriginTransferFnTy = FunctionType::get(
948       Type::getVoidTy(*Ctx), DFSanMemOriginTransferArgs, /*isVarArg=*/false);
949   Type *DFSanLoadStoreCallbackArgs[2] = {PrimitiveShadowTy, Int8Ptr};
950   DFSanLoadStoreCallbackFnTy =
951       FunctionType::get(Type::getVoidTy(*Ctx), DFSanLoadStoreCallbackArgs,
952                         /*isVarArg=*/false);
953   Type *DFSanMemTransferCallbackArgs[2] = {PrimitiveShadowPtrTy, IntptrTy};
954   DFSanMemTransferCallbackFnTy =
955       FunctionType::get(Type::getVoidTy(*Ctx), DFSanMemTransferCallbackArgs,
956                         /*isVarArg=*/false);
957 
958   ColdCallWeights = MDBuilder(*Ctx).createBranchWeights(1, 1000);
959   return true;
960 }
961 
962 bool DataFlowSanitizer::isInstrumented(const Function *F) {
963   return !ABIList.isIn(*F, "uninstrumented");
964 }
965 
966 bool DataFlowSanitizer::isInstrumented(const GlobalAlias *GA) {
967   return !ABIList.isIn(*GA, "uninstrumented");
968 }
969 
970 DataFlowSanitizer::InstrumentedABI DataFlowSanitizer::getInstrumentedABI() {
971   return ClArgsABI ? IA_Args : IA_TLS;
972 }
973 
974 DataFlowSanitizer::WrapperKind DataFlowSanitizer::getWrapperKind(Function *F) {
975   if (ABIList.isIn(*F, "functional"))
976     return WK_Functional;
977   if (ABIList.isIn(*F, "discard"))
978     return WK_Discard;
979   if (ABIList.isIn(*F, "custom"))
980     return WK_Custom;
981 
982   return WK_Warning;
983 }
984 
985 void DataFlowSanitizer::addGlobalNamePrefix(GlobalValue *GV) {
986   std::string GVName = std::string(GV->getName()), Prefix = "dfs$";
987   GV->setName(Prefix + GVName);
988 
989   // Try to change the name of the function in module inline asm.  We only do
990   // this for specific asm directives, currently only ".symver", to try to avoid
991   // corrupting asm which happens to contain the symbol name as a substring.
992   // Note that the substitution for .symver assumes that the versioned symbol
993   // also has an instrumented name.
994   std::string Asm = GV->getParent()->getModuleInlineAsm();
995   std::string SearchStr = ".symver " + GVName + ",";
996   size_t Pos = Asm.find(SearchStr);
997   if (Pos != std::string::npos) {
998     Asm.replace(Pos, SearchStr.size(),
999                 ".symver " + Prefix + GVName + "," + Prefix);
1000     GV->getParent()->setModuleInlineAsm(Asm);
1001   }
1002 }
1003 
1004 Function *
1005 DataFlowSanitizer::buildWrapperFunction(Function *F, StringRef NewFName,
1006                                         GlobalValue::LinkageTypes NewFLink,
1007                                         FunctionType *NewFT) {
1008   FunctionType *FT = F->getFunctionType();
1009   Function *NewF = Function::Create(NewFT, NewFLink, F->getAddressSpace(),
1010                                     NewFName, F->getParent());
1011   NewF->copyAttributesFrom(F);
1012   NewF->removeAttributes(
1013       AttributeList::ReturnIndex,
1014       AttributeFuncs::typeIncompatible(NewFT->getReturnType()));
1015 
1016   BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", NewF);
1017   if (F->isVarArg()) {
1018     NewF->removeAttributes(AttributeList::FunctionIndex,
1019                            AttrBuilder().addAttribute("split-stack"));
1020     CallInst::Create(DFSanVarargWrapperFn,
1021                      IRBuilder<>(BB).CreateGlobalStringPtr(F->getName()), "",
1022                      BB);
1023     new UnreachableInst(*Ctx, BB);
1024   } else {
1025     std::vector<Value *> Args;
1026     unsigned n = FT->getNumParams();
1027     for (Function::arg_iterator ai = NewF->arg_begin(); n != 0; ++ai, --n)
1028       Args.push_back(&*ai);
1029     CallInst *CI = CallInst::Create(F, Args, "", BB);
1030     if (FT->getReturnType()->isVoidTy())
1031       ReturnInst::Create(*Ctx, BB);
1032     else
1033       ReturnInst::Create(*Ctx, CI, BB);
1034   }
1035 
1036   return NewF;
1037 }
1038 
1039 Constant *DataFlowSanitizer::getOrBuildTrampolineFunction(FunctionType *FT,
1040                                                           StringRef FName) {
1041   FunctionType *FTT = getTrampolineFunctionType(FT);
1042   FunctionCallee C = Mod->getOrInsertFunction(FName, FTT);
1043   Function *F = dyn_cast<Function>(C.getCallee());
1044   if (F && F->isDeclaration()) {
1045     F->setLinkage(GlobalValue::LinkOnceODRLinkage);
1046     BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", F);
1047     std::vector<Value *> Args;
1048     Function::arg_iterator AI = F->arg_begin(); ++AI;
1049     for (unsigned N = FT->getNumParams(); N != 0; ++AI, --N)
1050       Args.push_back(&*AI);
1051     CallInst *CI = CallInst::Create(FT, &*F->arg_begin(), Args, "", BB);
1052     ReturnInst *RI;
1053     if (FT->getReturnType()->isVoidTy())
1054       RI = ReturnInst::Create(*Ctx, BB);
1055     else
1056       RI = ReturnInst::Create(*Ctx, CI, BB);
1057 
1058     // F is called by a wrapped custom function with primitive shadows. So
1059     // its arguments and return value need conversion.
1060     DFSanFunction DFSF(*this, F, /*IsNativeABI=*/true);
1061     Function::arg_iterator ValAI = F->arg_begin(), ShadowAI = AI; ++ValAI;
1062     for (unsigned N = FT->getNumParams(); N != 0; ++ValAI, ++ShadowAI, --N) {
1063       Value *Shadow =
1064           DFSF.expandFromPrimitiveShadow(ValAI->getType(), &*ShadowAI, CI);
1065       DFSF.ValShadowMap[&*ValAI] = Shadow;
1066     }
1067     DFSanVisitor(DFSF).visitCallInst(*CI);
1068     if (!FT->getReturnType()->isVoidTy()) {
1069       Value *PrimitiveShadow = DFSF.collapseToPrimitiveShadow(
1070           DFSF.getShadow(RI->getReturnValue()), RI);
1071       new StoreInst(PrimitiveShadow, &*std::prev(F->arg_end()), RI);
1072     }
1073   }
1074 
1075   return cast<Constant>(C.getCallee());
1076 }
1077 
1078 // Initialize DataFlowSanitizer runtime functions and declare them in the module
1079 void DataFlowSanitizer::initializeRuntimeFunctions(Module &M) {
1080   {
1081     AttributeList AL;
1082     AL = AL.addAttribute(M.getContext(), AttributeList::FunctionIndex,
1083                          Attribute::NoUnwind);
1084     AL = AL.addAttribute(M.getContext(), AttributeList::FunctionIndex,
1085                          Attribute::ReadNone);
1086     AL = AL.addAttribute(M.getContext(), AttributeList::ReturnIndex,
1087                          Attribute::ZExt);
1088     AL = AL.addParamAttribute(M.getContext(), 0, Attribute::ZExt);
1089     AL = AL.addParamAttribute(M.getContext(), 1, Attribute::ZExt);
1090     DFSanUnionFn =
1091         Mod->getOrInsertFunction("__dfsan_union", DFSanUnionFnTy, AL);
1092   }
1093   {
1094     AttributeList AL;
1095     AL = AL.addAttribute(M.getContext(), AttributeList::FunctionIndex,
1096                          Attribute::NoUnwind);
1097     AL = AL.addAttribute(M.getContext(), AttributeList::FunctionIndex,
1098                          Attribute::ReadNone);
1099     AL = AL.addAttribute(M.getContext(), AttributeList::ReturnIndex,
1100                          Attribute::ZExt);
1101     AL = AL.addParamAttribute(M.getContext(), 0, Attribute::ZExt);
1102     AL = AL.addParamAttribute(M.getContext(), 1, Attribute::ZExt);
1103     DFSanCheckedUnionFn =
1104         Mod->getOrInsertFunction("dfsan_union", DFSanUnionFnTy, AL);
1105   }
1106   {
1107     AttributeList AL;
1108     AL = AL.addAttribute(M.getContext(), AttributeList::FunctionIndex,
1109                          Attribute::NoUnwind);
1110     AL = AL.addAttribute(M.getContext(), AttributeList::FunctionIndex,
1111                          Attribute::ReadOnly);
1112     AL = AL.addAttribute(M.getContext(), AttributeList::ReturnIndex,
1113                          Attribute::ZExt);
1114     DFSanUnionLoadFn =
1115         Mod->getOrInsertFunction("__dfsan_union_load", DFSanUnionLoadFnTy, AL);
1116   }
1117   {
1118     AttributeList AL;
1119     AL = AL.addAttribute(M.getContext(), AttributeList::FunctionIndex,
1120                          Attribute::NoUnwind);
1121     AL = AL.addAttribute(M.getContext(), AttributeList::FunctionIndex,
1122                          Attribute::ReadOnly);
1123     AL = AL.addAttribute(M.getContext(), AttributeList::ReturnIndex,
1124                          Attribute::ZExt);
1125     DFSanUnionLoadFast16LabelsFn = Mod->getOrInsertFunction(
1126         "__dfsan_union_load_fast16labels", DFSanUnionLoadFnTy, AL);
1127   }
1128   {
1129     AttributeList AL;
1130     AL = AL.addAttribute(M.getContext(), AttributeList::FunctionIndex,
1131                          Attribute::NoUnwind);
1132     AL = AL.addAttribute(M.getContext(), AttributeList::FunctionIndex,
1133                          Attribute::ReadOnly);
1134     AL = AL.addAttribute(M.getContext(), AttributeList::ReturnIndex,
1135                          Attribute::ZExt);
1136     DFSanLoadLabelAndOriginFn = Mod->getOrInsertFunction(
1137         "__dfsan_load_label_and_origin", DFSanLoadLabelAndOriginFnTy, AL);
1138   }
1139   DFSanUnimplementedFn =
1140       Mod->getOrInsertFunction("__dfsan_unimplemented", DFSanUnimplementedFnTy);
1141   {
1142     AttributeList AL;
1143     AL = AL.addParamAttribute(M.getContext(), 0, Attribute::ZExt);
1144     DFSanSetLabelFn =
1145         Mod->getOrInsertFunction("__dfsan_set_label", DFSanSetLabelFnTy, AL);
1146   }
1147   DFSanNonzeroLabelFn =
1148       Mod->getOrInsertFunction("__dfsan_nonzero_label", DFSanNonzeroLabelFnTy);
1149   DFSanVarargWrapperFn = Mod->getOrInsertFunction("__dfsan_vararg_wrapper",
1150                                                   DFSanVarargWrapperFnTy);
1151   {
1152     AttributeList AL;
1153     AL = AL.addParamAttribute(M.getContext(), 0, Attribute::ZExt);
1154     AL = AL.addAttribute(M.getContext(), AttributeList::ReturnIndex,
1155                          Attribute::ZExt);
1156     DFSanChainOriginFn = Mod->getOrInsertFunction("__dfsan_chain_origin",
1157                                                   DFSanChainOriginFnTy, AL);
1158   }
1159   DFSanMemOriginTransferFn = Mod->getOrInsertFunction(
1160       "__dfsan_mem_origin_transfer", DFSanMemOriginTransferFnTy);
1161 
1162   {
1163     AttributeList AL;
1164     AL = AL.addParamAttribute(M.getContext(), 0, Attribute::ZExt);
1165     AL = AL.addParamAttribute(M.getContext(), 3, Attribute::ZExt);
1166     DFSanMaybeStoreOriginFn = Mod->getOrInsertFunction(
1167         "__dfsan_maybe_store_origin", DFSanMaybeStoreOriginFnTy, AL);
1168   }
1169 
1170   DFSanRuntimeFunctions.insert(DFSanUnionFn.getCallee()->stripPointerCasts());
1171   DFSanRuntimeFunctions.insert(
1172       DFSanCheckedUnionFn.getCallee()->stripPointerCasts());
1173   DFSanRuntimeFunctions.insert(
1174       DFSanUnionLoadFn.getCallee()->stripPointerCasts());
1175   DFSanRuntimeFunctions.insert(
1176       DFSanUnionLoadFast16LabelsFn.getCallee()->stripPointerCasts());
1177   DFSanRuntimeFunctions.insert(
1178       DFSanLoadLabelAndOriginFn.getCallee()->stripPointerCasts());
1179   DFSanRuntimeFunctions.insert(
1180       DFSanUnimplementedFn.getCallee()->stripPointerCasts());
1181   DFSanRuntimeFunctions.insert(
1182       DFSanSetLabelFn.getCallee()->stripPointerCasts());
1183   DFSanRuntimeFunctions.insert(
1184       DFSanNonzeroLabelFn.getCallee()->stripPointerCasts());
1185   DFSanRuntimeFunctions.insert(
1186       DFSanVarargWrapperFn.getCallee()->stripPointerCasts());
1187   DFSanRuntimeFunctions.insert(
1188       DFSanLoadCallbackFn.getCallee()->stripPointerCasts());
1189   DFSanRuntimeFunctions.insert(
1190       DFSanStoreCallbackFn.getCallee()->stripPointerCasts());
1191   DFSanRuntimeFunctions.insert(
1192       DFSanMemTransferCallbackFn.getCallee()->stripPointerCasts());
1193   DFSanRuntimeFunctions.insert(
1194       DFSanCmpCallbackFn.getCallee()->stripPointerCasts());
1195   DFSanRuntimeFunctions.insert(
1196       DFSanChainOriginFn.getCallee()->stripPointerCasts());
1197   DFSanRuntimeFunctions.insert(
1198       DFSanMemOriginTransferFn.getCallee()->stripPointerCasts());
1199   DFSanRuntimeFunctions.insert(
1200       DFSanMaybeStoreOriginFn.getCallee()->stripPointerCasts());
1201 }
1202 
1203 // Initializes event callback functions and declare them in the module
1204 void DataFlowSanitizer::initializeCallbackFunctions(Module &M) {
1205   DFSanLoadCallbackFn = Mod->getOrInsertFunction("__dfsan_load_callback",
1206                                                  DFSanLoadStoreCallbackFnTy);
1207   DFSanStoreCallbackFn = Mod->getOrInsertFunction("__dfsan_store_callback",
1208                                                   DFSanLoadStoreCallbackFnTy);
1209   DFSanMemTransferCallbackFn = Mod->getOrInsertFunction(
1210       "__dfsan_mem_transfer_callback", DFSanMemTransferCallbackFnTy);
1211   DFSanCmpCallbackFn =
1212       Mod->getOrInsertFunction("__dfsan_cmp_callback", DFSanCmpCallbackFnTy);
1213 }
1214 
1215 bool DataFlowSanitizer::runImpl(Module &M) {
1216   init(M);
1217 
1218   if (ABIList.isIn(M, "skip"))
1219     return false;
1220 
1221   const unsigned InitialGlobalSize = M.global_size();
1222   const unsigned InitialModuleSize = M.size();
1223 
1224   bool Changed = false;
1225 
1226   auto getOrInsertGlobal = [this, &Changed](StringRef Name,
1227                                             Type *Ty) -> Constant * {
1228     Constant *C = Mod->getOrInsertGlobal(Name, Ty);
1229     if (GlobalVariable *G = dyn_cast<GlobalVariable>(C)) {
1230       Changed |= G->getThreadLocalMode() != GlobalVariable::InitialExecTLSModel;
1231       G->setThreadLocalMode(GlobalVariable::InitialExecTLSModel);
1232     }
1233     return C;
1234   };
1235 
1236   // These globals must be kept in sync with the ones in dfsan.cpp.
1237   ArgTLS = getOrInsertGlobal(
1238       "__dfsan_arg_tls",
1239       ArrayType::get(Type::getInt64Ty(*Ctx), kArgTLSSize / 8));
1240   RetvalTLS = getOrInsertGlobal(
1241       "__dfsan_retval_tls",
1242       ArrayType::get(Type::getInt64Ty(*Ctx), kRetvalTLSSize / 8));
1243   ArgOriginTLSTy = ArrayType::get(OriginTy, kNumOfElementsInArgOrgTLS);
1244   ArgOriginTLS = getOrInsertGlobal("__dfsan_arg_origin_tls", ArgOriginTLSTy);
1245   RetvalOriginTLS = getOrInsertGlobal("__dfsan_retval_origin_tls", OriginTy);
1246 
1247   (void)Mod->getOrInsertGlobal("__dfsan_track_origins", OriginTy, [&] {
1248     Changed = true;
1249     return new GlobalVariable(
1250         M, OriginTy, true, GlobalValue::WeakODRLinkage,
1251         ConstantInt::getSigned(OriginTy, shouldTrackOrigins()),
1252         "__dfsan_track_origins");
1253   });
1254 
1255   ExternalShadowMask =
1256       Mod->getOrInsertGlobal(kDFSanExternShadowPtrMask, IntptrTy);
1257 
1258   initializeCallbackFunctions(M);
1259   initializeRuntimeFunctions(M);
1260 
1261   std::vector<Function *> FnsToInstrument;
1262   SmallPtrSet<Function *, 2> FnsWithNativeABI;
1263   for (Function &i : M)
1264     if (!i.isIntrinsic() && !DFSanRuntimeFunctions.contains(&i))
1265       FnsToInstrument.push_back(&i);
1266 
1267   // Give function aliases prefixes when necessary, and build wrappers where the
1268   // instrumentedness is inconsistent.
1269   for (Module::alias_iterator i = M.alias_begin(), e = M.alias_end(); i != e;) {
1270     GlobalAlias *GA = &*i;
1271     ++i;
1272     // Don't stop on weak.  We assume people aren't playing games with the
1273     // instrumentedness of overridden weak aliases.
1274     if (auto F = dyn_cast<Function>(GA->getBaseObject())) {
1275       bool GAInst = isInstrumented(GA), FInst = isInstrumented(F);
1276       if (GAInst && FInst) {
1277         addGlobalNamePrefix(GA);
1278       } else if (GAInst != FInst) {
1279         // Non-instrumented alias of an instrumented function, or vice versa.
1280         // Replace the alias with a native-ABI wrapper of the aliasee.  The pass
1281         // below will take care of instrumenting it.
1282         Function *NewF =
1283             buildWrapperFunction(F, "", GA->getLinkage(), F->getFunctionType());
1284         GA->replaceAllUsesWith(ConstantExpr::getBitCast(NewF, GA->getType()));
1285         NewF->takeName(GA);
1286         GA->eraseFromParent();
1287         FnsToInstrument.push_back(NewF);
1288       }
1289     }
1290   }
1291 
1292   ReadOnlyNoneAttrs.addAttribute(Attribute::ReadOnly)
1293       .addAttribute(Attribute::ReadNone);
1294 
1295   // First, change the ABI of every function in the module.  ABI-listed
1296   // functions keep their original ABI and get a wrapper function.
1297   for (std::vector<Function *>::iterator i = FnsToInstrument.begin(),
1298                                          e = FnsToInstrument.end();
1299        i != e; ++i) {
1300     Function &F = **i;
1301     FunctionType *FT = F.getFunctionType();
1302 
1303     bool IsZeroArgsVoidRet = (FT->getNumParams() == 0 && !FT->isVarArg() &&
1304                               FT->getReturnType()->isVoidTy());
1305 
1306     if (isInstrumented(&F)) {
1307       // Instrumented functions get a 'dfs$' prefix.  This allows us to more
1308       // easily identify cases of mismatching ABIs.
1309       if (getInstrumentedABI() == IA_Args && !IsZeroArgsVoidRet) {
1310         FunctionType *NewFT = getArgsFunctionType(FT);
1311         Function *NewF = Function::Create(NewFT, F.getLinkage(),
1312                                           F.getAddressSpace(), "", &M);
1313         NewF->copyAttributesFrom(&F);
1314         NewF->removeAttributes(
1315             AttributeList::ReturnIndex,
1316             AttributeFuncs::typeIncompatible(NewFT->getReturnType()));
1317         for (Function::arg_iterator FArg = F.arg_begin(),
1318                                     NewFArg = NewF->arg_begin(),
1319                                     FArgEnd = F.arg_end();
1320              FArg != FArgEnd; ++FArg, ++NewFArg) {
1321           FArg->replaceAllUsesWith(&*NewFArg);
1322         }
1323         NewF->getBasicBlockList().splice(NewF->begin(), F.getBasicBlockList());
1324 
1325         for (Function::user_iterator UI = F.user_begin(), UE = F.user_end();
1326              UI != UE;) {
1327           BlockAddress *BA = dyn_cast<BlockAddress>(*UI);
1328           ++UI;
1329           if (BA) {
1330             BA->replaceAllUsesWith(
1331                 BlockAddress::get(NewF, BA->getBasicBlock()));
1332             delete BA;
1333           }
1334         }
1335         F.replaceAllUsesWith(
1336             ConstantExpr::getBitCast(NewF, PointerType::getUnqual(FT)));
1337         NewF->takeName(&F);
1338         F.eraseFromParent();
1339         *i = NewF;
1340         addGlobalNamePrefix(NewF);
1341       } else {
1342         addGlobalNamePrefix(&F);
1343       }
1344     } else if (!IsZeroArgsVoidRet || getWrapperKind(&F) == WK_Custom) {
1345       // Build a wrapper function for F.  The wrapper simply calls F, and is
1346       // added to FnsToInstrument so that any instrumentation according to its
1347       // WrapperKind is done in the second pass below.
1348       FunctionType *NewFT = getInstrumentedABI() == IA_Args
1349                                 ? getArgsFunctionType(FT)
1350                                 : FT;
1351 
1352       // If the function being wrapped has local linkage, then preserve the
1353       // function's linkage in the wrapper function.
1354       GlobalValue::LinkageTypes wrapperLinkage =
1355           F.hasLocalLinkage()
1356               ? F.getLinkage()
1357               : GlobalValue::LinkOnceODRLinkage;
1358 
1359       Function *NewF = buildWrapperFunction(
1360           &F, std::string("dfsw$") + std::string(F.getName()),
1361           wrapperLinkage, NewFT);
1362       if (getInstrumentedABI() == IA_TLS)
1363         NewF->removeAttributes(AttributeList::FunctionIndex, ReadOnlyNoneAttrs);
1364 
1365       Value *WrappedFnCst =
1366           ConstantExpr::getBitCast(NewF, PointerType::getUnqual(FT));
1367       F.replaceAllUsesWith(WrappedFnCst);
1368 
1369       UnwrappedFnMap[WrappedFnCst] = &F;
1370       *i = NewF;
1371 
1372       if (!F.isDeclaration()) {
1373         // This function is probably defining an interposition of an
1374         // uninstrumented function and hence needs to keep the original ABI.
1375         // But any functions it may call need to use the instrumented ABI, so
1376         // we instrument it in a mode which preserves the original ABI.
1377         FnsWithNativeABI.insert(&F);
1378 
1379         // This code needs to rebuild the iterators, as they may be invalidated
1380         // by the push_back, taking care that the new range does not include
1381         // any functions added by this code.
1382         size_t N = i - FnsToInstrument.begin(),
1383                Count = e - FnsToInstrument.begin();
1384         FnsToInstrument.push_back(&F);
1385         i = FnsToInstrument.begin() + N;
1386         e = FnsToInstrument.begin() + Count;
1387       }
1388                // Hopefully, nobody will try to indirectly call a vararg
1389                // function... yet.
1390     } else if (FT->isVarArg()) {
1391       UnwrappedFnMap[&F] = &F;
1392       *i = nullptr;
1393     }
1394   }
1395 
1396   for (Function *i : FnsToInstrument) {
1397     if (!i || i->isDeclaration())
1398       continue;
1399 
1400     removeUnreachableBlocks(*i);
1401 
1402     DFSanFunction DFSF(*this, i, FnsWithNativeABI.count(i));
1403 
1404     // DFSanVisitor may create new basic blocks, which confuses df_iterator.
1405     // Build a copy of the list before iterating over it.
1406     SmallVector<BasicBlock *, 4> BBList(depth_first(&i->getEntryBlock()));
1407 
1408     for (BasicBlock *i : BBList) {
1409       Instruction *Inst = &i->front();
1410       while (true) {
1411         // DFSanVisitor may split the current basic block, changing the current
1412         // instruction's next pointer and moving the next instruction to the
1413         // tail block from which we should continue.
1414         Instruction *Next = Inst->getNextNode();
1415         // DFSanVisitor may delete Inst, so keep track of whether it was a
1416         // terminator.
1417         bool IsTerminator = Inst->isTerminator();
1418         if (!DFSF.SkipInsts.count(Inst))
1419           DFSanVisitor(DFSF).visit(Inst);
1420         if (IsTerminator)
1421           break;
1422         Inst = Next;
1423       }
1424     }
1425 
1426     // We will not necessarily be able to compute the shadow for every phi node
1427     // until we have visited every block.  Therefore, the code that handles phi
1428     // nodes adds them to the PHIFixups list so that they can be properly
1429     // handled here.
1430     for (std::vector<std::pair<PHINode *, PHINode *>>::iterator
1431              i = DFSF.PHIFixups.begin(),
1432              e = DFSF.PHIFixups.end();
1433          i != e; ++i) {
1434       for (unsigned val = 0, n = i->first->getNumIncomingValues(); val != n;
1435            ++val) {
1436         i->second->setIncomingValue(
1437             val, DFSF.getShadow(i->first->getIncomingValue(val)));
1438       }
1439     }
1440 
1441     // -dfsan-debug-nonzero-labels will split the CFG in all kinds of crazy
1442     // places (i.e. instructions in basic blocks we haven't even begun visiting
1443     // yet).  To make our life easier, do this work in a pass after the main
1444     // instrumentation.
1445     if (ClDebugNonzeroLabels) {
1446       for (Value *V : DFSF.NonZeroChecks) {
1447         Instruction *Pos;
1448         if (Instruction *I = dyn_cast<Instruction>(V))
1449           Pos = I->getNextNode();
1450         else
1451           Pos = &DFSF.F->getEntryBlock().front();
1452         while (isa<PHINode>(Pos) || isa<AllocaInst>(Pos))
1453           Pos = Pos->getNextNode();
1454         IRBuilder<> IRB(Pos);
1455         Value *PrimitiveShadow = DFSF.collapseToPrimitiveShadow(V, Pos);
1456         Value *Ne =
1457             IRB.CreateICmpNE(PrimitiveShadow, DFSF.DFS.ZeroPrimitiveShadow);
1458         BranchInst *BI = cast<BranchInst>(SplitBlockAndInsertIfThen(
1459             Ne, Pos, /*Unreachable=*/false, ColdCallWeights));
1460         IRBuilder<> ThenIRB(BI);
1461         ThenIRB.CreateCall(DFSF.DFS.DFSanNonzeroLabelFn, {});
1462       }
1463     }
1464   }
1465 
1466   return Changed || !FnsToInstrument.empty() ||
1467          M.global_size() != InitialGlobalSize || M.size() != InitialModuleSize;
1468 }
1469 
1470 Value *DFSanFunction::getArgTLS(Type *T, unsigned ArgOffset, IRBuilder<> &IRB) {
1471   Value *Base = IRB.CreatePointerCast(DFS.ArgTLS, DFS.IntptrTy);
1472   if (ArgOffset)
1473     Base = IRB.CreateAdd(Base, ConstantInt::get(DFS.IntptrTy, ArgOffset));
1474   return IRB.CreateIntToPtr(Base, PointerType::get(DFS.getShadowTy(T), 0),
1475                             "_dfsarg");
1476 }
1477 
1478 Value *DFSanFunction::getRetvalTLS(Type *T, IRBuilder<> &IRB) {
1479   return IRB.CreatePointerCast(
1480       DFS.RetvalTLS, PointerType::get(DFS.getShadowTy(T), 0), "_dfsret");
1481 }
1482 
1483 Value *DFSanFunction::getRetvalOriginTLS() { return DFS.RetvalOriginTLS; }
1484 
1485 Value *DFSanFunction::getArgOriginTLS(unsigned ArgNo, IRBuilder<> &IRB) {
1486   return IRB.CreateConstGEP2_64(DFS.ArgOriginTLSTy, DFS.ArgOriginTLS, 0, ArgNo,
1487                                 "_dfsarg_o");
1488 }
1489 
1490 Value *DFSanFunction::getOrigin(Value *V) {
1491   assert(DFS.shouldTrackOrigins());
1492   if (!isa<Argument>(V) && !isa<Instruction>(V))
1493     return DFS.ZeroOrigin;
1494   Value *&Origin = ValOriginMap[V];
1495   if (!Origin) {
1496     if (Argument *A = dyn_cast<Argument>(V)) {
1497       if (IsNativeABI)
1498         return DFS.ZeroOrigin;
1499       switch (IA) {
1500       case DataFlowSanitizer::IA_TLS: {
1501         if (A->getArgNo() < DFS.kNumOfElementsInArgOrgTLS) {
1502           Instruction *ArgOriginTLSPos = &*F->getEntryBlock().begin();
1503           IRBuilder<> IRB(ArgOriginTLSPos);
1504           Value *ArgOriginPtr = getArgOriginTLS(A->getArgNo(), IRB);
1505           Origin = IRB.CreateLoad(DFS.OriginTy, ArgOriginPtr);
1506         } else {
1507           // Overflow
1508           Origin = DFS.ZeroOrigin;
1509         }
1510         break;
1511       }
1512       case DataFlowSanitizer::IA_Args: {
1513         Origin = DFS.ZeroOrigin;
1514         break;
1515       }
1516       }
1517     } else {
1518       Origin = DFS.ZeroOrigin;
1519     }
1520   }
1521   return Origin;
1522 }
1523 
1524 void DFSanFunction::setOrigin(Instruction *I, Value *Origin) {
1525   if (!DFS.shouldTrackOrigins())
1526     return;
1527   assert(!ValOriginMap.count(I));
1528   assert(Origin->getType() == DFS.OriginTy);
1529   ValOriginMap[I] = Origin;
1530 }
1531 
1532 Value *DFSanFunction::getShadowForTLSArgument(Argument *A) {
1533   unsigned ArgOffset = 0;
1534   const DataLayout &DL = F->getParent()->getDataLayout();
1535   for (auto &FArg : F->args()) {
1536     if (!FArg.getType()->isSized()) {
1537       if (A == &FArg)
1538         break;
1539       continue;
1540     }
1541 
1542     unsigned Size = DL.getTypeAllocSize(DFS.getShadowTy(&FArg));
1543     if (A != &FArg) {
1544       ArgOffset += alignTo(Size, kShadowTLSAlignment);
1545       if (ArgOffset > kArgTLSSize)
1546         break; // ArgTLS overflows, uses a zero shadow.
1547       continue;
1548     }
1549 
1550     if (ArgOffset + Size > kArgTLSSize)
1551       break; // ArgTLS overflows, uses a zero shadow.
1552 
1553     Instruction *ArgTLSPos = &*F->getEntryBlock().begin();
1554     IRBuilder<> IRB(ArgTLSPos);
1555     Value *ArgShadowPtr = getArgTLS(FArg.getType(), ArgOffset, IRB);
1556     return IRB.CreateAlignedLoad(DFS.getShadowTy(&FArg), ArgShadowPtr,
1557                                  kShadowTLSAlignment);
1558   }
1559 
1560   return DFS.getZeroShadow(A);
1561 }
1562 
1563 Value *DFSanFunction::getShadow(Value *V) {
1564   if (!isa<Argument>(V) && !isa<Instruction>(V))
1565     return DFS.getZeroShadow(V);
1566   Value *&Shadow = ValShadowMap[V];
1567   if (!Shadow) {
1568     if (Argument *A = dyn_cast<Argument>(V)) {
1569       if (IsNativeABI)
1570         return DFS.getZeroShadow(V);
1571       switch (IA) {
1572       case DataFlowSanitizer::IA_TLS: {
1573         Shadow = getShadowForTLSArgument(A);
1574         break;
1575       }
1576       case DataFlowSanitizer::IA_Args: {
1577         unsigned ArgIdx = A->getArgNo() + F->arg_size() / 2;
1578         Function::arg_iterator i = F->arg_begin();
1579         while (ArgIdx--)
1580           ++i;
1581         Shadow = &*i;
1582         assert(Shadow->getType() == DFS.PrimitiveShadowTy);
1583         break;
1584       }
1585       }
1586       NonZeroChecks.push_back(Shadow);
1587     } else {
1588       Shadow = DFS.getZeroShadow(V);
1589     }
1590   }
1591   return Shadow;
1592 }
1593 
1594 void DFSanFunction::setShadow(Instruction *I, Value *Shadow) {
1595   assert(!ValShadowMap.count(I));
1596   assert(DFS.shouldTrackFieldsAndIndices() ||
1597          Shadow->getType() == DFS.PrimitiveShadowTy);
1598   ValShadowMap[I] = Shadow;
1599 }
1600 
1601 Value *DataFlowSanitizer::getShadowOffset(Value *Addr, IRBuilder<> &IRB) {
1602   // Returns Addr & shadow_mask
1603   assert(Addr != RetvalTLS && "Reinstrumenting?");
1604   Value *ShadowPtrMaskValue;
1605   if (DFSanRuntimeShadowMask)
1606     ShadowPtrMaskValue = IRB.CreateLoad(IntptrTy, ExternalShadowMask);
1607   else
1608     ShadowPtrMaskValue = ShadowPtrMask;
1609   return IRB.CreateAnd(IRB.CreatePtrToInt(Addr, IntptrTy),
1610                        IRB.CreatePtrToInt(ShadowPtrMaskValue, IntptrTy));
1611 }
1612 /*
1613 std::pair<Value *, Value *>
1614 DataFlowSanitizer::getShadowOriginAddress(Value *Addr, Align InstAlignment,
1615                                           Instruction *Pos) {
1616   // Returns ((Addr & shadow_mask) + origin_base) & ~4UL
1617   IRBuilder<> IRB(Pos);
1618   Value *ShadowOffset = getShadowOffset(Addr, IRB);
1619   Value *ShadowPtr = IRB.CreateIntToPtr(
1620       IRB.CreateMul(ShadowOffset, ShadowPtrMul), PrimitiveShadowPtrTy);
1621   Value *OriginPtr = nullptr;
1622   if (shouldTrackOrigins()) {
1623     Value *OriginLong = IRB.CreateAdd(ShadowOffset, OriginBase);
1624     const Align Alignment = llvm::assumeAligned(InstAlignment.value());
1625     // When alignment is >= 4, Addr must be aligned to 4, otherwise it is UB.
1626     // So Mask is unnecessary.
1627     if (Alignment < kMinOriginAlignment) {
1628       uint64_t Mask = kMinOriginAlignment.value() - 1;
1629       OriginLong = IRB.CreateAnd(OriginLong, ConstantInt::get(IntptrTy, ~Mask));
1630     }
1631     OriginPtr = IRB.CreateIntToPtr(OriginLong, OriginPtrTy);
1632   }
1633   return {ShadowPtr, OriginPtr};
1634 }
1635 */
1636 Value *DataFlowSanitizer::getShadowAddress(Value *Addr, Instruction *Pos) {
1637   // Returns (Addr & shadow_mask) x 2
1638   IRBuilder<> IRB(Pos);
1639   Value *ShadowOffset = getShadowOffset(Addr, IRB);
1640   return IRB.CreateIntToPtr(IRB.CreateMul(ShadowOffset, ShadowPtrMul),
1641                             PrimitiveShadowPtrTy);
1642 }
1643 
1644 Value *DFSanFunction::combineShadowsThenConvert(Type *T, Value *V1, Value *V2,
1645                                                 Instruction *Pos) {
1646   Value *PrimitiveValue = combineShadows(V1, V2, Pos);
1647   return expandFromPrimitiveShadow(T, PrimitiveValue, Pos);
1648 }
1649 
1650 // Generates IR to compute the union of the two given shadows, inserting it
1651 // before Pos. The combined value is with primitive type.
1652 Value *DFSanFunction::combineShadows(Value *V1, Value *V2, Instruction *Pos) {
1653   if (DFS.isZeroShadow(V1))
1654     return collapseToPrimitiveShadow(V2, Pos);
1655   if (DFS.isZeroShadow(V2))
1656     return collapseToPrimitiveShadow(V1, Pos);
1657   if (V1 == V2)
1658     return collapseToPrimitiveShadow(V1, Pos);
1659 
1660   auto V1Elems = ShadowElements.find(V1);
1661   auto V2Elems = ShadowElements.find(V2);
1662   if (V1Elems != ShadowElements.end() && V2Elems != ShadowElements.end()) {
1663     if (std::includes(V1Elems->second.begin(), V1Elems->second.end(),
1664                       V2Elems->second.begin(), V2Elems->second.end())) {
1665       return collapseToPrimitiveShadow(V1, Pos);
1666     } else if (std::includes(V2Elems->second.begin(), V2Elems->second.end(),
1667                              V1Elems->second.begin(), V1Elems->second.end())) {
1668       return collapseToPrimitiveShadow(V2, Pos);
1669     }
1670   } else if (V1Elems != ShadowElements.end()) {
1671     if (V1Elems->second.count(V2))
1672       return collapseToPrimitiveShadow(V1, Pos);
1673   } else if (V2Elems != ShadowElements.end()) {
1674     if (V2Elems->second.count(V1))
1675       return collapseToPrimitiveShadow(V2, Pos);
1676   }
1677 
1678   auto Key = std::make_pair(V1, V2);
1679   if (V1 > V2)
1680     std::swap(Key.first, Key.second);
1681   CachedShadow &CCS = CachedShadows[Key];
1682   if (CCS.Block && DT.dominates(CCS.Block, Pos->getParent()))
1683     return CCS.Shadow;
1684 
1685   // Converts inputs shadows to shadows with primitive types.
1686   Value *PV1 = collapseToPrimitiveShadow(V1, Pos);
1687   Value *PV2 = collapseToPrimitiveShadow(V2, Pos);
1688 
1689   IRBuilder<> IRB(Pos);
1690   if (ClFast16Labels) {
1691     CCS.Block = Pos->getParent();
1692     CCS.Shadow = IRB.CreateOr(PV1, PV2);
1693   } else if (AvoidNewBlocks) {
1694     CallInst *Call = IRB.CreateCall(DFS.DFSanCheckedUnionFn, {PV1, PV2});
1695     Call->addAttribute(AttributeList::ReturnIndex, Attribute::ZExt);
1696     Call->addParamAttr(0, Attribute::ZExt);
1697     Call->addParamAttr(1, Attribute::ZExt);
1698 
1699     CCS.Block = Pos->getParent();
1700     CCS.Shadow = Call;
1701   } else {
1702     BasicBlock *Head = Pos->getParent();
1703     Value *Ne = IRB.CreateICmpNE(PV1, PV2);
1704     BranchInst *BI = cast<BranchInst>(SplitBlockAndInsertIfThen(
1705         Ne, Pos, /*Unreachable=*/false, DFS.ColdCallWeights, &DT));
1706     IRBuilder<> ThenIRB(BI);
1707     CallInst *Call = ThenIRB.CreateCall(DFS.DFSanUnionFn, {PV1, PV2});
1708     Call->addAttribute(AttributeList::ReturnIndex, Attribute::ZExt);
1709     Call->addParamAttr(0, Attribute::ZExt);
1710     Call->addParamAttr(1, Attribute::ZExt);
1711 
1712     BasicBlock *Tail = BI->getSuccessor(0);
1713     PHINode *Phi =
1714         PHINode::Create(DFS.PrimitiveShadowTy, 2, "", &Tail->front());
1715     Phi->addIncoming(Call, Call->getParent());
1716     Phi->addIncoming(PV1, Head);
1717 
1718     CCS.Block = Tail;
1719     CCS.Shadow = Phi;
1720   }
1721 
1722   std::set<Value *> UnionElems;
1723   if (V1Elems != ShadowElements.end()) {
1724     UnionElems = V1Elems->second;
1725   } else {
1726     UnionElems.insert(V1);
1727   }
1728   if (V2Elems != ShadowElements.end()) {
1729     UnionElems.insert(V2Elems->second.begin(), V2Elems->second.end());
1730   } else {
1731     UnionElems.insert(V2);
1732   }
1733   ShadowElements[CCS.Shadow] = std::move(UnionElems);
1734 
1735   return CCS.Shadow;
1736 }
1737 
1738 // A convenience function which folds the shadows of each of the operands
1739 // of the provided instruction Inst, inserting the IR before Inst.  Returns
1740 // the computed union Value.
1741 Value *DFSanFunction::combineOperandShadows(Instruction *Inst) {
1742   if (Inst->getNumOperands() == 0)
1743     return DFS.getZeroShadow(Inst);
1744 
1745   Value *Shadow = getShadow(Inst->getOperand(0));
1746   for (unsigned i = 1, n = Inst->getNumOperands(); i != n; ++i) {
1747     Shadow = combineShadows(Shadow, getShadow(Inst->getOperand(i)), Inst);
1748   }
1749   return expandFromPrimitiveShadow(Inst->getType(), Shadow, Inst);
1750 }
1751 
1752 void DFSanVisitor::visitInstOperands(Instruction &I) {
1753   Value *CombinedShadow = DFSF.combineOperandShadows(&I);
1754   DFSF.setShadow(&I, CombinedShadow);
1755   visitInstOperandOrigins(I);
1756 }
1757 
1758 Value *DFSanFunction::combineOrigins(const std::vector<Value *> &Shadows,
1759                                      const std::vector<Value *> &Origins,
1760                                      Instruction *Pos, ConstantInt *Zero) {
1761   assert(Shadows.size() == Origins.size());
1762   size_t Size = Origins.size();
1763   if (Size == 0)
1764     return DFS.ZeroOrigin;
1765   Value *Origin = nullptr;
1766   if (!Zero)
1767     Zero = DFS.ZeroPrimitiveShadow;
1768   for (size_t I = 0; I != Size; ++I) {
1769     Value *OpOrigin = Origins[I];
1770     Constant *ConstOpOrigin = dyn_cast<Constant>(OpOrigin);
1771     if (ConstOpOrigin && ConstOpOrigin->isNullValue())
1772       continue;
1773     if (!Origin) {
1774       Origin = OpOrigin;
1775       continue;
1776     }
1777     Value *OpShadow = Shadows[I];
1778     Value *PrimitiveShadow = collapseToPrimitiveShadow(OpShadow, Pos);
1779     IRBuilder<> IRB(Pos);
1780     Value *Cond = IRB.CreateICmpNE(PrimitiveShadow, Zero);
1781     Origin = IRB.CreateSelect(Cond, OpOrigin, Origin);
1782   }
1783   return Origin ? Origin : DFS.ZeroOrigin;
1784 }
1785 
1786 Value *DFSanFunction::combineOperandOrigins(Instruction *Inst) {
1787   size_t Size = Inst->getNumOperands();
1788   std::vector<Value *> Shadows(Size);
1789   std::vector<Value *> Origins(Size);
1790   for (unsigned I = 0; I != Size; ++I) {
1791     Shadows[I] = getShadow(Inst->getOperand(I));
1792     Origins[I] = getOrigin(Inst->getOperand(I));
1793   }
1794   return combineOrigins(Shadows, Origins, Inst);
1795 }
1796 
1797 void DFSanVisitor::visitInstOperandOrigins(Instruction &I) {
1798   if (!DFSF.DFS.shouldTrackOrigins())
1799     return;
1800   Value *CombinedOrigin = DFSF.combineOperandOrigins(&I);
1801   DFSF.setOrigin(&I, CombinedOrigin);
1802 }
1803 
1804 Value *DFSanFunction::loadFast16ShadowFast(Value *ShadowAddr, uint64_t Size,
1805                                            Align ShadowAlign,
1806                                            Instruction *Pos) {
1807   // First OR all the WideShadows, then OR individual shadows within the
1808   // combined WideShadow. This is fewer instructions than ORing shadows
1809   // individually.
1810   IRBuilder<> IRB(Pos);
1811   Value *WideAddr =
1812       IRB.CreateBitCast(ShadowAddr, Type::getInt64PtrTy(*DFS.Ctx));
1813   Value *CombinedWideShadow =
1814       IRB.CreateAlignedLoad(IRB.getInt64Ty(), WideAddr, ShadowAlign);
1815   for (uint64_t Ofs = 64 / DFS.ShadowWidthBits; Ofs != Size;
1816        Ofs += 64 / DFS.ShadowWidthBits) {
1817     WideAddr = IRB.CreateGEP(Type::getInt64Ty(*DFS.Ctx), WideAddr,
1818                              ConstantInt::get(DFS.IntptrTy, 1));
1819     Value *NextWideShadow =
1820         IRB.CreateAlignedLoad(IRB.getInt64Ty(), WideAddr, ShadowAlign);
1821     CombinedWideShadow = IRB.CreateOr(CombinedWideShadow, NextWideShadow);
1822   }
1823   for (unsigned Width = 32; Width >= DFS.ShadowWidthBits; Width >>= 1) {
1824     Value *ShrShadow = IRB.CreateLShr(CombinedWideShadow, Width);
1825     CombinedWideShadow = IRB.CreateOr(CombinedWideShadow, ShrShadow);
1826   }
1827   return IRB.CreateTrunc(CombinedWideShadow, DFS.PrimitiveShadowTy);
1828 }
1829 
1830 Value *DFSanFunction::loadLegacyShadowFast(Value *ShadowAddr, uint64_t Size,
1831                                            Align ShadowAlign,
1832                                            Instruction *Pos) {
1833   // Fast path for the common case where each byte has identical shadow: load
1834   // shadow 64 bits at a time, fall out to a __dfsan_union_load call if any
1835   // shadow is non-equal.
1836   BasicBlock *FallbackBB = BasicBlock::Create(*DFS.Ctx, "", F);
1837   IRBuilder<> FallbackIRB(FallbackBB);
1838   CallInst *FallbackCall = FallbackIRB.CreateCall(
1839       DFS.DFSanUnionLoadFn, {ShadowAddr, ConstantInt::get(DFS.IntptrTy, Size)});
1840   FallbackCall->addAttribute(AttributeList::ReturnIndex, Attribute::ZExt);
1841 
1842   // Compare each of the shadows stored in the loaded 64 bits to each other,
1843   // by computing (WideShadow rotl ShadowWidthBits) == WideShadow.
1844   IRBuilder<> IRB(Pos);
1845   Value *WideAddr =
1846       IRB.CreateBitCast(ShadowAddr, Type::getInt64PtrTy(*DFS.Ctx));
1847   Value *WideShadow =
1848       IRB.CreateAlignedLoad(IRB.getInt64Ty(), WideAddr, ShadowAlign);
1849   Value *TruncShadow = IRB.CreateTrunc(WideShadow, DFS.PrimitiveShadowTy);
1850   Value *ShlShadow = IRB.CreateShl(WideShadow, DFS.ShadowWidthBits);
1851   Value *ShrShadow = IRB.CreateLShr(WideShadow, 64 - DFS.ShadowWidthBits);
1852   Value *RotShadow = IRB.CreateOr(ShlShadow, ShrShadow);
1853   Value *ShadowsEq = IRB.CreateICmpEQ(WideShadow, RotShadow);
1854 
1855   BasicBlock *Head = Pos->getParent();
1856   BasicBlock *Tail = Head->splitBasicBlock(Pos->getIterator());
1857 
1858   if (DomTreeNode *OldNode = DT.getNode(Head)) {
1859     std::vector<DomTreeNode *> Children(OldNode->begin(), OldNode->end());
1860 
1861     DomTreeNode *NewNode = DT.addNewBlock(Tail, Head);
1862     for (auto *Child : Children)
1863       DT.changeImmediateDominator(Child, NewNode);
1864   }
1865 
1866   // In the following code LastBr will refer to the previous basic block's
1867   // conditional branch instruction, whose true successor is fixed up to point
1868   // to the next block during the loop below or to the tail after the final
1869   // iteration.
1870   BranchInst *LastBr = BranchInst::Create(FallbackBB, FallbackBB, ShadowsEq);
1871   ReplaceInstWithInst(Head->getTerminator(), LastBr);
1872   DT.addNewBlock(FallbackBB, Head);
1873 
1874   for (uint64_t Ofs = 64 / DFS.ShadowWidthBits; Ofs != Size;
1875        Ofs += 64 / DFS.ShadowWidthBits) {
1876     BasicBlock *NextBB = BasicBlock::Create(*DFS.Ctx, "", F);
1877     DT.addNewBlock(NextBB, LastBr->getParent());
1878     IRBuilder<> NextIRB(NextBB);
1879     WideAddr = NextIRB.CreateGEP(Type::getInt64Ty(*DFS.Ctx), WideAddr,
1880                                  ConstantInt::get(DFS.IntptrTy, 1));
1881     Value *NextWideShadow =
1882         NextIRB.CreateAlignedLoad(NextIRB.getInt64Ty(), WideAddr, ShadowAlign);
1883     ShadowsEq = NextIRB.CreateICmpEQ(WideShadow, NextWideShadow);
1884     LastBr->setSuccessor(0, NextBB);
1885     LastBr = NextIRB.CreateCondBr(ShadowsEq, FallbackBB, FallbackBB);
1886   }
1887 
1888   LastBr->setSuccessor(0, Tail);
1889   FallbackIRB.CreateBr(Tail);
1890   PHINode *Shadow =
1891       PHINode::Create(DFS.PrimitiveShadowTy, 2, "", &Tail->front());
1892   Shadow->addIncoming(FallbackCall, FallbackBB);
1893   Shadow->addIncoming(TruncShadow, LastBr->getParent());
1894   return Shadow;
1895 }
1896 
1897 // Generates IR to load shadow corresponding to bytes [Addr, Addr+Size), where
1898 // Addr has alignment Align, and take the union of each of those shadows. The
1899 // returned shadow always has primitive type.
1900 Value *DFSanFunction::loadShadow(Value *Addr, uint64_t Size, uint64_t Align,
1901                                  Instruction *Pos) {
1902   if (AllocaInst *AI = dyn_cast<AllocaInst>(Addr)) {
1903     const auto i = AllocaShadowMap.find(AI);
1904     if (i != AllocaShadowMap.end()) {
1905       IRBuilder<> IRB(Pos);
1906       return IRB.CreateLoad(DFS.PrimitiveShadowTy, i->second);
1907     }
1908   }
1909 
1910   const llvm::Align ShadowAlign(Align * DFS.ShadowWidthBytes);
1911   SmallVector<const Value *, 2> Objs;
1912   getUnderlyingObjects(Addr, Objs);
1913   bool AllConstants = true;
1914   for (const Value *Obj : Objs) {
1915     if (isa<Function>(Obj) || isa<BlockAddress>(Obj))
1916       continue;
1917     if (isa<GlobalVariable>(Obj) && cast<GlobalVariable>(Obj)->isConstant())
1918       continue;
1919 
1920     AllConstants = false;
1921     break;
1922   }
1923   if (AllConstants)
1924     return DFS.ZeroPrimitiveShadow;
1925 
1926   Value *ShadowAddr = DFS.getShadowAddress(Addr, Pos);
1927   switch (Size) {
1928   case 0:
1929     return DFS.ZeroPrimitiveShadow;
1930   case 1: {
1931     LoadInst *LI = new LoadInst(DFS.PrimitiveShadowTy, ShadowAddr, "", Pos);
1932     LI->setAlignment(ShadowAlign);
1933     return LI;
1934   }
1935   case 2: {
1936     IRBuilder<> IRB(Pos);
1937     Value *ShadowAddr1 = IRB.CreateGEP(DFS.PrimitiveShadowTy, ShadowAddr,
1938                                        ConstantInt::get(DFS.IntptrTy, 1));
1939     return combineShadows(
1940         IRB.CreateAlignedLoad(DFS.PrimitiveShadowTy, ShadowAddr, ShadowAlign),
1941         IRB.CreateAlignedLoad(DFS.PrimitiveShadowTy, ShadowAddr1, ShadowAlign),
1942         Pos);
1943   }
1944   }
1945 
1946   if (ClFast16Labels && Size % (64 / DFS.ShadowWidthBits) == 0)
1947     return loadFast16ShadowFast(ShadowAddr, Size, ShadowAlign, Pos);
1948 
1949   if (!AvoidNewBlocks && Size % (64 / DFS.ShadowWidthBits) == 0)
1950     return loadLegacyShadowFast(ShadowAddr, Size, ShadowAlign, Pos);
1951 
1952   IRBuilder<> IRB(Pos);
1953   FunctionCallee &UnionLoadFn =
1954       ClFast16Labels ? DFS.DFSanUnionLoadFast16LabelsFn : DFS.DFSanUnionLoadFn;
1955   CallInst *FallbackCall = IRB.CreateCall(
1956       UnionLoadFn, {ShadowAddr, ConstantInt::get(DFS.IntptrTy, Size)});
1957   FallbackCall->addAttribute(AttributeList::ReturnIndex, Attribute::ZExt);
1958   return FallbackCall;
1959 }
1960 
1961 void DFSanVisitor::visitLoadInst(LoadInst &LI) {
1962   auto &DL = LI.getModule()->getDataLayout();
1963   uint64_t Size = DL.getTypeStoreSize(LI.getType());
1964   if (Size == 0) {
1965     DFSF.setShadow(&LI, DFSF.DFS.getZeroShadow(&LI));
1966     return;
1967   }
1968 
1969   Align Alignment = ClPreserveAlignment ? LI.getAlign() : Align(1);
1970   Value *PrimitiveShadow =
1971       DFSF.loadShadow(LI.getPointerOperand(), Size, Alignment.value(), &LI);
1972   if (ClCombinePointerLabelsOnLoad) {
1973     Value *PtrShadow = DFSF.getShadow(LI.getPointerOperand());
1974     PrimitiveShadow = DFSF.combineShadows(PrimitiveShadow, PtrShadow, &LI);
1975   }
1976   if (!DFSF.DFS.isZeroShadow(PrimitiveShadow))
1977     DFSF.NonZeroChecks.push_back(PrimitiveShadow);
1978 
1979   Value *Shadow =
1980       DFSF.expandFromPrimitiveShadow(LI.getType(), PrimitiveShadow, &LI);
1981   DFSF.setShadow(&LI, Shadow);
1982   if (ClEventCallbacks) {
1983     IRBuilder<> IRB(&LI);
1984     Value *Addr8 = IRB.CreateBitCast(LI.getPointerOperand(), DFSF.DFS.Int8Ptr);
1985     IRB.CreateCall(DFSF.DFS.DFSanLoadCallbackFn, {PrimitiveShadow, Addr8});
1986   }
1987 }
1988 
1989 void DFSanFunction::storePrimitiveShadow(Value *Addr, uint64_t Size,
1990                                          Align Alignment,
1991                                          Value *PrimitiveShadow,
1992                                          Instruction *Pos) {
1993   if (AllocaInst *AI = dyn_cast<AllocaInst>(Addr)) {
1994     const auto i = AllocaShadowMap.find(AI);
1995     if (i != AllocaShadowMap.end()) {
1996       IRBuilder<> IRB(Pos);
1997       IRB.CreateStore(PrimitiveShadow, i->second);
1998       return;
1999     }
2000   }
2001 
2002   const Align ShadowAlign(Alignment.value() * DFS.ShadowWidthBytes);
2003   IRBuilder<> IRB(Pos);
2004   Value *ShadowAddr = DFS.getShadowAddress(Addr, Pos);
2005   if (DFS.isZeroShadow(PrimitiveShadow)) {
2006     IntegerType *ShadowTy =
2007         IntegerType::get(*DFS.Ctx, Size * DFS.ShadowWidthBits);
2008     Value *ExtZeroShadow = ConstantInt::get(ShadowTy, 0);
2009     Value *ExtShadowAddr =
2010         IRB.CreateBitCast(ShadowAddr, PointerType::getUnqual(ShadowTy));
2011     IRB.CreateAlignedStore(ExtZeroShadow, ExtShadowAddr, ShadowAlign);
2012     return;
2013   }
2014 
2015   const unsigned ShadowVecSize = 128 / DFS.ShadowWidthBits;
2016   uint64_t Offset = 0;
2017   if (Size >= ShadowVecSize) {
2018     auto *ShadowVecTy =
2019         FixedVectorType::get(DFS.PrimitiveShadowTy, ShadowVecSize);
2020     Value *ShadowVec = UndefValue::get(ShadowVecTy);
2021     for (unsigned i = 0; i != ShadowVecSize; ++i) {
2022       ShadowVec = IRB.CreateInsertElement(
2023           ShadowVec, PrimitiveShadow,
2024           ConstantInt::get(Type::getInt32Ty(*DFS.Ctx), i));
2025     }
2026     Value *ShadowVecAddr =
2027         IRB.CreateBitCast(ShadowAddr, PointerType::getUnqual(ShadowVecTy));
2028     do {
2029       Value *CurShadowVecAddr =
2030           IRB.CreateConstGEP1_32(ShadowVecTy, ShadowVecAddr, Offset);
2031       IRB.CreateAlignedStore(ShadowVec, CurShadowVecAddr, ShadowAlign);
2032       Size -= ShadowVecSize;
2033       ++Offset;
2034     } while (Size >= ShadowVecSize);
2035     Offset *= ShadowVecSize;
2036   }
2037   while (Size > 0) {
2038     Value *CurShadowAddr =
2039         IRB.CreateConstGEP1_32(DFS.PrimitiveShadowTy, ShadowAddr, Offset);
2040     IRB.CreateAlignedStore(PrimitiveShadow, CurShadowAddr, ShadowAlign);
2041     --Size;
2042     ++Offset;
2043   }
2044 }
2045 
2046 void DFSanVisitor::visitStoreInst(StoreInst &SI) {
2047   auto &DL = SI.getModule()->getDataLayout();
2048   uint64_t Size = DL.getTypeStoreSize(SI.getValueOperand()->getType());
2049   if (Size == 0)
2050     return;
2051 
2052   const Align Alignment = ClPreserveAlignment ? SI.getAlign() : Align(1);
2053 
2054   Value* Shadow = DFSF.getShadow(SI.getValueOperand());
2055   Value *PrimitiveShadow;
2056   if (ClCombinePointerLabelsOnStore) {
2057     Value *PtrShadow = DFSF.getShadow(SI.getPointerOperand());
2058     PrimitiveShadow = DFSF.combineShadows(Shadow, PtrShadow, &SI);
2059   } else {
2060     PrimitiveShadow = DFSF.collapseToPrimitiveShadow(Shadow, &SI);
2061   }
2062   DFSF.storePrimitiveShadow(SI.getPointerOperand(), Size, Alignment,
2063                             PrimitiveShadow, &SI);
2064   if (ClEventCallbacks) {
2065     IRBuilder<> IRB(&SI);
2066     Value *Addr8 = IRB.CreateBitCast(SI.getPointerOperand(), DFSF.DFS.Int8Ptr);
2067     IRB.CreateCall(DFSF.DFS.DFSanStoreCallbackFn, {PrimitiveShadow, Addr8});
2068   }
2069 }
2070 
2071 void DFSanVisitor::visitUnaryOperator(UnaryOperator &UO) {
2072   visitInstOperands(UO);
2073 }
2074 
2075 void DFSanVisitor::visitBinaryOperator(BinaryOperator &BO) {
2076   visitInstOperands(BO);
2077 }
2078 
2079 void DFSanVisitor::visitCastInst(CastInst &CI) { visitInstOperands(CI); }
2080 
2081 void DFSanVisitor::visitCmpInst(CmpInst &CI) {
2082   visitInstOperands(CI);
2083   if (ClEventCallbacks) {
2084     IRBuilder<> IRB(&CI);
2085     Value *CombinedShadow = DFSF.getShadow(&CI);
2086     IRB.CreateCall(DFSF.DFS.DFSanCmpCallbackFn, CombinedShadow);
2087   }
2088 }
2089 
2090 void DFSanVisitor::visitGetElementPtrInst(GetElementPtrInst &GEPI) {
2091   visitInstOperands(GEPI);
2092 }
2093 
2094 void DFSanVisitor::visitExtractElementInst(ExtractElementInst &I) {
2095   visitInstOperands(I);
2096 }
2097 
2098 void DFSanVisitor::visitInsertElementInst(InsertElementInst &I) {
2099   visitInstOperands(I);
2100 }
2101 
2102 void DFSanVisitor::visitShuffleVectorInst(ShuffleVectorInst &I) {
2103   visitInstOperands(I);
2104 }
2105 
2106 void DFSanVisitor::visitExtractValueInst(ExtractValueInst &I) {
2107   if (!DFSF.DFS.shouldTrackFieldsAndIndices()) {
2108     visitInstOperands(I);
2109     return;
2110   }
2111 
2112   IRBuilder<> IRB(&I);
2113   Value *Agg = I.getAggregateOperand();
2114   Value *AggShadow = DFSF.getShadow(Agg);
2115   Value *ResShadow = IRB.CreateExtractValue(AggShadow, I.getIndices());
2116   DFSF.setShadow(&I, ResShadow);
2117   visitInstOperandOrigins(I);
2118 }
2119 
2120 void DFSanVisitor::visitInsertValueInst(InsertValueInst &I) {
2121   if (!DFSF.DFS.shouldTrackFieldsAndIndices()) {
2122     visitInstOperands(I);
2123     return;
2124   }
2125 
2126   IRBuilder<> IRB(&I);
2127   Value *AggShadow = DFSF.getShadow(I.getAggregateOperand());
2128   Value *InsShadow = DFSF.getShadow(I.getInsertedValueOperand());
2129   Value *Res = IRB.CreateInsertValue(AggShadow, InsShadow, I.getIndices());
2130   DFSF.setShadow(&I, Res);
2131   visitInstOperandOrigins(I);
2132 }
2133 
2134 void DFSanVisitor::visitAllocaInst(AllocaInst &I) {
2135   bool AllLoadsStores = true;
2136   for (User *U : I.users()) {
2137     if (isa<LoadInst>(U))
2138       continue;
2139 
2140     if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
2141       if (SI->getPointerOperand() == &I)
2142         continue;
2143     }
2144 
2145     AllLoadsStores = false;
2146     break;
2147   }
2148   if (AllLoadsStores) {
2149     IRBuilder<> IRB(&I);
2150     DFSF.AllocaShadowMap[&I] = IRB.CreateAlloca(DFSF.DFS.PrimitiveShadowTy);
2151   }
2152   DFSF.setShadow(&I, DFSF.DFS.ZeroPrimitiveShadow);
2153 }
2154 
2155 void DFSanVisitor::visitSelectInst(SelectInst &I) {
2156   Value *CondShadow = DFSF.getShadow(I.getCondition());
2157   Value *TrueShadow = DFSF.getShadow(I.getTrueValue());
2158   Value *FalseShadow = DFSF.getShadow(I.getFalseValue());
2159   Value *ShadowSel = nullptr;
2160   const bool ShouldTrackOrigins = DFSF.DFS.shouldTrackOrigins();
2161   std::vector<Value *> Shadows;
2162   std::vector<Value *> Origins;
2163   Value *TrueOrigin =
2164       ShouldTrackOrigins ? DFSF.getOrigin(I.getTrueValue()) : nullptr;
2165   Value *FalseOrigin =
2166       ShouldTrackOrigins ? DFSF.getOrigin(I.getFalseValue()) : nullptr;
2167 
2168   if (isa<VectorType>(I.getCondition()->getType())) {
2169     ShadowSel = DFSF.combineShadowsThenConvert(I.getType(), TrueShadow,
2170                                                FalseShadow, &I);
2171     if (ShouldTrackOrigins) {
2172       Shadows.push_back(TrueShadow);
2173       Shadows.push_back(FalseShadow);
2174       Origins.push_back(TrueOrigin);
2175       Origins.push_back(FalseOrigin);
2176     }
2177   } else {
2178     if (TrueShadow == FalseShadow) {
2179       ShadowSel = TrueShadow;
2180       if (ShouldTrackOrigins) {
2181         Shadows.push_back(TrueShadow);
2182         Origins.push_back(TrueOrigin);
2183       }
2184     } else {
2185       ShadowSel =
2186           SelectInst::Create(I.getCondition(), TrueShadow, FalseShadow, "", &I);
2187       if (ShouldTrackOrigins) {
2188         Shadows.push_back(ShadowSel);
2189         Origins.push_back(SelectInst::Create(I.getCondition(), TrueOrigin,
2190                                              FalseOrigin, "", &I));
2191       }
2192     }
2193   }
2194   DFSF.setShadow(&I, ClTrackSelectControlFlow
2195                          ? DFSF.combineShadowsThenConvert(
2196                                I.getType(), CondShadow, ShadowSel, &I)
2197                          : ShadowSel);
2198   if (ShouldTrackOrigins) {
2199     if (ClTrackSelectControlFlow) {
2200       Shadows.push_back(CondShadow);
2201       Origins.push_back(DFSF.getOrigin(I.getCondition()));
2202     }
2203     DFSF.setOrigin(&I, DFSF.combineOrigins(Shadows, Origins, &I));
2204   }
2205 }
2206 
2207 void DFSanVisitor::visitMemSetInst(MemSetInst &I) {
2208   IRBuilder<> IRB(&I);
2209   Value *ValShadow = DFSF.getShadow(I.getValue());
2210   IRB.CreateCall(DFSF.DFS.DFSanSetLabelFn,
2211                  {ValShadow, IRB.CreateBitCast(I.getDest(), Type::getInt8PtrTy(
2212                                                                 *DFSF.DFS.Ctx)),
2213                   IRB.CreateZExtOrTrunc(I.getLength(), DFSF.DFS.IntptrTy)});
2214 }
2215 
2216 void DFSanVisitor::visitMemTransferInst(MemTransferInst &I) {
2217   IRBuilder<> IRB(&I);
2218   Value *RawDestShadow = DFSF.DFS.getShadowAddress(I.getDest(), &I);
2219   Value *SrcShadow = DFSF.DFS.getShadowAddress(I.getSource(), &I);
2220   Value *LenShadow =
2221       IRB.CreateMul(I.getLength(), ConstantInt::get(I.getLength()->getType(),
2222                                                     DFSF.DFS.ShadowWidthBytes));
2223   Type *Int8Ptr = Type::getInt8PtrTy(*DFSF.DFS.Ctx);
2224   Value *DestShadow = IRB.CreateBitCast(RawDestShadow, Int8Ptr);
2225   SrcShadow = IRB.CreateBitCast(SrcShadow, Int8Ptr);
2226   auto *MTI = cast<MemTransferInst>(
2227       IRB.CreateCall(I.getFunctionType(), I.getCalledOperand(),
2228                      {DestShadow, SrcShadow, LenShadow, I.getVolatileCst()}));
2229   if (ClPreserveAlignment) {
2230     MTI->setDestAlignment(I.getDestAlign() * DFSF.DFS.ShadowWidthBytes);
2231     MTI->setSourceAlignment(I.getSourceAlign() * DFSF.DFS.ShadowWidthBytes);
2232   } else {
2233     MTI->setDestAlignment(Align(DFSF.DFS.ShadowWidthBytes));
2234     MTI->setSourceAlignment(Align(DFSF.DFS.ShadowWidthBytes));
2235   }
2236   if (ClEventCallbacks) {
2237     IRB.CreateCall(DFSF.DFS.DFSanMemTransferCallbackFn,
2238                    {RawDestShadow, I.getLength()});
2239   }
2240 }
2241 
2242 void DFSanVisitor::visitReturnInst(ReturnInst &RI) {
2243   if (!DFSF.IsNativeABI && RI.getReturnValue()) {
2244     switch (DFSF.IA) {
2245     case DataFlowSanitizer::IA_TLS: {
2246       Value *S = DFSF.getShadow(RI.getReturnValue());
2247       IRBuilder<> IRB(&RI);
2248       Type *RT = DFSF.F->getFunctionType()->getReturnType();
2249       unsigned Size =
2250           getDataLayout().getTypeAllocSize(DFSF.DFS.getShadowTy(RT));
2251       if (Size <= kRetvalTLSSize) {
2252         // If the size overflows, stores nothing. At callsite, oversized return
2253         // shadows are set to zero.
2254         IRB.CreateAlignedStore(S, DFSF.getRetvalTLS(RT, IRB),
2255                                kShadowTLSAlignment);
2256       }
2257       if (DFSF.DFS.shouldTrackOrigins()) {
2258         Value *O = DFSF.getOrigin(RI.getReturnValue());
2259         IRB.CreateStore(O, DFSF.getRetvalOriginTLS());
2260       }
2261       break;
2262     }
2263     case DataFlowSanitizer::IA_Args: {
2264       IRBuilder<> IRB(&RI);
2265       Type *RT = DFSF.F->getFunctionType()->getReturnType();
2266       Value *InsVal =
2267           IRB.CreateInsertValue(UndefValue::get(RT), RI.getReturnValue(), 0);
2268       Value *InsShadow =
2269           IRB.CreateInsertValue(InsVal, DFSF.getShadow(RI.getReturnValue()), 1);
2270       RI.setOperand(0, InsShadow);
2271       break;
2272     }
2273     }
2274   }
2275 }
2276 
2277 bool DFSanVisitor::visitWrappedCallBase(Function &F, CallBase &CB) {
2278   IRBuilder<> IRB(&CB);
2279   switch (DFSF.DFS.getWrapperKind(&F)) {
2280   case DataFlowSanitizer::WK_Warning:
2281     CB.setCalledFunction(&F);
2282     IRB.CreateCall(DFSF.DFS.DFSanUnimplementedFn,
2283                    IRB.CreateGlobalStringPtr(F.getName()));
2284     DFSF.setShadow(&CB, DFSF.DFS.getZeroShadow(&CB));
2285     return true;
2286   case DataFlowSanitizer::WK_Discard:
2287     CB.setCalledFunction(&F);
2288     DFSF.setShadow(&CB, DFSF.DFS.getZeroShadow(&CB));
2289     return true;
2290   case DataFlowSanitizer::WK_Functional:
2291     CB.setCalledFunction(&F);
2292     visitInstOperands(CB);
2293     return true;
2294   case DataFlowSanitizer::WK_Custom:
2295     // Don't try to handle invokes of custom functions, it's too complicated.
2296     // Instead, invoke the dfsw$ wrapper, which will in turn call the __dfsw_
2297     // wrapper.
2298     CallInst *CI = dyn_cast<CallInst>(&CB);
2299     if (!CI)
2300       return false;
2301 
2302     FunctionType *FT = F.getFunctionType();
2303     TransformedFunction CustomFn = DFSF.DFS.getCustomFunctionType(FT);
2304     std::string CustomFName = "__dfsw_";
2305     CustomFName += F.getName();
2306     FunctionCallee CustomF = DFSF.DFS.Mod->getOrInsertFunction(
2307         CustomFName, CustomFn.TransformedType);
2308     if (Function *CustomFn = dyn_cast<Function>(CustomF.getCallee())) {
2309       CustomFn->copyAttributesFrom(&F);
2310 
2311       // Custom functions returning non-void will write to the return label.
2312       if (!FT->getReturnType()->isVoidTy()) {
2313         CustomFn->removeAttributes(AttributeList::FunctionIndex,
2314                                    DFSF.DFS.ReadOnlyNoneAttrs);
2315       }
2316     }
2317 
2318     std::vector<Value *> Args;
2319 
2320     // Adds non-variable arguments.
2321     auto *I = CB.arg_begin();
2322     for (unsigned n = FT->getNumParams(); n != 0; ++I, --n) {
2323       Type *T = (*I)->getType();
2324       FunctionType *ParamFT;
2325       if (isa<PointerType>(T) &&
2326           (ParamFT = dyn_cast<FunctionType>(
2327                cast<PointerType>(T)->getElementType()))) {
2328         std::string TName = "dfst";
2329         TName += utostr(FT->getNumParams() - n);
2330         TName += "$";
2331         TName += F.getName();
2332         Constant *T = DFSF.DFS.getOrBuildTrampolineFunction(ParamFT, TName);
2333         Args.push_back(T);
2334         Args.push_back(
2335             IRB.CreateBitCast(*I, Type::getInt8PtrTy(*DFSF.DFS.Ctx)));
2336       } else {
2337         Args.push_back(*I);
2338       }
2339     }
2340 
2341     // Adds non-variable argument shadows.
2342     I = CB.arg_begin();
2343     const unsigned ShadowArgStart = Args.size();
2344     for (unsigned N = FT->getNumParams(); N != 0; ++I, --N)
2345       Args.push_back(DFSF.collapseToPrimitiveShadow(DFSF.getShadow(*I), &CB));
2346 
2347     // Adds variable argument shadows.
2348     if (FT->isVarArg()) {
2349       auto *LabelVATy = ArrayType::get(DFSF.DFS.PrimitiveShadowTy,
2350                                        CB.arg_size() - FT->getNumParams());
2351       auto *LabelVAAlloca =
2352           new AllocaInst(LabelVATy, getDataLayout().getAllocaAddrSpace(),
2353                          "labelva", &DFSF.F->getEntryBlock().front());
2354 
2355       for (unsigned N = 0; I != CB.arg_end(); ++I, ++N) {
2356         auto *LabelVAPtr = IRB.CreateStructGEP(LabelVATy, LabelVAAlloca, N);
2357         IRB.CreateStore(DFSF.collapseToPrimitiveShadow(DFSF.getShadow(*I), &CB),
2358                         LabelVAPtr);
2359       }
2360 
2361       Args.push_back(IRB.CreateStructGEP(LabelVATy, LabelVAAlloca, 0));
2362     }
2363 
2364     // Adds the return value shadow.
2365     if (!FT->getReturnType()->isVoidTy()) {
2366       if (!DFSF.LabelReturnAlloca) {
2367         DFSF.LabelReturnAlloca = new AllocaInst(
2368             DFSF.DFS.PrimitiveShadowTy, getDataLayout().getAllocaAddrSpace(),
2369             "labelreturn", &DFSF.F->getEntryBlock().front());
2370       }
2371       Args.push_back(DFSF.LabelReturnAlloca);
2372     }
2373 
2374     // Adds variable arguments.
2375     append_range(Args, drop_begin(CB.args(), FT->getNumParams()));
2376 
2377     CallInst *CustomCI = IRB.CreateCall(CustomF, Args);
2378     CustomCI->setCallingConv(CI->getCallingConv());
2379     CustomCI->setAttributes(TransformFunctionAttributes(
2380         CustomFn, CI->getContext(), CI->getAttributes()));
2381 
2382     // Update the parameter attributes of the custom call instruction to
2383     // zero extend the shadow parameters. This is required for targets
2384     // which consider PrimitiveShadowTy an illegal type.
2385     for (unsigned N = 0; N < FT->getNumParams(); N++) {
2386       const unsigned ArgNo = ShadowArgStart + N;
2387       if (CustomCI->getArgOperand(ArgNo)->getType() ==
2388           DFSF.DFS.PrimitiveShadowTy)
2389         CustomCI->addParamAttr(ArgNo, Attribute::ZExt);
2390     }
2391 
2392     // Loads the return value shadow.
2393     if (!FT->getReturnType()->isVoidTy()) {
2394       LoadInst *LabelLoad =
2395           IRB.CreateLoad(DFSF.DFS.PrimitiveShadowTy, DFSF.LabelReturnAlloca);
2396       DFSF.setShadow(CustomCI, DFSF.expandFromPrimitiveShadow(
2397                                    FT->getReturnType(), LabelLoad, &CB));
2398     }
2399 
2400     CI->replaceAllUsesWith(CustomCI);
2401     CI->eraseFromParent();
2402     return true;
2403   }
2404   return false;
2405 }
2406 
2407 void DFSanVisitor::visitCallBase(CallBase &CB) {
2408   Function *F = CB.getCalledFunction();
2409   if ((F && F->isIntrinsic()) || CB.isInlineAsm()) {
2410     visitInstOperands(CB);
2411     return;
2412   }
2413 
2414   // Calls to this function are synthesized in wrappers, and we shouldn't
2415   // instrument them.
2416   if (F == DFSF.DFS.DFSanVarargWrapperFn.getCallee()->stripPointerCasts())
2417     return;
2418 
2419   DenseMap<Value *, Function *>::iterator i =
2420       DFSF.DFS.UnwrappedFnMap.find(CB.getCalledOperand());
2421   if (i != DFSF.DFS.UnwrappedFnMap.end())
2422     if (visitWrappedCallBase(*i->second, CB))
2423       return;
2424 
2425   IRBuilder<> IRB(&CB);
2426 
2427   FunctionType *FT = CB.getFunctionType();
2428   if (DFSF.DFS.getInstrumentedABI() == DataFlowSanitizer::IA_TLS) {
2429     // Stores argument shadows.
2430     unsigned ArgOffset = 0;
2431     const DataLayout &DL = getDataLayout();
2432     for (unsigned I = 0, N = FT->getNumParams(); I != N; ++I) {
2433       unsigned Size =
2434           DL.getTypeAllocSize(DFSF.DFS.getShadowTy(FT->getParamType(I)));
2435       // Stop storing if arguments' size overflows. Inside a function, arguments
2436       // after overflow have zero shadow values.
2437       if (ArgOffset + Size > kArgTLSSize)
2438         break;
2439       IRB.CreateAlignedStore(
2440           DFSF.getShadow(CB.getArgOperand(I)),
2441           DFSF.getArgTLS(FT->getParamType(I), ArgOffset, IRB),
2442           kShadowTLSAlignment);
2443       ArgOffset += alignTo(Size, kShadowTLSAlignment);
2444     }
2445   }
2446 
2447   Instruction *Next = nullptr;
2448   if (!CB.getType()->isVoidTy()) {
2449     if (InvokeInst *II = dyn_cast<InvokeInst>(&CB)) {
2450       if (II->getNormalDest()->getSinglePredecessor()) {
2451         Next = &II->getNormalDest()->front();
2452       } else {
2453         BasicBlock *NewBB =
2454             SplitEdge(II->getParent(), II->getNormalDest(), &DFSF.DT);
2455         Next = &NewBB->front();
2456       }
2457     } else {
2458       assert(CB.getIterator() != CB.getParent()->end());
2459       Next = CB.getNextNode();
2460     }
2461 
2462     if (DFSF.DFS.getInstrumentedABI() == DataFlowSanitizer::IA_TLS) {
2463       // Loads the return value shadow.
2464       IRBuilder<> NextIRB(Next);
2465       const DataLayout &DL = getDataLayout();
2466       unsigned Size = DL.getTypeAllocSize(DFSF.DFS.getShadowTy(&CB));
2467       if (Size > kRetvalTLSSize) {
2468         // Set overflowed return shadow to be zero.
2469         DFSF.setShadow(&CB, DFSF.DFS.getZeroShadow(&CB));
2470       } else {
2471         LoadInst *LI = NextIRB.CreateAlignedLoad(
2472             DFSF.DFS.getShadowTy(&CB), DFSF.getRetvalTLS(CB.getType(), NextIRB),
2473             kShadowTLSAlignment, "_dfsret");
2474         DFSF.SkipInsts.insert(LI);
2475         DFSF.setShadow(&CB, LI);
2476         DFSF.NonZeroChecks.push_back(LI);
2477       }
2478     }
2479   }
2480 
2481   // Do all instrumentation for IA_Args down here to defer tampering with the
2482   // CFG in a way that SplitEdge may be able to detect.
2483   if (DFSF.DFS.getInstrumentedABI() == DataFlowSanitizer::IA_Args) {
2484     FunctionType *NewFT = DFSF.DFS.getArgsFunctionType(FT);
2485     Value *Func =
2486         IRB.CreateBitCast(CB.getCalledOperand(), PointerType::getUnqual(NewFT));
2487     std::vector<Value *> Args;
2488 
2489     auto i = CB.arg_begin(), E = CB.arg_end();
2490     for (unsigned n = FT->getNumParams(); n != 0; ++i, --n)
2491       Args.push_back(*i);
2492 
2493     i = CB.arg_begin();
2494     for (unsigned n = FT->getNumParams(); n != 0; ++i, --n)
2495       Args.push_back(DFSF.getShadow(*i));
2496 
2497     if (FT->isVarArg()) {
2498       unsigned VarArgSize = CB.arg_size() - FT->getNumParams();
2499       ArrayType *VarArgArrayTy =
2500           ArrayType::get(DFSF.DFS.PrimitiveShadowTy, VarArgSize);
2501       AllocaInst *VarArgShadow =
2502         new AllocaInst(VarArgArrayTy, getDataLayout().getAllocaAddrSpace(),
2503                        "", &DFSF.F->getEntryBlock().front());
2504       Args.push_back(IRB.CreateConstGEP2_32(VarArgArrayTy, VarArgShadow, 0, 0));
2505       for (unsigned n = 0; i != E; ++i, ++n) {
2506         IRB.CreateStore(
2507             DFSF.getShadow(*i),
2508             IRB.CreateConstGEP2_32(VarArgArrayTy, VarArgShadow, 0, n));
2509         Args.push_back(*i);
2510       }
2511     }
2512 
2513     CallBase *NewCB;
2514     if (InvokeInst *II = dyn_cast<InvokeInst>(&CB)) {
2515       NewCB = IRB.CreateInvoke(NewFT, Func, II->getNormalDest(),
2516                                II->getUnwindDest(), Args);
2517     } else {
2518       NewCB = IRB.CreateCall(NewFT, Func, Args);
2519     }
2520     NewCB->setCallingConv(CB.getCallingConv());
2521     NewCB->setAttributes(CB.getAttributes().removeAttributes(
2522         *DFSF.DFS.Ctx, AttributeList::ReturnIndex,
2523         AttributeFuncs::typeIncompatible(NewCB->getType())));
2524 
2525     if (Next) {
2526       ExtractValueInst *ExVal = ExtractValueInst::Create(NewCB, 0, "", Next);
2527       DFSF.SkipInsts.insert(ExVal);
2528       ExtractValueInst *ExShadow = ExtractValueInst::Create(NewCB, 1, "", Next);
2529       DFSF.SkipInsts.insert(ExShadow);
2530       DFSF.setShadow(ExVal, ExShadow);
2531       DFSF.NonZeroChecks.push_back(ExShadow);
2532 
2533       CB.replaceAllUsesWith(ExVal);
2534     }
2535 
2536     CB.eraseFromParent();
2537   }
2538 }
2539 
2540 void DFSanVisitor::visitPHINode(PHINode &PN) {
2541   Type *ShadowTy = DFSF.DFS.getShadowTy(&PN);
2542   PHINode *ShadowPN =
2543       PHINode::Create(ShadowTy, PN.getNumIncomingValues(), "", &PN);
2544 
2545   // Give the shadow phi node valid predecessors to fool SplitEdge into working.
2546   Value *UndefShadow = UndefValue::get(ShadowTy);
2547   for (PHINode::block_iterator i = PN.block_begin(), e = PN.block_end(); i != e;
2548        ++i) {
2549     ShadowPN->addIncoming(UndefShadow, *i);
2550   }
2551 
2552   DFSF.PHIFixups.push_back(std::make_pair(&PN, ShadowPN));
2553   DFSF.setShadow(&PN, ShadowPN);
2554 }
2555 
2556 namespace {
2557 class DataFlowSanitizerLegacyPass : public ModulePass {
2558 private:
2559   std::vector<std::string> ABIListFiles;
2560 
2561 public:
2562   static char ID;
2563 
2564   DataFlowSanitizerLegacyPass(
2565       const std::vector<std::string> &ABIListFiles = std::vector<std::string>())
2566       : ModulePass(ID), ABIListFiles(ABIListFiles) {}
2567 
2568   bool runOnModule(Module &M) override {
2569     return DataFlowSanitizer(ABIListFiles).runImpl(M);
2570   }
2571 };
2572 } // namespace
2573 
2574 char DataFlowSanitizerLegacyPass::ID;
2575 
2576 INITIALIZE_PASS(DataFlowSanitizerLegacyPass, "dfsan",
2577                 "DataFlowSanitizer: dynamic data flow analysis.", false, false)
2578 
2579 ModulePass *llvm::createDataFlowSanitizerLegacyPassPass(
2580     const std::vector<std::string> &ABIListFiles) {
2581   return new DataFlowSanitizerLegacyPass(ABIListFiles);
2582 }
2583 
2584 PreservedAnalyses DataFlowSanitizerPass::run(Module &M,
2585                                              ModuleAnalysisManager &AM) {
2586   if (DataFlowSanitizer(ABIListFiles).runImpl(M)) {
2587     return PreservedAnalyses::none();
2588   }
2589   return PreservedAnalyses::all();
2590 }
2591