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.
20 ///
21 /// Each byte of application memory is backed by a shadow memory byte. The
22 /// shadow byte can represent up to 8 labels. On Linux/x86_64, memory is then
23 /// laid out as follows:
24 ///
25 /// +--------------------+ 0x800000000000 (top of memory)
26 /// |    application 3   |
27 /// +--------------------+ 0x700000000000
28 /// |      invalid       |
29 /// +--------------------+ 0x610000000000
30 /// |      origin 1      |
31 /// +--------------------+ 0x600000000000
32 /// |    application 2   |
33 /// +--------------------+ 0x510000000000
34 /// |      shadow 1      |
35 /// +--------------------+ 0x500000000000
36 /// |      invalid       |
37 /// +--------------------+ 0x400000000000
38 /// |      origin 3      |
39 /// +--------------------+ 0x300000000000
40 /// |      shadow 3      |
41 /// +--------------------+ 0x200000000000
42 /// |      origin 2      |
43 /// +--------------------+ 0x110000000000
44 /// |      invalid       |
45 /// +--------------------+ 0x100000000000
46 /// |      shadow 2      |
47 /// +--------------------+ 0x010000000000
48 /// |    application 1   |
49 /// +--------------------+ 0x000000000000
50 ///
51 /// MEM_TO_SHADOW(mem) = mem ^ 0x500000000000
52 /// SHADOW_TO_ORIGIN(shadow) = shadow + 0x100000000000
53 ///
54 /// For more information, please refer to the design document:
55 /// http://clang.llvm.org/docs/DataFlowSanitizerDesign.html
56 //
57 //===----------------------------------------------------------------------===//
58 
59 #include "llvm/Transforms/Instrumentation/DataFlowSanitizer.h"
60 #include "llvm/ADT/DenseMap.h"
61 #include "llvm/ADT/DenseSet.h"
62 #include "llvm/ADT/DepthFirstIterator.h"
63 #include "llvm/ADT/None.h"
64 #include "llvm/ADT/SmallPtrSet.h"
65 #include "llvm/ADT/SmallVector.h"
66 #include "llvm/ADT/StringExtras.h"
67 #include "llvm/ADT/StringRef.h"
68 #include "llvm/ADT/Triple.h"
69 #include "llvm/ADT/iterator.h"
70 #include "llvm/Analysis/ValueTracking.h"
71 #include "llvm/IR/Argument.h"
72 #include "llvm/IR/Attributes.h"
73 #include "llvm/IR/BasicBlock.h"
74 #include "llvm/IR/Constant.h"
75 #include "llvm/IR/Constants.h"
76 #include "llvm/IR/DataLayout.h"
77 #include "llvm/IR/DerivedTypes.h"
78 #include "llvm/IR/Dominators.h"
79 #include "llvm/IR/Function.h"
80 #include "llvm/IR/GlobalAlias.h"
81 #include "llvm/IR/GlobalValue.h"
82 #include "llvm/IR/GlobalVariable.h"
83 #include "llvm/IR/IRBuilder.h"
84 #include "llvm/IR/InlineAsm.h"
85 #include "llvm/IR/InstVisitor.h"
86 #include "llvm/IR/InstrTypes.h"
87 #include "llvm/IR/Instruction.h"
88 #include "llvm/IR/Instructions.h"
89 #include "llvm/IR/IntrinsicInst.h"
90 #include "llvm/IR/LLVMContext.h"
91 #include "llvm/IR/MDBuilder.h"
92 #include "llvm/IR/Module.h"
93 #include "llvm/IR/PassManager.h"
94 #include "llvm/IR/Type.h"
95 #include "llvm/IR/User.h"
96 #include "llvm/IR/Value.h"
97 #include "llvm/InitializePasses.h"
98 #include "llvm/Pass.h"
99 #include "llvm/Support/Alignment.h"
100 #include "llvm/Support/Casting.h"
101 #include "llvm/Support/CommandLine.h"
102 #include "llvm/Support/ErrorHandling.h"
103 #include "llvm/Support/SpecialCaseList.h"
104 #include "llvm/Support/VirtualFileSystem.h"
105 #include "llvm/Transforms/Instrumentation.h"
106 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
107 #include "llvm/Transforms/Utils/Local.h"
108 #include <algorithm>
109 #include <cassert>
110 #include <cstddef>
111 #include <cstdint>
112 #include <iterator>
113 #include <memory>
114 #include <set>
115 #include <string>
116 #include <utility>
117 #include <vector>
118 
119 using namespace llvm;
120 
121 // This must be consistent with ShadowWidthBits.
122 static const Align ShadowTLSAlignment = Align(2);
123 
124 static const Align MinOriginAlignment = Align(4);
125 
126 // The size of TLS variables. These constants must be kept in sync with the ones
127 // in dfsan.cpp.
128 static const unsigned ArgTLSSize = 800;
129 static const unsigned RetvalTLSSize = 800;
130 
131 // The -dfsan-preserve-alignment flag controls whether this pass assumes that
132 // alignment requirements provided by the input IR are correct.  For example,
133 // if the input IR contains a load with alignment 8, this flag will cause
134 // the shadow load to have alignment 16.  This flag is disabled by default as
135 // we have unfortunately encountered too much code (including Clang itself;
136 // see PR14291) which performs misaligned access.
137 static cl::opt<bool> ClPreserveAlignment(
138     "dfsan-preserve-alignment",
139     cl::desc("respect alignment requirements provided by input IR"), cl::Hidden,
140     cl::init(false));
141 
142 // The ABI list files control how shadow parameters are passed. The pass treats
143 // every function labelled "uninstrumented" in the ABI list file as conforming
144 // to the "native" (i.e. unsanitized) ABI.  Unless the ABI list contains
145 // additional annotations for those functions, a call to one of those functions
146 // will produce a warning message, as the labelling behaviour of the function is
147 // unknown.  The other supported annotations are "functional" and "discard",
148 // which are described below under DataFlowSanitizer::WrapperKind.
149 static cl::list<std::string> ClABIListFiles(
150     "dfsan-abilist",
151     cl::desc("File listing native ABI functions and how the pass treats them"),
152     cl::Hidden);
153 
154 // Controls whether the pass uses IA_Args or IA_TLS as the ABI for instrumented
155 // functions (see DataFlowSanitizer::InstrumentedABI below).
156 static cl::opt<bool>
157     ClArgsABI("dfsan-args-abi",
158               cl::desc("Use the argument ABI rather than the TLS ABI"),
159               cl::Hidden);
160 
161 // Controls whether the pass includes or ignores the labels of pointers in load
162 // instructions.
163 static cl::opt<bool> ClCombinePointerLabelsOnLoad(
164     "dfsan-combine-pointer-labels-on-load",
165     cl::desc("Combine the label of the pointer with the label of the data when "
166              "loading from memory."),
167     cl::Hidden, cl::init(true));
168 
169 // Controls whether the pass includes or ignores the labels of pointers in
170 // stores instructions.
171 static cl::opt<bool> ClCombinePointerLabelsOnStore(
172     "dfsan-combine-pointer-labels-on-store",
173     cl::desc("Combine the label of the pointer with the label of the data when "
174              "storing in memory."),
175     cl::Hidden, cl::init(false));
176 
177 // Controls whether the pass propagates labels of offsets in GEP instructions.
178 static cl::opt<bool> ClCombineOffsetLabelsOnGEP(
179     "dfsan-combine-offset-labels-on-gep",
180     cl::desc(
181         "Combine the label of the offset with the label of the pointer when "
182         "doing pointer arithmetic."),
183     cl::Hidden, cl::init(true));
184 
185 static cl::opt<bool> ClDebugNonzeroLabels(
186     "dfsan-debug-nonzero-labels",
187     cl::desc("Insert calls to __dfsan_nonzero_label on observing a parameter, "
188              "load or return with a nonzero label"),
189     cl::Hidden);
190 
191 // Experimental feature that inserts callbacks for certain data events.
192 // Currently callbacks are only inserted for loads, stores, memory transfers
193 // (i.e. memcpy and memmove), and comparisons.
194 //
195 // If this flag is set to true, the user must provide definitions for the
196 // following callback functions:
197 //   void __dfsan_load_callback(dfsan_label Label, void* addr);
198 //   void __dfsan_store_callback(dfsan_label Label, void* addr);
199 //   void __dfsan_mem_transfer_callback(dfsan_label *Start, size_t Len);
200 //   void __dfsan_cmp_callback(dfsan_label CombinedLabel);
201 static cl::opt<bool> ClEventCallbacks(
202     "dfsan-event-callbacks",
203     cl::desc("Insert calls to __dfsan_*_callback functions on data events."),
204     cl::Hidden, cl::init(false));
205 
206 // Controls whether the pass tracks the control flow of select instructions.
207 static cl::opt<bool> ClTrackSelectControlFlow(
208     "dfsan-track-select-control-flow",
209     cl::desc("Propagate labels from condition values of select instructions "
210              "to results."),
211     cl::Hidden, cl::init(true));
212 
213 // TODO: This default value follows MSan. DFSan may use a different value.
214 static cl::opt<int> ClInstrumentWithCallThreshold(
215     "dfsan-instrument-with-call-threshold",
216     cl::desc("If the function being instrumented requires more than "
217              "this number of origin stores, use callbacks instead of "
218              "inline checks (-1 means never use callbacks)."),
219     cl::Hidden, cl::init(3500));
220 
221 // Controls how to track origins.
222 // * 0: do not track origins.
223 // * 1: track origins at memory store operations.
224 // * 2: track origins at memory load and store operations.
225 //      TODO: track callsites.
226 static cl::opt<int> ClTrackOrigins("dfsan-track-origins",
227                                    cl::desc("Track origins of labels"),
228                                    cl::Hidden, cl::init(0));
229 
230 static StringRef getGlobalTypeString(const GlobalValue &G) {
231   // Types of GlobalVariables are always pointer types.
232   Type *GType = G.getValueType();
233   // For now we support excluding struct types only.
234   if (StructType *SGType = dyn_cast<StructType>(GType)) {
235     if (!SGType->isLiteral())
236       return SGType->getName();
237   }
238   return "<unknown type>";
239 }
240 
241 namespace {
242 
243 // Memory map parameters used in application-to-shadow address calculation.
244 // Offset = (Addr & ~AndMask) ^ XorMask
245 // Shadow = ShadowBase + Offset
246 // Origin = (OriginBase + Offset) & ~3ULL
247 struct MemoryMapParams {
248   uint64_t AndMask;
249   uint64_t XorMask;
250   uint64_t ShadowBase;
251   uint64_t OriginBase;
252 };
253 
254 } // end anonymous namespace
255 
256 // x86_64 Linux
257 // NOLINTNEXTLINE(readability-identifier-naming)
258 static const MemoryMapParams Linux_X86_64_MemoryMapParams = {
259     0,              // AndMask (not used)
260     0x500000000000, // XorMask
261     0,              // ShadowBase (not used)
262     0x100000000000, // OriginBase
263 };
264 
265 namespace {
266 
267 class DFSanABIList {
268   std::unique_ptr<SpecialCaseList> SCL;
269 
270 public:
271   DFSanABIList() = default;
272 
273   void set(std::unique_ptr<SpecialCaseList> List) { SCL = std::move(List); }
274 
275   /// Returns whether either this function or its source file are listed in the
276   /// given category.
277   bool isIn(const Function &F, StringRef Category) const {
278     return isIn(*F.getParent(), Category) ||
279            SCL->inSection("dataflow", "fun", F.getName(), Category);
280   }
281 
282   /// Returns whether this global alias is listed in the given category.
283   ///
284   /// If GA aliases a function, the alias's name is matched as a function name
285   /// would be.  Similarly, aliases of globals are matched like globals.
286   bool isIn(const GlobalAlias &GA, StringRef Category) const {
287     if (isIn(*GA.getParent(), Category))
288       return true;
289 
290     if (isa<FunctionType>(GA.getValueType()))
291       return SCL->inSection("dataflow", "fun", GA.getName(), Category);
292 
293     return SCL->inSection("dataflow", "global", GA.getName(), Category) ||
294            SCL->inSection("dataflow", "type", getGlobalTypeString(GA),
295                           Category);
296   }
297 
298   /// Returns whether this module is listed in the given category.
299   bool isIn(const Module &M, StringRef Category) const {
300     return SCL->inSection("dataflow", "src", M.getModuleIdentifier(), Category);
301   }
302 };
303 
304 /// TransformedFunction is used to express the result of transforming one
305 /// function type into another.  This struct is immutable.  It holds metadata
306 /// useful for updating calls of the old function to the new type.
307 struct TransformedFunction {
308   TransformedFunction(FunctionType *OriginalType, FunctionType *TransformedType,
309                       std::vector<unsigned> ArgumentIndexMapping)
310       : OriginalType(OriginalType), TransformedType(TransformedType),
311         ArgumentIndexMapping(ArgumentIndexMapping) {}
312 
313   // Disallow copies.
314   TransformedFunction(const TransformedFunction &) = delete;
315   TransformedFunction &operator=(const TransformedFunction &) = delete;
316 
317   // Allow moves.
318   TransformedFunction(TransformedFunction &&) = default;
319   TransformedFunction &operator=(TransformedFunction &&) = default;
320 
321   /// Type of the function before the transformation.
322   FunctionType *OriginalType;
323 
324   /// Type of the function after the transformation.
325   FunctionType *TransformedType;
326 
327   /// Transforming a function may change the position of arguments.  This
328   /// member records the mapping from each argument's old position to its new
329   /// position.  Argument positions are zero-indexed.  If the transformation
330   /// from F to F' made the first argument of F into the third argument of F',
331   /// then ArgumentIndexMapping[0] will equal 2.
332   std::vector<unsigned> ArgumentIndexMapping;
333 };
334 
335 /// Given function attributes from a call site for the original function,
336 /// return function attributes appropriate for a call to the transformed
337 /// function.
338 AttributeList
339 transformFunctionAttributes(const TransformedFunction &TransformedFunction,
340                             LLVMContext &Ctx, AttributeList CallSiteAttrs) {
341 
342   // Construct a vector of AttributeSet for each function argument.
343   std::vector<llvm::AttributeSet> ArgumentAttributes(
344       TransformedFunction.TransformedType->getNumParams());
345 
346   // Copy attributes from the parameter of the original function to the
347   // transformed version.  'ArgumentIndexMapping' holds the mapping from
348   // old argument position to new.
349   for (unsigned I = 0, IE = TransformedFunction.ArgumentIndexMapping.size();
350        I < IE; ++I) {
351     unsigned TransformedIndex = TransformedFunction.ArgumentIndexMapping[I];
352     ArgumentAttributes[TransformedIndex] = CallSiteAttrs.getParamAttributes(I);
353   }
354 
355   // Copy annotations on varargs arguments.
356   for (unsigned I = TransformedFunction.OriginalType->getNumParams(),
357                 IE = CallSiteAttrs.getNumAttrSets();
358        I < IE; ++I) {
359     ArgumentAttributes.push_back(CallSiteAttrs.getParamAttributes(I));
360   }
361 
362   return AttributeList::get(Ctx, CallSiteAttrs.getFnAttributes(),
363                             CallSiteAttrs.getRetAttributes(),
364                             llvm::makeArrayRef(ArgumentAttributes));
365 }
366 
367 class DataFlowSanitizer {
368   friend struct DFSanFunction;
369   friend class DFSanVisitor;
370 
371   enum { ShadowWidthBits = 8, ShadowWidthBytes = ShadowWidthBits / 8 };
372 
373   enum { OriginWidthBits = 32, OriginWidthBytes = OriginWidthBits / 8 };
374 
375   /// Which ABI should be used for instrumented functions?
376   enum InstrumentedABI {
377     /// Argument and return value labels are passed through additional
378     /// arguments and by modifying the return type.
379     IA_Args,
380 
381     /// Argument and return value labels are passed through TLS variables
382     /// __dfsan_arg_tls and __dfsan_retval_tls.
383     IA_TLS
384   };
385 
386   /// How should calls to uninstrumented functions be handled?
387   enum WrapperKind {
388     /// This function is present in an uninstrumented form but we don't know
389     /// how it should be handled.  Print a warning and call the function anyway.
390     /// Don't label the return value.
391     WK_Warning,
392 
393     /// This function does not write to (user-accessible) memory, and its return
394     /// value is unlabelled.
395     WK_Discard,
396 
397     /// This function does not write to (user-accessible) memory, and the label
398     /// of its return value is the union of the label of its arguments.
399     WK_Functional,
400 
401     /// Instead of calling the function, a custom wrapper __dfsw_F is called,
402     /// where F is the name of the function.  This function may wrap the
403     /// original function or provide its own implementation.  This is similar to
404     /// the IA_Args ABI, except that IA_Args uses a struct return type to
405     /// pass the return value shadow in a register, while WK_Custom uses an
406     /// extra pointer argument to return the shadow.  This allows the wrapped
407     /// form of the function type to be expressed in C.
408     WK_Custom
409   };
410 
411   Module *Mod;
412   LLVMContext *Ctx;
413   Type *Int8Ptr;
414   IntegerType *OriginTy;
415   PointerType *OriginPtrTy;
416   ConstantInt *ZeroOrigin;
417   /// The shadow type for all primitive types and vector types.
418   IntegerType *PrimitiveShadowTy;
419   PointerType *PrimitiveShadowPtrTy;
420   IntegerType *IntptrTy;
421   ConstantInt *ZeroPrimitiveShadow;
422   Constant *ArgTLS;
423   ArrayType *ArgOriginTLSTy;
424   Constant *ArgOriginTLS;
425   Constant *RetvalTLS;
426   Constant *RetvalOriginTLS;
427   FunctionType *DFSanUnionLoadFnTy;
428   FunctionType *DFSanLoadLabelAndOriginFnTy;
429   FunctionType *DFSanUnimplementedFnTy;
430   FunctionType *DFSanSetLabelFnTy;
431   FunctionType *DFSanNonzeroLabelFnTy;
432   FunctionType *DFSanVarargWrapperFnTy;
433   FunctionType *DFSanCmpCallbackFnTy;
434   FunctionType *DFSanLoadStoreCallbackFnTy;
435   FunctionType *DFSanMemTransferCallbackFnTy;
436   FunctionType *DFSanChainOriginFnTy;
437   FunctionType *DFSanChainOriginIfTaintedFnTy;
438   FunctionType *DFSanMemOriginTransferFnTy;
439   FunctionType *DFSanMaybeStoreOriginFnTy;
440   FunctionCallee DFSanUnionLoadFn;
441   FunctionCallee DFSanLoadLabelAndOriginFn;
442   FunctionCallee DFSanUnimplementedFn;
443   FunctionCallee DFSanSetLabelFn;
444   FunctionCallee DFSanNonzeroLabelFn;
445   FunctionCallee DFSanVarargWrapperFn;
446   FunctionCallee DFSanLoadCallbackFn;
447   FunctionCallee DFSanStoreCallbackFn;
448   FunctionCallee DFSanMemTransferCallbackFn;
449   FunctionCallee DFSanCmpCallbackFn;
450   FunctionCallee DFSanChainOriginFn;
451   FunctionCallee DFSanChainOriginIfTaintedFn;
452   FunctionCallee DFSanMemOriginTransferFn;
453   FunctionCallee DFSanMaybeStoreOriginFn;
454   SmallPtrSet<Value *, 16> DFSanRuntimeFunctions;
455   MDNode *ColdCallWeights;
456   MDNode *OriginStoreWeights;
457   DFSanABIList ABIList;
458   DenseMap<Value *, Function *> UnwrappedFnMap;
459   AttrBuilder ReadOnlyNoneAttrs;
460 
461   /// Memory map parameters used in calculation mapping application addresses
462   /// to shadow addresses and origin addresses.
463   const MemoryMapParams *MapParams;
464 
465   Value *getShadowOffset(Value *Addr, IRBuilder<> &IRB);
466   Value *getShadowAddress(Value *Addr, Instruction *Pos);
467   Value *getShadowAddress(Value *Addr, Instruction *Pos, Value *ShadowOffset);
468   std::pair<Value *, Value *>
469   getShadowOriginAddress(Value *Addr, Align InstAlignment, Instruction *Pos);
470   bool isInstrumented(const Function *F);
471   bool isInstrumented(const GlobalAlias *GA);
472   FunctionType *getArgsFunctionType(FunctionType *T);
473   FunctionType *getTrampolineFunctionType(FunctionType *T);
474   TransformedFunction getCustomFunctionType(FunctionType *T);
475   InstrumentedABI getInstrumentedABI();
476   WrapperKind getWrapperKind(Function *F);
477   void addGlobalNameSuffix(GlobalValue *GV);
478   Function *buildWrapperFunction(Function *F, StringRef NewFName,
479                                  GlobalValue::LinkageTypes NewFLink,
480                                  FunctionType *NewFT);
481   Constant *getOrBuildTrampolineFunction(FunctionType *FT, StringRef FName);
482   void initializeCallbackFunctions(Module &M);
483   void initializeRuntimeFunctions(Module &M);
484   void injectMetadataGlobals(Module &M);
485   bool initializeModule(Module &M);
486 
487   /// Advances \p OriginAddr to point to the next 32-bit origin and then loads
488   /// from it. Returns the origin's loaded value.
489   Value *loadNextOrigin(Instruction *Pos, Align OriginAlign,
490                         Value **OriginAddr);
491 
492   /// Returns whether the given load byte size is amenable to inlined
493   /// optimization patterns.
494   bool hasLoadSizeForFastPath(uint64_t Size);
495 
496   /// Returns whether the pass tracks origins. Supports only TLS ABI mode.
497   bool shouldTrackOrigins();
498 
499   /// Returns whether the pass tracks labels for struct fields and array
500   /// indices. Supports only TLS ABI mode.
501   bool shouldTrackFieldsAndIndices();
502 
503   /// Returns a zero constant with the shadow type of OrigTy.
504   ///
505   /// getZeroShadow({T1,T2,...}) = {getZeroShadow(T1),getZeroShadow(T2,...}
506   /// getZeroShadow([n x T]) = [n x getZeroShadow(T)]
507   /// getZeroShadow(other type) = i16(0)
508   ///
509   /// Note that a zero shadow is always i16(0) when shouldTrackFieldsAndIndices
510   /// returns false.
511   Constant *getZeroShadow(Type *OrigTy);
512   /// Returns a zero constant with the shadow type of V's type.
513   Constant *getZeroShadow(Value *V);
514 
515   /// Checks if V is a zero shadow.
516   bool isZeroShadow(Value *V);
517 
518   /// Returns the shadow type of OrigTy.
519   ///
520   /// getShadowTy({T1,T2,...}) = {getShadowTy(T1),getShadowTy(T2),...}
521   /// getShadowTy([n x T]) = [n x getShadowTy(T)]
522   /// getShadowTy(other type) = i16
523   ///
524   /// Note that a shadow type is always i16 when shouldTrackFieldsAndIndices
525   /// returns false.
526   Type *getShadowTy(Type *OrigTy);
527   /// Returns the shadow type of of V's type.
528   Type *getShadowTy(Value *V);
529 
530   const uint64_t NumOfElementsInArgOrgTLS = ArgTLSSize / OriginWidthBytes;
531 
532 public:
533   DataFlowSanitizer(const std::vector<std::string> &ABIListFiles);
534 
535   bool runImpl(Module &M);
536 };
537 
538 struct DFSanFunction {
539   DataFlowSanitizer &DFS;
540   Function *F;
541   DominatorTree DT;
542   DataFlowSanitizer::InstrumentedABI IA;
543   bool IsNativeABI;
544   AllocaInst *LabelReturnAlloca = nullptr;
545   AllocaInst *OriginReturnAlloca = nullptr;
546   DenseMap<Value *, Value *> ValShadowMap;
547   DenseMap<Value *, Value *> ValOriginMap;
548   DenseMap<AllocaInst *, AllocaInst *> AllocaShadowMap;
549   DenseMap<AllocaInst *, AllocaInst *> AllocaOriginMap;
550 
551   struct PHIFixupElement {
552     PHINode *Phi;
553     PHINode *ShadowPhi;
554     PHINode *OriginPhi;
555   };
556   std::vector<PHIFixupElement> PHIFixups;
557 
558   DenseSet<Instruction *> SkipInsts;
559   std::vector<Value *> NonZeroChecks;
560 
561   struct CachedShadow {
562     BasicBlock *Block; // The block where Shadow is defined.
563     Value *Shadow;
564   };
565   /// Maps a value to its latest shadow value in terms of domination tree.
566   DenseMap<std::pair<Value *, Value *>, CachedShadow> CachedShadows;
567   /// Maps a value to its latest collapsed shadow value it was converted to in
568   /// terms of domination tree. When ClDebugNonzeroLabels is on, this cache is
569   /// used at a post process where CFG blocks are split. So it does not cache
570   /// BasicBlock like CachedShadows, but uses domination between values.
571   DenseMap<Value *, Value *> CachedCollapsedShadows;
572   DenseMap<Value *, std::set<Value *>> ShadowElements;
573 
574   DFSanFunction(DataFlowSanitizer &DFS, Function *F, bool IsNativeABI)
575       : DFS(DFS), F(F), IA(DFS.getInstrumentedABI()), IsNativeABI(IsNativeABI) {
576     DT.recalculate(*F);
577   }
578 
579   /// Computes the shadow address for a given function argument.
580   ///
581   /// Shadow = ArgTLS+ArgOffset.
582   Value *getArgTLS(Type *T, unsigned ArgOffset, IRBuilder<> &IRB);
583 
584   /// Computes the shadow address for a return value.
585   Value *getRetvalTLS(Type *T, IRBuilder<> &IRB);
586 
587   /// Computes the origin address for a given function argument.
588   ///
589   /// Origin = ArgOriginTLS[ArgNo].
590   Value *getArgOriginTLS(unsigned ArgNo, IRBuilder<> &IRB);
591 
592   /// Computes the origin address for a return value.
593   Value *getRetvalOriginTLS();
594 
595   Value *getOrigin(Value *V);
596   void setOrigin(Instruction *I, Value *Origin);
597   /// Generates IR to compute the origin of the last operand with a taint label.
598   Value *combineOperandOrigins(Instruction *Inst);
599   /// Before the instruction Pos, generates IR to compute the last origin with a
600   /// taint label. Labels and origins are from vectors Shadows and Origins
601   /// correspondingly. The generated IR is like
602   ///   Sn-1 != Zero ? On-1: ... S2 != Zero ? O2: S1 != Zero ? O1: O0
603   /// When Zero is nullptr, it uses ZeroPrimitiveShadow. Otherwise it can be
604   /// zeros with other bitwidths.
605   Value *combineOrigins(const std::vector<Value *> &Shadows,
606                         const std::vector<Value *> &Origins, Instruction *Pos,
607                         ConstantInt *Zero = nullptr);
608 
609   Value *getShadow(Value *V);
610   void setShadow(Instruction *I, Value *Shadow);
611   /// Generates IR to compute the union of the two given shadows, inserting it
612   /// before Pos. The combined value is with primitive type.
613   Value *combineShadows(Value *V1, Value *V2, Instruction *Pos);
614   /// Combines the shadow values of V1 and V2, then converts the combined value
615   /// with primitive type into a shadow value with the original type T.
616   Value *combineShadowsThenConvert(Type *T, Value *V1, Value *V2,
617                                    Instruction *Pos);
618   Value *combineOperandShadows(Instruction *Inst);
619 
620   /// Generates IR to load shadow and origin corresponding to bytes [\p
621   /// Addr, \p Addr + \p Size), where addr has alignment \p
622   /// InstAlignment, and take the union of each of those shadows. The returned
623   /// shadow always has primitive type.
624   ///
625   /// When tracking loads is enabled, the returned origin is a chain at the
626   /// current stack if the returned shadow is tainted.
627   std::pair<Value *, Value *> loadShadowOrigin(Value *Addr, uint64_t Size,
628                                                Align InstAlignment,
629                                                Instruction *Pos);
630 
631   void storePrimitiveShadowOrigin(Value *Addr, uint64_t Size,
632                                   Align InstAlignment, Value *PrimitiveShadow,
633                                   Value *Origin, Instruction *Pos);
634   /// Applies PrimitiveShadow to all primitive subtypes of T, returning
635   /// the expanded shadow value.
636   ///
637   /// EFP({T1,T2, ...}, PS) = {EFP(T1,PS),EFP(T2,PS),...}
638   /// EFP([n x T], PS) = [n x EFP(T,PS)]
639   /// EFP(other types, PS) = PS
640   Value *expandFromPrimitiveShadow(Type *T, Value *PrimitiveShadow,
641                                    Instruction *Pos);
642   /// Collapses Shadow into a single primitive shadow value, unioning all
643   /// primitive shadow values in the process. Returns the final primitive
644   /// shadow value.
645   ///
646   /// CTP({V1,V2, ...}) = UNION(CFP(V1,PS),CFP(V2,PS),...)
647   /// CTP([V1,V2,...]) = UNION(CFP(V1,PS),CFP(V2,PS),...)
648   /// CTP(other types, PS) = PS
649   Value *collapseToPrimitiveShadow(Value *Shadow, Instruction *Pos);
650 
651   void storeZeroPrimitiveShadow(Value *Addr, uint64_t Size, Align ShadowAlign,
652                                 Instruction *Pos);
653 
654   Align getShadowAlign(Align InstAlignment);
655 
656 private:
657   /// Collapses the shadow with aggregate type into a single primitive shadow
658   /// value.
659   template <class AggregateType>
660   Value *collapseAggregateShadow(AggregateType *AT, Value *Shadow,
661                                  IRBuilder<> &IRB);
662 
663   Value *collapseToPrimitiveShadow(Value *Shadow, IRBuilder<> &IRB);
664 
665   /// Returns the shadow value of an argument A.
666   Value *getShadowForTLSArgument(Argument *A);
667 
668   /// The fast path of loading shadows.
669   std::pair<Value *, Value *>
670   loadShadowFast(Value *ShadowAddr, Value *OriginAddr, uint64_t Size,
671                  Align ShadowAlign, Align OriginAlign, Value *FirstOrigin,
672                  Instruction *Pos);
673 
674   Align getOriginAlign(Align InstAlignment);
675 
676   /// Because 4 contiguous bytes share one 4-byte origin, the most accurate load
677   /// is __dfsan_load_label_and_origin. This function returns the union of all
678   /// labels and the origin of the first taint label. However this is an
679   /// additional call with many instructions. To ensure common cases are fast,
680   /// checks if it is possible to load labels and origins without using the
681   /// callback function.
682   ///
683   /// When enabling tracking load instructions, we always use
684   /// __dfsan_load_label_and_origin to reduce code size.
685   bool useCallbackLoadLabelAndOrigin(uint64_t Size, Align InstAlignment);
686 
687   /// Returns a chain at the current stack with previous origin V.
688   Value *updateOrigin(Value *V, IRBuilder<> &IRB);
689 
690   /// Returns a chain at the current stack with previous origin V if Shadow is
691   /// tainted.
692   Value *updateOriginIfTainted(Value *Shadow, Value *Origin, IRBuilder<> &IRB);
693 
694   /// Creates an Intptr = Origin | Origin << 32 if Intptr's size is 64. Returns
695   /// Origin otherwise.
696   Value *originToIntptr(IRBuilder<> &IRB, Value *Origin);
697 
698   /// Stores Origin into the address range [StoreOriginAddr, StoreOriginAddr +
699   /// Size).
700   void paintOrigin(IRBuilder<> &IRB, Value *Origin, Value *StoreOriginAddr,
701                    uint64_t StoreOriginSize, Align Alignment);
702 
703   /// Stores Origin in terms of its Shadow value.
704   /// * Do not write origins for zero shadows because we do not trace origins
705   ///   for untainted sinks.
706   /// * Use __dfsan_maybe_store_origin if there are too many origin store
707   ///   instrumentations.
708   void storeOrigin(Instruction *Pos, Value *Addr, uint64_t Size, Value *Shadow,
709                    Value *Origin, Value *StoreOriginAddr, Align InstAlignment);
710 
711   /// Convert a scalar value to an i1 by comparing with 0.
712   Value *convertToBool(Value *V, IRBuilder<> &IRB, const Twine &Name = "");
713 
714   bool shouldInstrumentWithCall();
715 
716   /// Generates IR to load shadow and origin corresponding to bytes [\p
717   /// Addr, \p Addr + \p Size), where addr has alignment \p
718   /// InstAlignment, and take the union of each of those shadows. The returned
719   /// shadow always has primitive type.
720   std::pair<Value *, Value *>
721   loadShadowOriginSansLoadTracking(Value *Addr, uint64_t Size,
722                                    Align InstAlignment, Instruction *Pos);
723   int NumOriginStores = 0;
724 };
725 
726 class DFSanVisitor : public InstVisitor<DFSanVisitor> {
727 public:
728   DFSanFunction &DFSF;
729 
730   DFSanVisitor(DFSanFunction &DFSF) : DFSF(DFSF) {}
731 
732   const DataLayout &getDataLayout() const {
733     return DFSF.F->getParent()->getDataLayout();
734   }
735 
736   // Combines shadow values and origins for all of I's operands.
737   void visitInstOperands(Instruction &I);
738 
739   void visitUnaryOperator(UnaryOperator &UO);
740   void visitBinaryOperator(BinaryOperator &BO);
741   void visitBitCastInst(BitCastInst &BCI);
742   void visitCastInst(CastInst &CI);
743   void visitCmpInst(CmpInst &CI);
744   void visitLandingPadInst(LandingPadInst &LPI);
745   void visitGetElementPtrInst(GetElementPtrInst &GEPI);
746   void visitLoadInst(LoadInst &LI);
747   void visitStoreInst(StoreInst &SI);
748   void visitAtomicRMWInst(AtomicRMWInst &I);
749   void visitAtomicCmpXchgInst(AtomicCmpXchgInst &I);
750   void visitReturnInst(ReturnInst &RI);
751   void visitCallBase(CallBase &CB);
752   void visitPHINode(PHINode &PN);
753   void visitExtractElementInst(ExtractElementInst &I);
754   void visitInsertElementInst(InsertElementInst &I);
755   void visitShuffleVectorInst(ShuffleVectorInst &I);
756   void visitExtractValueInst(ExtractValueInst &I);
757   void visitInsertValueInst(InsertValueInst &I);
758   void visitAllocaInst(AllocaInst &I);
759   void visitSelectInst(SelectInst &I);
760   void visitMemSetInst(MemSetInst &I);
761   void visitMemTransferInst(MemTransferInst &I);
762 
763 private:
764   void visitCASOrRMW(Align InstAlignment, Instruction &I);
765 
766   // Returns false when this is an invoke of a custom function.
767   bool visitWrappedCallBase(Function &F, CallBase &CB);
768 
769   // Combines origins for all of I's operands.
770   void visitInstOperandOrigins(Instruction &I);
771 
772   void addShadowArguments(Function &F, CallBase &CB, std::vector<Value *> &Args,
773                           IRBuilder<> &IRB);
774 
775   void addOriginArguments(Function &F, CallBase &CB, std::vector<Value *> &Args,
776                           IRBuilder<> &IRB);
777 };
778 
779 } // end anonymous namespace
780 
781 DataFlowSanitizer::DataFlowSanitizer(
782     const std::vector<std::string> &ABIListFiles) {
783   std::vector<std::string> AllABIListFiles(std::move(ABIListFiles));
784   llvm::append_range(AllABIListFiles, ClABIListFiles);
785   // FIXME: should we propagate vfs::FileSystem to this constructor?
786   ABIList.set(
787       SpecialCaseList::createOrDie(AllABIListFiles, *vfs::getRealFileSystem()));
788 }
789 
790 FunctionType *DataFlowSanitizer::getArgsFunctionType(FunctionType *T) {
791   SmallVector<Type *, 4> ArgTypes(T->param_begin(), T->param_end());
792   ArgTypes.append(T->getNumParams(), PrimitiveShadowTy);
793   if (T->isVarArg())
794     ArgTypes.push_back(PrimitiveShadowPtrTy);
795   Type *RetType = T->getReturnType();
796   if (!RetType->isVoidTy())
797     RetType = StructType::get(RetType, PrimitiveShadowTy);
798   return FunctionType::get(RetType, ArgTypes, T->isVarArg());
799 }
800 
801 FunctionType *DataFlowSanitizer::getTrampolineFunctionType(FunctionType *T) {
802   assert(!T->isVarArg());
803   SmallVector<Type *, 4> ArgTypes;
804   ArgTypes.push_back(T->getPointerTo());
805   ArgTypes.append(T->param_begin(), T->param_end());
806   ArgTypes.append(T->getNumParams(), PrimitiveShadowTy);
807   Type *RetType = T->getReturnType();
808   if (!RetType->isVoidTy())
809     ArgTypes.push_back(PrimitiveShadowPtrTy);
810 
811   if (shouldTrackOrigins()) {
812     ArgTypes.append(T->getNumParams(), OriginTy);
813     if (!RetType->isVoidTy())
814       ArgTypes.push_back(OriginPtrTy);
815   }
816 
817   return FunctionType::get(T->getReturnType(), ArgTypes, false);
818 }
819 
820 TransformedFunction DataFlowSanitizer::getCustomFunctionType(FunctionType *T) {
821   SmallVector<Type *, 4> ArgTypes;
822 
823   // Some parameters of the custom function being constructed are
824   // parameters of T.  Record the mapping from parameters of T to
825   // parameters of the custom function, so that parameter attributes
826   // at call sites can be updated.
827   std::vector<unsigned> ArgumentIndexMapping;
828   for (unsigned I = 0, E = T->getNumParams(); I != E; ++I) {
829     Type *ParamType = T->getParamType(I);
830     FunctionType *FT;
831     if (isa<PointerType>(ParamType) &&
832         (FT = dyn_cast<FunctionType>(ParamType->getPointerElementType()))) {
833       ArgumentIndexMapping.push_back(ArgTypes.size());
834       ArgTypes.push_back(getTrampolineFunctionType(FT)->getPointerTo());
835       ArgTypes.push_back(Type::getInt8PtrTy(*Ctx));
836     } else {
837       ArgumentIndexMapping.push_back(ArgTypes.size());
838       ArgTypes.push_back(ParamType);
839     }
840   }
841   for (unsigned I = 0, E = T->getNumParams(); I != E; ++I)
842     ArgTypes.push_back(PrimitiveShadowTy);
843   if (T->isVarArg())
844     ArgTypes.push_back(PrimitiveShadowPtrTy);
845   Type *RetType = T->getReturnType();
846   if (!RetType->isVoidTy())
847     ArgTypes.push_back(PrimitiveShadowPtrTy);
848 
849   if (shouldTrackOrigins()) {
850     for (unsigned I = 0, E = T->getNumParams(); I != E; ++I)
851       ArgTypes.push_back(OriginTy);
852     if (T->isVarArg())
853       ArgTypes.push_back(OriginPtrTy);
854     if (!RetType->isVoidTy())
855       ArgTypes.push_back(OriginPtrTy);
856   }
857 
858   return TransformedFunction(
859       T, FunctionType::get(T->getReturnType(), ArgTypes, T->isVarArg()),
860       ArgumentIndexMapping);
861 }
862 
863 bool DataFlowSanitizer::isZeroShadow(Value *V) {
864   if (!shouldTrackFieldsAndIndices())
865     return ZeroPrimitiveShadow == V;
866 
867   Type *T = V->getType();
868   if (!isa<ArrayType>(T) && !isa<StructType>(T)) {
869     if (const ConstantInt *CI = dyn_cast<ConstantInt>(V))
870       return CI->isZero();
871     return false;
872   }
873 
874   return isa<ConstantAggregateZero>(V);
875 }
876 
877 bool DataFlowSanitizer::hasLoadSizeForFastPath(uint64_t Size) {
878   uint64_t ShadowSize = Size * ShadowWidthBytes;
879   return ShadowSize % 8 == 0 || ShadowSize == 4;
880 }
881 
882 bool DataFlowSanitizer::shouldTrackOrigins() {
883   static const bool ShouldTrackOrigins =
884       ClTrackOrigins && getInstrumentedABI() == DataFlowSanitizer::IA_TLS;
885   return ShouldTrackOrigins;
886 }
887 
888 bool DataFlowSanitizer::shouldTrackFieldsAndIndices() {
889   return getInstrumentedABI() == DataFlowSanitizer::IA_TLS;
890 }
891 
892 Constant *DataFlowSanitizer::getZeroShadow(Type *OrigTy) {
893   if (!shouldTrackFieldsAndIndices())
894     return ZeroPrimitiveShadow;
895 
896   if (!isa<ArrayType>(OrigTy) && !isa<StructType>(OrigTy))
897     return ZeroPrimitiveShadow;
898   Type *ShadowTy = getShadowTy(OrigTy);
899   return ConstantAggregateZero::get(ShadowTy);
900 }
901 
902 Constant *DataFlowSanitizer::getZeroShadow(Value *V) {
903   return getZeroShadow(V->getType());
904 }
905 
906 static Value *expandFromPrimitiveShadowRecursive(
907     Value *Shadow, SmallVector<unsigned, 4> &Indices, Type *SubShadowTy,
908     Value *PrimitiveShadow, IRBuilder<> &IRB) {
909   if (!isa<ArrayType>(SubShadowTy) && !isa<StructType>(SubShadowTy))
910     return IRB.CreateInsertValue(Shadow, PrimitiveShadow, Indices);
911 
912   if (ArrayType *AT = dyn_cast<ArrayType>(SubShadowTy)) {
913     for (unsigned Idx = 0; Idx < AT->getNumElements(); Idx++) {
914       Indices.push_back(Idx);
915       Shadow = expandFromPrimitiveShadowRecursive(
916           Shadow, Indices, AT->getElementType(), PrimitiveShadow, IRB);
917       Indices.pop_back();
918     }
919     return Shadow;
920   }
921 
922   if (StructType *ST = dyn_cast<StructType>(SubShadowTy)) {
923     for (unsigned Idx = 0; Idx < ST->getNumElements(); Idx++) {
924       Indices.push_back(Idx);
925       Shadow = expandFromPrimitiveShadowRecursive(
926           Shadow, Indices, ST->getElementType(Idx), PrimitiveShadow, IRB);
927       Indices.pop_back();
928     }
929     return Shadow;
930   }
931   llvm_unreachable("Unexpected shadow type");
932 }
933 
934 bool DFSanFunction::shouldInstrumentWithCall() {
935   return ClInstrumentWithCallThreshold >= 0 &&
936          NumOriginStores >= ClInstrumentWithCallThreshold;
937 }
938 
939 Value *DFSanFunction::expandFromPrimitiveShadow(Type *T, Value *PrimitiveShadow,
940                                                 Instruction *Pos) {
941   Type *ShadowTy = DFS.getShadowTy(T);
942 
943   if (!isa<ArrayType>(ShadowTy) && !isa<StructType>(ShadowTy))
944     return PrimitiveShadow;
945 
946   if (DFS.isZeroShadow(PrimitiveShadow))
947     return DFS.getZeroShadow(ShadowTy);
948 
949   IRBuilder<> IRB(Pos);
950   SmallVector<unsigned, 4> Indices;
951   Value *Shadow = UndefValue::get(ShadowTy);
952   Shadow = expandFromPrimitiveShadowRecursive(Shadow, Indices, ShadowTy,
953                                               PrimitiveShadow, IRB);
954 
955   // Caches the primitive shadow value that built the shadow value.
956   CachedCollapsedShadows[Shadow] = PrimitiveShadow;
957   return Shadow;
958 }
959 
960 template <class AggregateType>
961 Value *DFSanFunction::collapseAggregateShadow(AggregateType *AT, Value *Shadow,
962                                               IRBuilder<> &IRB) {
963   if (!AT->getNumElements())
964     return DFS.ZeroPrimitiveShadow;
965 
966   Value *FirstItem = IRB.CreateExtractValue(Shadow, 0);
967   Value *Aggregator = collapseToPrimitiveShadow(FirstItem, IRB);
968 
969   for (unsigned Idx = 1; Idx < AT->getNumElements(); Idx++) {
970     Value *ShadowItem = IRB.CreateExtractValue(Shadow, Idx);
971     Value *ShadowInner = collapseToPrimitiveShadow(ShadowItem, IRB);
972     Aggregator = IRB.CreateOr(Aggregator, ShadowInner);
973   }
974   return Aggregator;
975 }
976 
977 Value *DFSanFunction::collapseToPrimitiveShadow(Value *Shadow,
978                                                 IRBuilder<> &IRB) {
979   Type *ShadowTy = Shadow->getType();
980   if (!isa<ArrayType>(ShadowTy) && !isa<StructType>(ShadowTy))
981     return Shadow;
982   if (ArrayType *AT = dyn_cast<ArrayType>(ShadowTy))
983     return collapseAggregateShadow<>(AT, Shadow, IRB);
984   if (StructType *ST = dyn_cast<StructType>(ShadowTy))
985     return collapseAggregateShadow<>(ST, Shadow, IRB);
986   llvm_unreachable("Unexpected shadow type");
987 }
988 
989 Value *DFSanFunction::collapseToPrimitiveShadow(Value *Shadow,
990                                                 Instruction *Pos) {
991   Type *ShadowTy = Shadow->getType();
992   if (!isa<ArrayType>(ShadowTy) && !isa<StructType>(ShadowTy))
993     return Shadow;
994 
995   assert(DFS.shouldTrackFieldsAndIndices());
996 
997   // Checks if the cached collapsed shadow value dominates Pos.
998   Value *&CS = CachedCollapsedShadows[Shadow];
999   if (CS && DT.dominates(CS, Pos))
1000     return CS;
1001 
1002   IRBuilder<> IRB(Pos);
1003   Value *PrimitiveShadow = collapseToPrimitiveShadow(Shadow, IRB);
1004   // Caches the converted primitive shadow value.
1005   CS = PrimitiveShadow;
1006   return PrimitiveShadow;
1007 }
1008 
1009 Type *DataFlowSanitizer::getShadowTy(Type *OrigTy) {
1010   if (!shouldTrackFieldsAndIndices())
1011     return PrimitiveShadowTy;
1012 
1013   if (!OrigTy->isSized())
1014     return PrimitiveShadowTy;
1015   if (isa<IntegerType>(OrigTy))
1016     return PrimitiveShadowTy;
1017   if (isa<VectorType>(OrigTy))
1018     return PrimitiveShadowTy;
1019   if (ArrayType *AT = dyn_cast<ArrayType>(OrigTy))
1020     return ArrayType::get(getShadowTy(AT->getElementType()),
1021                           AT->getNumElements());
1022   if (StructType *ST = dyn_cast<StructType>(OrigTy)) {
1023     SmallVector<Type *, 4> Elements;
1024     for (unsigned I = 0, N = ST->getNumElements(); I < N; ++I)
1025       Elements.push_back(getShadowTy(ST->getElementType(I)));
1026     return StructType::get(*Ctx, Elements);
1027   }
1028   return PrimitiveShadowTy;
1029 }
1030 
1031 Type *DataFlowSanitizer::getShadowTy(Value *V) {
1032   return getShadowTy(V->getType());
1033 }
1034 
1035 bool DataFlowSanitizer::initializeModule(Module &M) {
1036   Triple TargetTriple(M.getTargetTriple());
1037   const DataLayout &DL = M.getDataLayout();
1038 
1039   if (TargetTriple.getOS() != Triple::Linux)
1040     report_fatal_error("unsupported operating system");
1041   if (TargetTriple.getArch() != Triple::x86_64)
1042     report_fatal_error("unsupported architecture");
1043   MapParams = &Linux_X86_64_MemoryMapParams;
1044 
1045   Mod = &M;
1046   Ctx = &M.getContext();
1047   Int8Ptr = Type::getInt8PtrTy(*Ctx);
1048   OriginTy = IntegerType::get(*Ctx, OriginWidthBits);
1049   OriginPtrTy = PointerType::getUnqual(OriginTy);
1050   PrimitiveShadowTy = IntegerType::get(*Ctx, ShadowWidthBits);
1051   PrimitiveShadowPtrTy = PointerType::getUnqual(PrimitiveShadowTy);
1052   IntptrTy = DL.getIntPtrType(*Ctx);
1053   ZeroPrimitiveShadow = ConstantInt::getSigned(PrimitiveShadowTy, 0);
1054   ZeroOrigin = ConstantInt::getSigned(OriginTy, 0);
1055 
1056   Type *DFSanUnionLoadArgs[2] = {PrimitiveShadowPtrTy, IntptrTy};
1057   DFSanUnionLoadFnTy = FunctionType::get(PrimitiveShadowTy, DFSanUnionLoadArgs,
1058                                          /*isVarArg=*/false);
1059   Type *DFSanLoadLabelAndOriginArgs[2] = {Int8Ptr, IntptrTy};
1060   DFSanLoadLabelAndOriginFnTy =
1061       FunctionType::get(IntegerType::get(*Ctx, 64), DFSanLoadLabelAndOriginArgs,
1062                         /*isVarArg=*/false);
1063   DFSanUnimplementedFnTy = FunctionType::get(
1064       Type::getVoidTy(*Ctx), Type::getInt8PtrTy(*Ctx), /*isVarArg=*/false);
1065   Type *DFSanSetLabelArgs[4] = {PrimitiveShadowTy, OriginTy,
1066                                 Type::getInt8PtrTy(*Ctx), IntptrTy};
1067   DFSanSetLabelFnTy = FunctionType::get(Type::getVoidTy(*Ctx),
1068                                         DFSanSetLabelArgs, /*isVarArg=*/false);
1069   DFSanNonzeroLabelFnTy =
1070       FunctionType::get(Type::getVoidTy(*Ctx), None, /*isVarArg=*/false);
1071   DFSanVarargWrapperFnTy = FunctionType::get(
1072       Type::getVoidTy(*Ctx), Type::getInt8PtrTy(*Ctx), /*isVarArg=*/false);
1073   DFSanCmpCallbackFnTy =
1074       FunctionType::get(Type::getVoidTy(*Ctx), PrimitiveShadowTy,
1075                         /*isVarArg=*/false);
1076   DFSanChainOriginFnTy =
1077       FunctionType::get(OriginTy, OriginTy, /*isVarArg=*/false);
1078   Type *DFSanChainOriginIfTaintedArgs[2] = {PrimitiveShadowTy, OriginTy};
1079   DFSanChainOriginIfTaintedFnTy = FunctionType::get(
1080       OriginTy, DFSanChainOriginIfTaintedArgs, /*isVarArg=*/false);
1081   Type *DFSanMaybeStoreOriginArgs[4] = {IntegerType::get(*Ctx, ShadowWidthBits),
1082                                         Int8Ptr, IntptrTy, OriginTy};
1083   DFSanMaybeStoreOriginFnTy = FunctionType::get(
1084       Type::getVoidTy(*Ctx), DFSanMaybeStoreOriginArgs, /*isVarArg=*/false);
1085   Type *DFSanMemOriginTransferArgs[3] = {Int8Ptr, Int8Ptr, IntptrTy};
1086   DFSanMemOriginTransferFnTy = FunctionType::get(
1087       Type::getVoidTy(*Ctx), DFSanMemOriginTransferArgs, /*isVarArg=*/false);
1088   Type *DFSanLoadStoreCallbackArgs[2] = {PrimitiveShadowTy, Int8Ptr};
1089   DFSanLoadStoreCallbackFnTy =
1090       FunctionType::get(Type::getVoidTy(*Ctx), DFSanLoadStoreCallbackArgs,
1091                         /*isVarArg=*/false);
1092   Type *DFSanMemTransferCallbackArgs[2] = {PrimitiveShadowPtrTy, IntptrTy};
1093   DFSanMemTransferCallbackFnTy =
1094       FunctionType::get(Type::getVoidTy(*Ctx), DFSanMemTransferCallbackArgs,
1095                         /*isVarArg=*/false);
1096 
1097   ColdCallWeights = MDBuilder(*Ctx).createBranchWeights(1, 1000);
1098   OriginStoreWeights = MDBuilder(*Ctx).createBranchWeights(1, 1000);
1099   return true;
1100 }
1101 
1102 bool DataFlowSanitizer::isInstrumented(const Function *F) {
1103   return !ABIList.isIn(*F, "uninstrumented");
1104 }
1105 
1106 bool DataFlowSanitizer::isInstrumented(const GlobalAlias *GA) {
1107   return !ABIList.isIn(*GA, "uninstrumented");
1108 }
1109 
1110 DataFlowSanitizer::InstrumentedABI DataFlowSanitizer::getInstrumentedABI() {
1111   return ClArgsABI ? IA_Args : IA_TLS;
1112 }
1113 
1114 DataFlowSanitizer::WrapperKind DataFlowSanitizer::getWrapperKind(Function *F) {
1115   if (ABIList.isIn(*F, "functional"))
1116     return WK_Functional;
1117   if (ABIList.isIn(*F, "discard"))
1118     return WK_Discard;
1119   if (ABIList.isIn(*F, "custom"))
1120     return WK_Custom;
1121 
1122   return WK_Warning;
1123 }
1124 
1125 void DataFlowSanitizer::addGlobalNameSuffix(GlobalValue *GV) {
1126   std::string GVName = std::string(GV->getName()), Suffix = ".dfsan";
1127   GV->setName(GVName + Suffix);
1128 
1129   // Try to change the name of the function in module inline asm.  We only do
1130   // this for specific asm directives, currently only ".symver", to try to avoid
1131   // corrupting asm which happens to contain the symbol name as a substring.
1132   // Note that the substitution for .symver assumes that the versioned symbol
1133   // also has an instrumented name.
1134   std::string Asm = GV->getParent()->getModuleInlineAsm();
1135   std::string SearchStr = ".symver " + GVName + ",";
1136   size_t Pos = Asm.find(SearchStr);
1137   if (Pos != std::string::npos) {
1138     Asm.replace(Pos, SearchStr.size(), ".symver " + GVName + Suffix + ",");
1139     Pos = Asm.find("@");
1140 
1141     if (Pos == std::string::npos)
1142       report_fatal_error("unsupported .symver: " + Asm);
1143 
1144     Asm.replace(Pos, 1, Suffix + "@");
1145     GV->getParent()->setModuleInlineAsm(Asm);
1146   }
1147 }
1148 
1149 Function *
1150 DataFlowSanitizer::buildWrapperFunction(Function *F, StringRef NewFName,
1151                                         GlobalValue::LinkageTypes NewFLink,
1152                                         FunctionType *NewFT) {
1153   FunctionType *FT = F->getFunctionType();
1154   Function *NewF = Function::Create(NewFT, NewFLink, F->getAddressSpace(),
1155                                     NewFName, F->getParent());
1156   NewF->copyAttributesFrom(F);
1157   NewF->removeAttributes(
1158       AttributeList::ReturnIndex,
1159       AttributeFuncs::typeIncompatible(NewFT->getReturnType()));
1160 
1161   BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", NewF);
1162   if (F->isVarArg()) {
1163     NewF->removeAttributes(AttributeList::FunctionIndex,
1164                            AttrBuilder().addAttribute("split-stack"));
1165     CallInst::Create(DFSanVarargWrapperFn,
1166                      IRBuilder<>(BB).CreateGlobalStringPtr(F->getName()), "",
1167                      BB);
1168     new UnreachableInst(*Ctx, BB);
1169   } else {
1170     auto ArgIt = pointer_iterator<Argument *>(NewF->arg_begin());
1171     std::vector<Value *> Args(ArgIt, ArgIt + FT->getNumParams());
1172 
1173     CallInst *CI = CallInst::Create(F, Args, "", BB);
1174     if (FT->getReturnType()->isVoidTy())
1175       ReturnInst::Create(*Ctx, BB);
1176     else
1177       ReturnInst::Create(*Ctx, CI, BB);
1178   }
1179 
1180   return NewF;
1181 }
1182 
1183 Constant *DataFlowSanitizer::getOrBuildTrampolineFunction(FunctionType *FT,
1184                                                           StringRef FName) {
1185   FunctionType *FTT = getTrampolineFunctionType(FT);
1186   FunctionCallee C = Mod->getOrInsertFunction(FName, FTT);
1187   Function *F = dyn_cast<Function>(C.getCallee());
1188   if (F && F->isDeclaration()) {
1189     F->setLinkage(GlobalValue::LinkOnceODRLinkage);
1190     BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", F);
1191     std::vector<Value *> Args;
1192     Function::arg_iterator AI = F->arg_begin() + 1;
1193     for (unsigned N = FT->getNumParams(); N != 0; ++AI, --N)
1194       Args.push_back(&*AI);
1195     CallInst *CI = CallInst::Create(FT, &*F->arg_begin(), Args, "", BB);
1196     Type *RetType = FT->getReturnType();
1197     ReturnInst *RI = RetType->isVoidTy() ? ReturnInst::Create(*Ctx, BB)
1198                                          : ReturnInst::Create(*Ctx, CI, BB);
1199 
1200     // F is called by a wrapped custom function with primitive shadows. So
1201     // its arguments and return value need conversion.
1202     DFSanFunction DFSF(*this, F, /*IsNativeABI=*/true);
1203     Function::arg_iterator ValAI = F->arg_begin(), ShadowAI = AI;
1204     ++ValAI;
1205     for (unsigned N = FT->getNumParams(); N != 0; ++ValAI, ++ShadowAI, --N) {
1206       Value *Shadow =
1207           DFSF.expandFromPrimitiveShadow(ValAI->getType(), &*ShadowAI, CI);
1208       DFSF.ValShadowMap[&*ValAI] = Shadow;
1209     }
1210     Function::arg_iterator RetShadowAI = ShadowAI;
1211     const bool ShouldTrackOrigins = shouldTrackOrigins();
1212     if (ShouldTrackOrigins) {
1213       ValAI = F->arg_begin();
1214       ++ValAI;
1215       Function::arg_iterator OriginAI = ShadowAI;
1216       if (!RetType->isVoidTy())
1217         ++OriginAI;
1218       for (unsigned N = FT->getNumParams(); N != 0; ++ValAI, ++OriginAI, --N) {
1219         DFSF.ValOriginMap[&*ValAI] = &*OriginAI;
1220       }
1221     }
1222     DFSanVisitor(DFSF).visitCallInst(*CI);
1223     if (!RetType->isVoidTy()) {
1224       Value *PrimitiveShadow = DFSF.collapseToPrimitiveShadow(
1225           DFSF.getShadow(RI->getReturnValue()), RI);
1226       new StoreInst(PrimitiveShadow, &*RetShadowAI, RI);
1227       if (ShouldTrackOrigins) {
1228         Value *Origin = DFSF.getOrigin(RI->getReturnValue());
1229         new StoreInst(Origin, &*std::prev(F->arg_end()), RI);
1230       }
1231     }
1232   }
1233 
1234   return cast<Constant>(C.getCallee());
1235 }
1236 
1237 // Initialize DataFlowSanitizer runtime functions and declare them in the module
1238 void DataFlowSanitizer::initializeRuntimeFunctions(Module &M) {
1239   {
1240     AttributeList AL;
1241     AL = AL.addAttribute(M.getContext(), AttributeList::FunctionIndex,
1242                          Attribute::NoUnwind);
1243     AL = AL.addAttribute(M.getContext(), AttributeList::FunctionIndex,
1244                          Attribute::ReadOnly);
1245     AL = AL.addAttribute(M.getContext(), AttributeList::ReturnIndex,
1246                          Attribute::ZExt);
1247     DFSanUnionLoadFn =
1248         Mod->getOrInsertFunction("__dfsan_union_load", DFSanUnionLoadFnTy, AL);
1249   }
1250   {
1251     AttributeList AL;
1252     AL = AL.addAttribute(M.getContext(), AttributeList::FunctionIndex,
1253                          Attribute::NoUnwind);
1254     AL = AL.addAttribute(M.getContext(), AttributeList::FunctionIndex,
1255                          Attribute::ReadOnly);
1256     AL = AL.addAttribute(M.getContext(), AttributeList::ReturnIndex,
1257                          Attribute::ZExt);
1258     DFSanLoadLabelAndOriginFn = Mod->getOrInsertFunction(
1259         "__dfsan_load_label_and_origin", DFSanLoadLabelAndOriginFnTy, AL);
1260   }
1261   DFSanUnimplementedFn =
1262       Mod->getOrInsertFunction("__dfsan_unimplemented", DFSanUnimplementedFnTy);
1263   {
1264     AttributeList AL;
1265     AL = AL.addParamAttribute(M.getContext(), 0, Attribute::ZExt);
1266     AL = AL.addParamAttribute(M.getContext(), 1, Attribute::ZExt);
1267     DFSanSetLabelFn =
1268         Mod->getOrInsertFunction("__dfsan_set_label", DFSanSetLabelFnTy, AL);
1269   }
1270   DFSanNonzeroLabelFn =
1271       Mod->getOrInsertFunction("__dfsan_nonzero_label", DFSanNonzeroLabelFnTy);
1272   DFSanVarargWrapperFn = Mod->getOrInsertFunction("__dfsan_vararg_wrapper",
1273                                                   DFSanVarargWrapperFnTy);
1274   {
1275     AttributeList AL;
1276     AL = AL.addParamAttribute(M.getContext(), 0, Attribute::ZExt);
1277     AL = AL.addAttribute(M.getContext(), AttributeList::ReturnIndex,
1278                          Attribute::ZExt);
1279     DFSanChainOriginFn = Mod->getOrInsertFunction("__dfsan_chain_origin",
1280                                                   DFSanChainOriginFnTy, AL);
1281   }
1282   {
1283     AttributeList AL;
1284     AL = AL.addParamAttribute(M.getContext(), 0, Attribute::ZExt);
1285     AL = AL.addParamAttribute(M.getContext(), 1, Attribute::ZExt);
1286     AL = AL.addAttribute(M.getContext(), AttributeList::ReturnIndex,
1287                          Attribute::ZExt);
1288     DFSanChainOriginIfTaintedFn = Mod->getOrInsertFunction(
1289         "__dfsan_chain_origin_if_tainted", DFSanChainOriginIfTaintedFnTy, AL);
1290   }
1291   DFSanMemOriginTransferFn = Mod->getOrInsertFunction(
1292       "__dfsan_mem_origin_transfer", DFSanMemOriginTransferFnTy);
1293 
1294   {
1295     AttributeList AL;
1296     AL = AL.addParamAttribute(M.getContext(), 0, Attribute::ZExt);
1297     AL = AL.addParamAttribute(M.getContext(), 3, Attribute::ZExt);
1298     DFSanMaybeStoreOriginFn = Mod->getOrInsertFunction(
1299         "__dfsan_maybe_store_origin", DFSanMaybeStoreOriginFnTy, AL);
1300   }
1301 
1302   DFSanRuntimeFunctions.insert(
1303       DFSanUnionLoadFn.getCallee()->stripPointerCasts());
1304   DFSanRuntimeFunctions.insert(
1305       DFSanLoadLabelAndOriginFn.getCallee()->stripPointerCasts());
1306   DFSanRuntimeFunctions.insert(
1307       DFSanUnimplementedFn.getCallee()->stripPointerCasts());
1308   DFSanRuntimeFunctions.insert(
1309       DFSanSetLabelFn.getCallee()->stripPointerCasts());
1310   DFSanRuntimeFunctions.insert(
1311       DFSanNonzeroLabelFn.getCallee()->stripPointerCasts());
1312   DFSanRuntimeFunctions.insert(
1313       DFSanVarargWrapperFn.getCallee()->stripPointerCasts());
1314   DFSanRuntimeFunctions.insert(
1315       DFSanLoadCallbackFn.getCallee()->stripPointerCasts());
1316   DFSanRuntimeFunctions.insert(
1317       DFSanStoreCallbackFn.getCallee()->stripPointerCasts());
1318   DFSanRuntimeFunctions.insert(
1319       DFSanMemTransferCallbackFn.getCallee()->stripPointerCasts());
1320   DFSanRuntimeFunctions.insert(
1321       DFSanCmpCallbackFn.getCallee()->stripPointerCasts());
1322   DFSanRuntimeFunctions.insert(
1323       DFSanChainOriginFn.getCallee()->stripPointerCasts());
1324   DFSanRuntimeFunctions.insert(
1325       DFSanChainOriginIfTaintedFn.getCallee()->stripPointerCasts());
1326   DFSanRuntimeFunctions.insert(
1327       DFSanMemOriginTransferFn.getCallee()->stripPointerCasts());
1328   DFSanRuntimeFunctions.insert(
1329       DFSanMaybeStoreOriginFn.getCallee()->stripPointerCasts());
1330 }
1331 
1332 // Initializes event callback functions and declare them in the module
1333 void DataFlowSanitizer::initializeCallbackFunctions(Module &M) {
1334   DFSanLoadCallbackFn = Mod->getOrInsertFunction("__dfsan_load_callback",
1335                                                  DFSanLoadStoreCallbackFnTy);
1336   DFSanStoreCallbackFn = Mod->getOrInsertFunction("__dfsan_store_callback",
1337                                                   DFSanLoadStoreCallbackFnTy);
1338   DFSanMemTransferCallbackFn = Mod->getOrInsertFunction(
1339       "__dfsan_mem_transfer_callback", DFSanMemTransferCallbackFnTy);
1340   DFSanCmpCallbackFn =
1341       Mod->getOrInsertFunction("__dfsan_cmp_callback", DFSanCmpCallbackFnTy);
1342 }
1343 
1344 void DataFlowSanitizer::injectMetadataGlobals(Module &M) {
1345   // These variables can be used:
1346   // - by the runtime (to discover what the shadow width was, during
1347   //   compilation)
1348   // - in testing (to avoid hardcoding the shadow width and type but instead
1349   //   extract them by pattern matching)
1350   Type *IntTy = Type::getInt32Ty(*Ctx);
1351   (void)Mod->getOrInsertGlobal("__dfsan_shadow_width_bits", IntTy, [&] {
1352     return new GlobalVariable(
1353         M, IntTy, /*isConstant=*/true, GlobalValue::WeakODRLinkage,
1354         ConstantInt::get(IntTy, ShadowWidthBits), "__dfsan_shadow_width_bits");
1355   });
1356   (void)Mod->getOrInsertGlobal("__dfsan_shadow_width_bytes", IntTy, [&] {
1357     return new GlobalVariable(M, IntTy, /*isConstant=*/true,
1358                               GlobalValue::WeakODRLinkage,
1359                               ConstantInt::get(IntTy, ShadowWidthBytes),
1360                               "__dfsan_shadow_width_bytes");
1361   });
1362 }
1363 
1364 bool DataFlowSanitizer::runImpl(Module &M) {
1365   initializeModule(M);
1366 
1367   if (ABIList.isIn(M, "skip"))
1368     return false;
1369 
1370   const unsigned InitialGlobalSize = M.global_size();
1371   const unsigned InitialModuleSize = M.size();
1372 
1373   bool Changed = false;
1374 
1375   auto GetOrInsertGlobal = [this, &Changed](StringRef Name,
1376                                             Type *Ty) -> Constant * {
1377     Constant *C = Mod->getOrInsertGlobal(Name, Ty);
1378     if (GlobalVariable *G = dyn_cast<GlobalVariable>(C)) {
1379       Changed |= G->getThreadLocalMode() != GlobalVariable::InitialExecTLSModel;
1380       G->setThreadLocalMode(GlobalVariable::InitialExecTLSModel);
1381     }
1382     return C;
1383   };
1384 
1385   // These globals must be kept in sync with the ones in dfsan.cpp.
1386   ArgTLS =
1387       GetOrInsertGlobal("__dfsan_arg_tls",
1388                         ArrayType::get(Type::getInt64Ty(*Ctx), ArgTLSSize / 8));
1389   RetvalTLS = GetOrInsertGlobal(
1390       "__dfsan_retval_tls",
1391       ArrayType::get(Type::getInt64Ty(*Ctx), RetvalTLSSize / 8));
1392   ArgOriginTLSTy = ArrayType::get(OriginTy, NumOfElementsInArgOrgTLS);
1393   ArgOriginTLS = GetOrInsertGlobal("__dfsan_arg_origin_tls", ArgOriginTLSTy);
1394   RetvalOriginTLS = GetOrInsertGlobal("__dfsan_retval_origin_tls", OriginTy);
1395 
1396   (void)Mod->getOrInsertGlobal("__dfsan_track_origins", OriginTy, [&] {
1397     Changed = true;
1398     return new GlobalVariable(
1399         M, OriginTy, true, GlobalValue::WeakODRLinkage,
1400         ConstantInt::getSigned(OriginTy, shouldTrackOrigins()),
1401         "__dfsan_track_origins");
1402   });
1403 
1404   injectMetadataGlobals(M);
1405 
1406   initializeCallbackFunctions(M);
1407   initializeRuntimeFunctions(M);
1408 
1409   std::vector<Function *> FnsToInstrument;
1410   SmallPtrSet<Function *, 2> FnsWithNativeABI;
1411   for (Function &F : M)
1412     if (!F.isIntrinsic() && !DFSanRuntimeFunctions.contains(&F))
1413       FnsToInstrument.push_back(&F);
1414 
1415   // Give function aliases prefixes when necessary, and build wrappers where the
1416   // instrumentedness is inconsistent.
1417   for (Module::alias_iterator AI = M.alias_begin(), AE = M.alias_end();
1418        AI != AE;) {
1419     GlobalAlias *GA = &*AI;
1420     ++AI;
1421     // Don't stop on weak.  We assume people aren't playing games with the
1422     // instrumentedness of overridden weak aliases.
1423     auto *F = dyn_cast<Function>(GA->getBaseObject());
1424     if (!F)
1425       continue;
1426 
1427     bool GAInst = isInstrumented(GA), FInst = isInstrumented(F);
1428     if (GAInst && FInst) {
1429       addGlobalNameSuffix(GA);
1430     } else if (GAInst != FInst) {
1431       // Non-instrumented alias of an instrumented function, or vice versa.
1432       // Replace the alias with a native-ABI wrapper of the aliasee.  The pass
1433       // below will take care of instrumenting it.
1434       Function *NewF =
1435           buildWrapperFunction(F, "", GA->getLinkage(), F->getFunctionType());
1436       GA->replaceAllUsesWith(ConstantExpr::getBitCast(NewF, GA->getType()));
1437       NewF->takeName(GA);
1438       GA->eraseFromParent();
1439       FnsToInstrument.push_back(NewF);
1440     }
1441   }
1442 
1443   ReadOnlyNoneAttrs.addAttribute(Attribute::ReadOnly)
1444       .addAttribute(Attribute::ReadNone);
1445 
1446   // First, change the ABI of every function in the module.  ABI-listed
1447   // functions keep their original ABI and get a wrapper function.
1448   for (std::vector<Function *>::iterator FI = FnsToInstrument.begin(),
1449                                          FE = FnsToInstrument.end();
1450        FI != FE; ++FI) {
1451     Function &F = **FI;
1452     FunctionType *FT = F.getFunctionType();
1453 
1454     bool IsZeroArgsVoidRet = (FT->getNumParams() == 0 && !FT->isVarArg() &&
1455                               FT->getReturnType()->isVoidTy());
1456 
1457     if (isInstrumented(&F)) {
1458       // Instrumented functions get a '.dfsan' suffix.  This allows us to more
1459       // easily identify cases of mismatching ABIs. This naming scheme is
1460       // mangling-compatible (see Itanium ABI), using a vendor-specific suffix.
1461       if (getInstrumentedABI() == IA_Args && !IsZeroArgsVoidRet) {
1462         FunctionType *NewFT = getArgsFunctionType(FT);
1463         Function *NewF = Function::Create(NewFT, F.getLinkage(),
1464                                           F.getAddressSpace(), "", &M);
1465         NewF->copyAttributesFrom(&F);
1466         NewF->removeAttributes(
1467             AttributeList::ReturnIndex,
1468             AttributeFuncs::typeIncompatible(NewFT->getReturnType()));
1469         for (Function::arg_iterator FArg = F.arg_begin(),
1470                                     NewFArg = NewF->arg_begin(),
1471                                     FArgEnd = F.arg_end();
1472              FArg != FArgEnd; ++FArg, ++NewFArg) {
1473           FArg->replaceAllUsesWith(&*NewFArg);
1474         }
1475         NewF->getBasicBlockList().splice(NewF->begin(), F.getBasicBlockList());
1476 
1477         for (Function::user_iterator UI = F.user_begin(), UE = F.user_end();
1478              UI != UE;) {
1479           BlockAddress *BA = dyn_cast<BlockAddress>(*UI);
1480           ++UI;
1481           if (BA) {
1482             BA->replaceAllUsesWith(
1483                 BlockAddress::get(NewF, BA->getBasicBlock()));
1484             delete BA;
1485           }
1486         }
1487         F.replaceAllUsesWith(
1488             ConstantExpr::getBitCast(NewF, PointerType::getUnqual(FT)));
1489         NewF->takeName(&F);
1490         F.eraseFromParent();
1491         *FI = NewF;
1492         addGlobalNameSuffix(NewF);
1493       } else {
1494         addGlobalNameSuffix(&F);
1495       }
1496     } else if (!IsZeroArgsVoidRet || getWrapperKind(&F) == WK_Custom) {
1497       // Build a wrapper function for F.  The wrapper simply calls F, and is
1498       // added to FnsToInstrument so that any instrumentation according to its
1499       // WrapperKind is done in the second pass below.
1500       FunctionType *NewFT =
1501           getInstrumentedABI() == IA_Args ? getArgsFunctionType(FT) : FT;
1502 
1503       // If the function being wrapped has local linkage, then preserve the
1504       // function's linkage in the wrapper function.
1505       GlobalValue::LinkageTypes WrapperLinkage =
1506           F.hasLocalLinkage() ? F.getLinkage()
1507                               : GlobalValue::LinkOnceODRLinkage;
1508 
1509       Function *NewF = buildWrapperFunction(
1510           &F,
1511           (shouldTrackOrigins() ? std::string("dfso$") : std::string("dfsw$")) +
1512               std::string(F.getName()),
1513           WrapperLinkage, NewFT);
1514       if (getInstrumentedABI() == IA_TLS)
1515         NewF->removeAttributes(AttributeList::FunctionIndex, ReadOnlyNoneAttrs);
1516 
1517       Value *WrappedFnCst =
1518           ConstantExpr::getBitCast(NewF, PointerType::getUnqual(FT));
1519       F.replaceAllUsesWith(WrappedFnCst);
1520 
1521       UnwrappedFnMap[WrappedFnCst] = &F;
1522       *FI = NewF;
1523 
1524       if (!F.isDeclaration()) {
1525         // This function is probably defining an interposition of an
1526         // uninstrumented function and hence needs to keep the original ABI.
1527         // But any functions it may call need to use the instrumented ABI, so
1528         // we instrument it in a mode which preserves the original ABI.
1529         FnsWithNativeABI.insert(&F);
1530 
1531         // This code needs to rebuild the iterators, as they may be invalidated
1532         // by the push_back, taking care that the new range does not include
1533         // any functions added by this code.
1534         size_t N = FI - FnsToInstrument.begin(),
1535                Count = FE - FnsToInstrument.begin();
1536         FnsToInstrument.push_back(&F);
1537         FI = FnsToInstrument.begin() + N;
1538         FE = FnsToInstrument.begin() + Count;
1539       }
1540       // Hopefully, nobody will try to indirectly call a vararg
1541       // function... yet.
1542     } else if (FT->isVarArg()) {
1543       UnwrappedFnMap[&F] = &F;
1544       *FI = nullptr;
1545     }
1546   }
1547 
1548   for (Function *F : FnsToInstrument) {
1549     if (!F || F->isDeclaration())
1550       continue;
1551 
1552     removeUnreachableBlocks(*F);
1553 
1554     DFSanFunction DFSF(*this, F, FnsWithNativeABI.count(F));
1555 
1556     // DFSanVisitor may create new basic blocks, which confuses df_iterator.
1557     // Build a copy of the list before iterating over it.
1558     SmallVector<BasicBlock *, 4> BBList(depth_first(&F->getEntryBlock()));
1559 
1560     for (BasicBlock *BB : BBList) {
1561       Instruction *Inst = &BB->front();
1562       while (true) {
1563         // DFSanVisitor may split the current basic block, changing the current
1564         // instruction's next pointer and moving the next instruction to the
1565         // tail block from which we should continue.
1566         Instruction *Next = Inst->getNextNode();
1567         // DFSanVisitor may delete Inst, so keep track of whether it was a
1568         // terminator.
1569         bool IsTerminator = Inst->isTerminator();
1570         if (!DFSF.SkipInsts.count(Inst))
1571           DFSanVisitor(DFSF).visit(Inst);
1572         if (IsTerminator)
1573           break;
1574         Inst = Next;
1575       }
1576     }
1577 
1578     // We will not necessarily be able to compute the shadow for every phi node
1579     // until we have visited every block.  Therefore, the code that handles phi
1580     // nodes adds them to the PHIFixups list so that they can be properly
1581     // handled here.
1582     for (DFSanFunction::PHIFixupElement &P : DFSF.PHIFixups) {
1583       for (unsigned Val = 0, N = P.Phi->getNumIncomingValues(); Val != N;
1584            ++Val) {
1585         P.ShadowPhi->setIncomingValue(
1586             Val, DFSF.getShadow(P.Phi->getIncomingValue(Val)));
1587         if (P.OriginPhi)
1588           P.OriginPhi->setIncomingValue(
1589               Val, DFSF.getOrigin(P.Phi->getIncomingValue(Val)));
1590       }
1591     }
1592 
1593     // -dfsan-debug-nonzero-labels will split the CFG in all kinds of crazy
1594     // places (i.e. instructions in basic blocks we haven't even begun visiting
1595     // yet).  To make our life easier, do this work in a pass after the main
1596     // instrumentation.
1597     if (ClDebugNonzeroLabels) {
1598       for (Value *V : DFSF.NonZeroChecks) {
1599         Instruction *Pos;
1600         if (Instruction *I = dyn_cast<Instruction>(V))
1601           Pos = I->getNextNode();
1602         else
1603           Pos = &DFSF.F->getEntryBlock().front();
1604         while (isa<PHINode>(Pos) || isa<AllocaInst>(Pos))
1605           Pos = Pos->getNextNode();
1606         IRBuilder<> IRB(Pos);
1607         Value *PrimitiveShadow = DFSF.collapseToPrimitiveShadow(V, Pos);
1608         Value *Ne =
1609             IRB.CreateICmpNE(PrimitiveShadow, DFSF.DFS.ZeroPrimitiveShadow);
1610         BranchInst *BI = cast<BranchInst>(SplitBlockAndInsertIfThen(
1611             Ne, Pos, /*Unreachable=*/false, ColdCallWeights));
1612         IRBuilder<> ThenIRB(BI);
1613         ThenIRB.CreateCall(DFSF.DFS.DFSanNonzeroLabelFn, {});
1614       }
1615     }
1616   }
1617 
1618   return Changed || !FnsToInstrument.empty() ||
1619          M.global_size() != InitialGlobalSize || M.size() != InitialModuleSize;
1620 }
1621 
1622 Value *DFSanFunction::getArgTLS(Type *T, unsigned ArgOffset, IRBuilder<> &IRB) {
1623   Value *Base = IRB.CreatePointerCast(DFS.ArgTLS, DFS.IntptrTy);
1624   if (ArgOffset)
1625     Base = IRB.CreateAdd(Base, ConstantInt::get(DFS.IntptrTy, ArgOffset));
1626   return IRB.CreateIntToPtr(Base, PointerType::get(DFS.getShadowTy(T), 0),
1627                             "_dfsarg");
1628 }
1629 
1630 Value *DFSanFunction::getRetvalTLS(Type *T, IRBuilder<> &IRB) {
1631   return IRB.CreatePointerCast(
1632       DFS.RetvalTLS, PointerType::get(DFS.getShadowTy(T), 0), "_dfsret");
1633 }
1634 
1635 Value *DFSanFunction::getRetvalOriginTLS() { return DFS.RetvalOriginTLS; }
1636 
1637 Value *DFSanFunction::getArgOriginTLS(unsigned ArgNo, IRBuilder<> &IRB) {
1638   return IRB.CreateConstGEP2_64(DFS.ArgOriginTLSTy, DFS.ArgOriginTLS, 0, ArgNo,
1639                                 "_dfsarg_o");
1640 }
1641 
1642 Value *DFSanFunction::getOrigin(Value *V) {
1643   assert(DFS.shouldTrackOrigins());
1644   if (!isa<Argument>(V) && !isa<Instruction>(V))
1645     return DFS.ZeroOrigin;
1646   Value *&Origin = ValOriginMap[V];
1647   if (!Origin) {
1648     if (Argument *A = dyn_cast<Argument>(V)) {
1649       if (IsNativeABI)
1650         return DFS.ZeroOrigin;
1651       switch (IA) {
1652       case DataFlowSanitizer::IA_TLS: {
1653         if (A->getArgNo() < DFS.NumOfElementsInArgOrgTLS) {
1654           Instruction *ArgOriginTLSPos = &*F->getEntryBlock().begin();
1655           IRBuilder<> IRB(ArgOriginTLSPos);
1656           Value *ArgOriginPtr = getArgOriginTLS(A->getArgNo(), IRB);
1657           Origin = IRB.CreateLoad(DFS.OriginTy, ArgOriginPtr);
1658         } else {
1659           // Overflow
1660           Origin = DFS.ZeroOrigin;
1661         }
1662         break;
1663       }
1664       case DataFlowSanitizer::IA_Args: {
1665         Origin = DFS.ZeroOrigin;
1666         break;
1667       }
1668       }
1669     } else {
1670       Origin = DFS.ZeroOrigin;
1671     }
1672   }
1673   return Origin;
1674 }
1675 
1676 void DFSanFunction::setOrigin(Instruction *I, Value *Origin) {
1677   if (!DFS.shouldTrackOrigins())
1678     return;
1679   assert(!ValOriginMap.count(I));
1680   assert(Origin->getType() == DFS.OriginTy);
1681   ValOriginMap[I] = Origin;
1682 }
1683 
1684 Value *DFSanFunction::getShadowForTLSArgument(Argument *A) {
1685   unsigned ArgOffset = 0;
1686   const DataLayout &DL = F->getParent()->getDataLayout();
1687   for (auto &FArg : F->args()) {
1688     if (!FArg.getType()->isSized()) {
1689       if (A == &FArg)
1690         break;
1691       continue;
1692     }
1693 
1694     unsigned Size = DL.getTypeAllocSize(DFS.getShadowTy(&FArg));
1695     if (A != &FArg) {
1696       ArgOffset += alignTo(Size, ShadowTLSAlignment);
1697       if (ArgOffset > ArgTLSSize)
1698         break; // ArgTLS overflows, uses a zero shadow.
1699       continue;
1700     }
1701 
1702     if (ArgOffset + Size > ArgTLSSize)
1703       break; // ArgTLS overflows, uses a zero shadow.
1704 
1705     Instruction *ArgTLSPos = &*F->getEntryBlock().begin();
1706     IRBuilder<> IRB(ArgTLSPos);
1707     Value *ArgShadowPtr = getArgTLS(FArg.getType(), ArgOffset, IRB);
1708     return IRB.CreateAlignedLoad(DFS.getShadowTy(&FArg), ArgShadowPtr,
1709                                  ShadowTLSAlignment);
1710   }
1711 
1712   return DFS.getZeroShadow(A);
1713 }
1714 
1715 Value *DFSanFunction::getShadow(Value *V) {
1716   if (!isa<Argument>(V) && !isa<Instruction>(V))
1717     return DFS.getZeroShadow(V);
1718   Value *&Shadow = ValShadowMap[V];
1719   if (!Shadow) {
1720     if (Argument *A = dyn_cast<Argument>(V)) {
1721       if (IsNativeABI)
1722         return DFS.getZeroShadow(V);
1723       switch (IA) {
1724       case DataFlowSanitizer::IA_TLS: {
1725         Shadow = getShadowForTLSArgument(A);
1726         break;
1727       }
1728       case DataFlowSanitizer::IA_Args: {
1729         unsigned ArgIdx = A->getArgNo() + F->arg_size() / 2;
1730         Function::arg_iterator Arg = F->arg_begin();
1731         std::advance(Arg, ArgIdx);
1732         Shadow = &*Arg;
1733         assert(Shadow->getType() == DFS.PrimitiveShadowTy);
1734         break;
1735       }
1736       }
1737       NonZeroChecks.push_back(Shadow);
1738     } else {
1739       Shadow = DFS.getZeroShadow(V);
1740     }
1741   }
1742   return Shadow;
1743 }
1744 
1745 void DFSanFunction::setShadow(Instruction *I, Value *Shadow) {
1746   assert(!ValShadowMap.count(I));
1747   assert(DFS.shouldTrackFieldsAndIndices() ||
1748          Shadow->getType() == DFS.PrimitiveShadowTy);
1749   ValShadowMap[I] = Shadow;
1750 }
1751 
1752 /// Compute the integer shadow offset that corresponds to a given
1753 /// application address.
1754 ///
1755 /// Offset = (Addr & ~AndMask) ^ XorMask
1756 Value *DataFlowSanitizer::getShadowOffset(Value *Addr, IRBuilder<> &IRB) {
1757   assert(Addr != RetvalTLS && "Reinstrumenting?");
1758   Value *OffsetLong = IRB.CreatePointerCast(Addr, IntptrTy);
1759 
1760   uint64_t AndMask = MapParams->AndMask;
1761   if (AndMask)
1762     OffsetLong =
1763         IRB.CreateAnd(OffsetLong, ConstantInt::get(IntptrTy, ~AndMask));
1764 
1765   uint64_t XorMask = MapParams->XorMask;
1766   if (XorMask)
1767     OffsetLong = IRB.CreateXor(OffsetLong, ConstantInt::get(IntptrTy, XorMask));
1768   return OffsetLong;
1769 }
1770 
1771 std::pair<Value *, Value *>
1772 DataFlowSanitizer::getShadowOriginAddress(Value *Addr, Align InstAlignment,
1773                                           Instruction *Pos) {
1774   // Returns ((Addr & shadow_mask) + origin_base - shadow_base) & ~4UL
1775   IRBuilder<> IRB(Pos);
1776   Value *ShadowOffset = getShadowOffset(Addr, IRB);
1777   Value *ShadowLong = ShadowOffset;
1778   uint64_t ShadowBase = MapParams->ShadowBase;
1779   if (ShadowBase != 0) {
1780     ShadowLong =
1781         IRB.CreateAdd(ShadowLong, ConstantInt::get(IntptrTy, ShadowBase));
1782   }
1783   IntegerType *ShadowTy = IntegerType::get(*Ctx, ShadowWidthBits);
1784   Value *ShadowPtr =
1785       IRB.CreateIntToPtr(ShadowLong, PointerType::get(ShadowTy, 0));
1786   Value *OriginPtr = nullptr;
1787   if (shouldTrackOrigins()) {
1788     Value *OriginLong = ShadowOffset;
1789     uint64_t OriginBase = MapParams->OriginBase;
1790     if (OriginBase != 0)
1791       OriginLong =
1792           IRB.CreateAdd(OriginLong, ConstantInt::get(IntptrTy, OriginBase));
1793     const Align Alignment = llvm::assumeAligned(InstAlignment.value());
1794     // When alignment is >= 4, Addr must be aligned to 4, otherwise it is UB.
1795     // So Mask is unnecessary.
1796     if (Alignment < MinOriginAlignment) {
1797       uint64_t Mask = MinOriginAlignment.value() - 1;
1798       OriginLong = IRB.CreateAnd(OriginLong, ConstantInt::get(IntptrTy, ~Mask));
1799     }
1800     OriginPtr = IRB.CreateIntToPtr(OriginLong, OriginPtrTy);
1801   }
1802   return std::make_pair(ShadowPtr, OriginPtr);
1803 }
1804 
1805 Value *DataFlowSanitizer::getShadowAddress(Value *Addr, Instruction *Pos,
1806                                            Value *ShadowOffset) {
1807   IRBuilder<> IRB(Pos);
1808   return IRB.CreateIntToPtr(ShadowOffset, PrimitiveShadowPtrTy);
1809 }
1810 
1811 Value *DataFlowSanitizer::getShadowAddress(Value *Addr, Instruction *Pos) {
1812   IRBuilder<> IRB(Pos);
1813   Value *ShadowOffset = getShadowOffset(Addr, IRB);
1814   return getShadowAddress(Addr, Pos, ShadowOffset);
1815 }
1816 
1817 Value *DFSanFunction::combineShadowsThenConvert(Type *T, Value *V1, Value *V2,
1818                                                 Instruction *Pos) {
1819   Value *PrimitiveValue = combineShadows(V1, V2, Pos);
1820   return expandFromPrimitiveShadow(T, PrimitiveValue, Pos);
1821 }
1822 
1823 // Generates IR to compute the union of the two given shadows, inserting it
1824 // before Pos. The combined value is with primitive type.
1825 Value *DFSanFunction::combineShadows(Value *V1, Value *V2, Instruction *Pos) {
1826   if (DFS.isZeroShadow(V1))
1827     return collapseToPrimitiveShadow(V2, Pos);
1828   if (DFS.isZeroShadow(V2))
1829     return collapseToPrimitiveShadow(V1, Pos);
1830   if (V1 == V2)
1831     return collapseToPrimitiveShadow(V1, Pos);
1832 
1833   auto V1Elems = ShadowElements.find(V1);
1834   auto V2Elems = ShadowElements.find(V2);
1835   if (V1Elems != ShadowElements.end() && V2Elems != ShadowElements.end()) {
1836     if (std::includes(V1Elems->second.begin(), V1Elems->second.end(),
1837                       V2Elems->second.begin(), V2Elems->second.end())) {
1838       return collapseToPrimitiveShadow(V1, Pos);
1839     }
1840     if (std::includes(V2Elems->second.begin(), V2Elems->second.end(),
1841                       V1Elems->second.begin(), V1Elems->second.end())) {
1842       return collapseToPrimitiveShadow(V2, Pos);
1843     }
1844   } else if (V1Elems != ShadowElements.end()) {
1845     if (V1Elems->second.count(V2))
1846       return collapseToPrimitiveShadow(V1, Pos);
1847   } else if (V2Elems != ShadowElements.end()) {
1848     if (V2Elems->second.count(V1))
1849       return collapseToPrimitiveShadow(V2, Pos);
1850   }
1851 
1852   auto Key = std::make_pair(V1, V2);
1853   if (V1 > V2)
1854     std::swap(Key.first, Key.second);
1855   CachedShadow &CCS = CachedShadows[Key];
1856   if (CCS.Block && DT.dominates(CCS.Block, Pos->getParent()))
1857     return CCS.Shadow;
1858 
1859   // Converts inputs shadows to shadows with primitive types.
1860   Value *PV1 = collapseToPrimitiveShadow(V1, Pos);
1861   Value *PV2 = collapseToPrimitiveShadow(V2, Pos);
1862 
1863   IRBuilder<> IRB(Pos);
1864   CCS.Block = Pos->getParent();
1865   CCS.Shadow = IRB.CreateOr(PV1, PV2);
1866 
1867   std::set<Value *> UnionElems;
1868   if (V1Elems != ShadowElements.end()) {
1869     UnionElems = V1Elems->second;
1870   } else {
1871     UnionElems.insert(V1);
1872   }
1873   if (V2Elems != ShadowElements.end()) {
1874     UnionElems.insert(V2Elems->second.begin(), V2Elems->second.end());
1875   } else {
1876     UnionElems.insert(V2);
1877   }
1878   ShadowElements[CCS.Shadow] = std::move(UnionElems);
1879 
1880   return CCS.Shadow;
1881 }
1882 
1883 // A convenience function which folds the shadows of each of the operands
1884 // of the provided instruction Inst, inserting the IR before Inst.  Returns
1885 // the computed union Value.
1886 Value *DFSanFunction::combineOperandShadows(Instruction *Inst) {
1887   if (Inst->getNumOperands() == 0)
1888     return DFS.getZeroShadow(Inst);
1889 
1890   Value *Shadow = getShadow(Inst->getOperand(0));
1891   for (unsigned I = 1, N = Inst->getNumOperands(); I < N; ++I)
1892     Shadow = combineShadows(Shadow, getShadow(Inst->getOperand(I)), Inst);
1893 
1894   return expandFromPrimitiveShadow(Inst->getType(), Shadow, Inst);
1895 }
1896 
1897 void DFSanVisitor::visitInstOperands(Instruction &I) {
1898   Value *CombinedShadow = DFSF.combineOperandShadows(&I);
1899   DFSF.setShadow(&I, CombinedShadow);
1900   visitInstOperandOrigins(I);
1901 }
1902 
1903 Value *DFSanFunction::combineOrigins(const std::vector<Value *> &Shadows,
1904                                      const std::vector<Value *> &Origins,
1905                                      Instruction *Pos, ConstantInt *Zero) {
1906   assert(Shadows.size() == Origins.size());
1907   size_t Size = Origins.size();
1908   if (Size == 0)
1909     return DFS.ZeroOrigin;
1910   Value *Origin = nullptr;
1911   if (!Zero)
1912     Zero = DFS.ZeroPrimitiveShadow;
1913   for (size_t I = 0; I != Size; ++I) {
1914     Value *OpOrigin = Origins[I];
1915     Constant *ConstOpOrigin = dyn_cast<Constant>(OpOrigin);
1916     if (ConstOpOrigin && ConstOpOrigin->isNullValue())
1917       continue;
1918     if (!Origin) {
1919       Origin = OpOrigin;
1920       continue;
1921     }
1922     Value *OpShadow = Shadows[I];
1923     Value *PrimitiveShadow = collapseToPrimitiveShadow(OpShadow, Pos);
1924     IRBuilder<> IRB(Pos);
1925     Value *Cond = IRB.CreateICmpNE(PrimitiveShadow, Zero);
1926     Origin = IRB.CreateSelect(Cond, OpOrigin, Origin);
1927   }
1928   return Origin ? Origin : DFS.ZeroOrigin;
1929 }
1930 
1931 Value *DFSanFunction::combineOperandOrigins(Instruction *Inst) {
1932   size_t Size = Inst->getNumOperands();
1933   std::vector<Value *> Shadows(Size);
1934   std::vector<Value *> Origins(Size);
1935   for (unsigned I = 0; I != Size; ++I) {
1936     Shadows[I] = getShadow(Inst->getOperand(I));
1937     Origins[I] = getOrigin(Inst->getOperand(I));
1938   }
1939   return combineOrigins(Shadows, Origins, Inst);
1940 }
1941 
1942 void DFSanVisitor::visitInstOperandOrigins(Instruction &I) {
1943   if (!DFSF.DFS.shouldTrackOrigins())
1944     return;
1945   Value *CombinedOrigin = DFSF.combineOperandOrigins(&I);
1946   DFSF.setOrigin(&I, CombinedOrigin);
1947 }
1948 
1949 Align DFSanFunction::getShadowAlign(Align InstAlignment) {
1950   const Align Alignment = ClPreserveAlignment ? InstAlignment : Align(1);
1951   return Align(Alignment.value() * DFS.ShadowWidthBytes);
1952 }
1953 
1954 Align DFSanFunction::getOriginAlign(Align InstAlignment) {
1955   const Align Alignment = llvm::assumeAligned(InstAlignment.value());
1956   return Align(std::max(MinOriginAlignment, Alignment));
1957 }
1958 
1959 bool DFSanFunction::useCallbackLoadLabelAndOrigin(uint64_t Size,
1960                                                   Align InstAlignment) {
1961   // When enabling tracking load instructions, we always use
1962   // __dfsan_load_label_and_origin to reduce code size.
1963   if (ClTrackOrigins == 2)
1964     return true;
1965 
1966   assert(Size != 0);
1967   // * if Size == 1, it is sufficient to load its origin aligned at 4.
1968   // * if Size == 2, we assume most cases Addr % 2 == 0, so it is sufficient to
1969   //   load its origin aligned at 4. If not, although origins may be lost, it
1970   //   should not happen very often.
1971   // * if align >= 4, Addr must be aligned to 4, otherwise it is UB. When
1972   //   Size % 4 == 0, it is more efficient to load origins without callbacks.
1973   // * Otherwise we use __dfsan_load_label_and_origin.
1974   // This should ensure that common cases run efficiently.
1975   if (Size <= 2)
1976     return false;
1977 
1978   const Align Alignment = llvm::assumeAligned(InstAlignment.value());
1979   return Alignment < MinOriginAlignment || !DFS.hasLoadSizeForFastPath(Size);
1980 }
1981 
1982 Value *DataFlowSanitizer::loadNextOrigin(Instruction *Pos, Align OriginAlign,
1983                                          Value **OriginAddr) {
1984   IRBuilder<> IRB(Pos);
1985   *OriginAddr =
1986       IRB.CreateGEP(OriginTy, *OriginAddr, ConstantInt::get(IntptrTy, 1));
1987   return IRB.CreateAlignedLoad(OriginTy, *OriginAddr, OriginAlign);
1988 }
1989 
1990 std::pair<Value *, Value *> DFSanFunction::loadShadowFast(
1991     Value *ShadowAddr, Value *OriginAddr, uint64_t Size, Align ShadowAlign,
1992     Align OriginAlign, Value *FirstOrigin, Instruction *Pos) {
1993   const bool ShouldTrackOrigins = DFS.shouldTrackOrigins();
1994   const uint64_t ShadowSize = Size * DFS.ShadowWidthBytes;
1995 
1996   assert(Size >= 4 && "Not large enough load size for fast path!");
1997 
1998   // Used for origin tracking.
1999   std::vector<Value *> Shadows;
2000   std::vector<Value *> Origins;
2001 
2002   // Load instructions in LLVM can have arbitrary byte sizes (e.g., 3, 12, 20)
2003   // but this function is only used in a subset of cases that make it possible
2004   // to optimize the instrumentation.
2005   //
2006   // Specifically, when the shadow size in bytes (i.e., loaded bytes x shadow
2007   // per byte) is either:
2008   // - a multiple of 8  (common)
2009   // - equal to 4       (only for load32)
2010   //
2011   // For the second case, we can fit the wide shadow in a 32-bit integer. In all
2012   // other cases, we use a 64-bit integer to hold the wide shadow.
2013   Type *WideShadowTy =
2014       ShadowSize == 4 ? Type::getInt32Ty(*DFS.Ctx) : Type::getInt64Ty(*DFS.Ctx);
2015 
2016   IRBuilder<> IRB(Pos);
2017   Value *WideAddr = IRB.CreateBitCast(ShadowAddr, WideShadowTy->getPointerTo());
2018   Value *CombinedWideShadow =
2019       IRB.CreateAlignedLoad(WideShadowTy, WideAddr, ShadowAlign);
2020 
2021   unsigned WideShadowBitWidth = WideShadowTy->getIntegerBitWidth();
2022   const uint64_t BytesPerWideShadow = WideShadowBitWidth / DFS.ShadowWidthBits;
2023 
2024   auto AppendWideShadowAndOrigin = [&](Value *WideShadow, Value *Origin) {
2025     if (BytesPerWideShadow > 4) {
2026       assert(BytesPerWideShadow == 8);
2027       // The wide shadow relates to two origin pointers: one for the first four
2028       // application bytes, and one for the latest four. We use a left shift to
2029       // get just the shadow bytes that correspond to the first origin pointer,
2030       // and then the entire shadow for the second origin pointer (which will be
2031       // chosen by combineOrigins() iff the least-significant half of the wide
2032       // shadow was empty but the other half was not).
2033       Value *WideShadowLo = IRB.CreateShl(
2034           WideShadow, ConstantInt::get(WideShadowTy, WideShadowBitWidth / 2));
2035       Shadows.push_back(WideShadow);
2036       Origins.push_back(DFS.loadNextOrigin(Pos, OriginAlign, &OriginAddr));
2037 
2038       Shadows.push_back(WideShadowLo);
2039       Origins.push_back(Origin);
2040     } else {
2041       Shadows.push_back(WideShadow);
2042       Origins.push_back(Origin);
2043     }
2044   };
2045 
2046   if (ShouldTrackOrigins)
2047     AppendWideShadowAndOrigin(CombinedWideShadow, FirstOrigin);
2048 
2049   // First OR all the WideShadows (i.e., 64bit or 32bit shadow chunks) linearly;
2050   // then OR individual shadows within the combined WideShadow by binary ORing.
2051   // This is fewer instructions than ORing shadows individually, since it
2052   // needs logN shift/or instructions (N being the bytes of the combined wide
2053   // shadow).
2054   for (uint64_t ByteOfs = BytesPerWideShadow; ByteOfs < Size;
2055        ByteOfs += BytesPerWideShadow) {
2056     WideAddr = IRB.CreateGEP(WideShadowTy, WideAddr,
2057                              ConstantInt::get(DFS.IntptrTy, 1));
2058     Value *NextWideShadow =
2059         IRB.CreateAlignedLoad(WideShadowTy, WideAddr, ShadowAlign);
2060     CombinedWideShadow = IRB.CreateOr(CombinedWideShadow, NextWideShadow);
2061     if (ShouldTrackOrigins) {
2062       Value *NextOrigin = DFS.loadNextOrigin(Pos, OriginAlign, &OriginAddr);
2063       AppendWideShadowAndOrigin(NextWideShadow, NextOrigin);
2064     }
2065   }
2066   for (unsigned Width = WideShadowBitWidth / 2; Width >= DFS.ShadowWidthBits;
2067        Width >>= 1) {
2068     Value *ShrShadow = IRB.CreateLShr(CombinedWideShadow, Width);
2069     CombinedWideShadow = IRB.CreateOr(CombinedWideShadow, ShrShadow);
2070   }
2071   return {IRB.CreateTrunc(CombinedWideShadow, DFS.PrimitiveShadowTy),
2072           ShouldTrackOrigins
2073               ? combineOrigins(Shadows, Origins, Pos,
2074                                ConstantInt::getSigned(IRB.getInt64Ty(), 0))
2075               : DFS.ZeroOrigin};
2076 }
2077 
2078 std::pair<Value *, Value *> DFSanFunction::loadShadowOriginSansLoadTracking(
2079     Value *Addr, uint64_t Size, Align InstAlignment, Instruction *Pos) {
2080   const bool ShouldTrackOrigins = DFS.shouldTrackOrigins();
2081 
2082   // Non-escaped loads.
2083   if (AllocaInst *AI = dyn_cast<AllocaInst>(Addr)) {
2084     const auto SI = AllocaShadowMap.find(AI);
2085     if (SI != AllocaShadowMap.end()) {
2086       IRBuilder<> IRB(Pos);
2087       Value *ShadowLI = IRB.CreateLoad(DFS.PrimitiveShadowTy, SI->second);
2088       const auto OI = AllocaOriginMap.find(AI);
2089       assert(!ShouldTrackOrigins || OI != AllocaOriginMap.end());
2090       return {ShadowLI, ShouldTrackOrigins
2091                             ? IRB.CreateLoad(DFS.OriginTy, OI->second)
2092                             : nullptr};
2093     }
2094   }
2095 
2096   // Load from constant addresses.
2097   SmallVector<const Value *, 2> Objs;
2098   getUnderlyingObjects(Addr, Objs);
2099   bool AllConstants = true;
2100   for (const Value *Obj : Objs) {
2101     if (isa<Function>(Obj) || isa<BlockAddress>(Obj))
2102       continue;
2103     if (isa<GlobalVariable>(Obj) && cast<GlobalVariable>(Obj)->isConstant())
2104       continue;
2105 
2106     AllConstants = false;
2107     break;
2108   }
2109   if (AllConstants)
2110     return {DFS.ZeroPrimitiveShadow,
2111             ShouldTrackOrigins ? DFS.ZeroOrigin : nullptr};
2112 
2113   if (Size == 0)
2114     return {DFS.ZeroPrimitiveShadow,
2115             ShouldTrackOrigins ? DFS.ZeroOrigin : nullptr};
2116 
2117   // Use callback to load if this is not an optimizable case for origin
2118   // tracking.
2119   if (ShouldTrackOrigins &&
2120       useCallbackLoadLabelAndOrigin(Size, InstAlignment)) {
2121     IRBuilder<> IRB(Pos);
2122     CallInst *Call =
2123         IRB.CreateCall(DFS.DFSanLoadLabelAndOriginFn,
2124                        {IRB.CreatePointerCast(Addr, IRB.getInt8PtrTy()),
2125                         ConstantInt::get(DFS.IntptrTy, Size)});
2126     Call->addAttribute(AttributeList::ReturnIndex, Attribute::ZExt);
2127     return {IRB.CreateTrunc(IRB.CreateLShr(Call, DFS.OriginWidthBits),
2128                             DFS.PrimitiveShadowTy),
2129             IRB.CreateTrunc(Call, DFS.OriginTy)};
2130   }
2131 
2132   // Other cases that support loading shadows or origins in a fast way.
2133   Value *ShadowAddr, *OriginAddr;
2134   std::tie(ShadowAddr, OriginAddr) =
2135       DFS.getShadowOriginAddress(Addr, InstAlignment, Pos);
2136 
2137   const Align ShadowAlign = getShadowAlign(InstAlignment);
2138   const Align OriginAlign = getOriginAlign(InstAlignment);
2139   Value *Origin = nullptr;
2140   if (ShouldTrackOrigins) {
2141     IRBuilder<> IRB(Pos);
2142     Origin = IRB.CreateAlignedLoad(DFS.OriginTy, OriginAddr, OriginAlign);
2143   }
2144 
2145   // When the byte size is small enough, we can load the shadow directly with
2146   // just a few instructions.
2147   switch (Size) {
2148   case 1: {
2149     LoadInst *LI = new LoadInst(DFS.PrimitiveShadowTy, ShadowAddr, "", Pos);
2150     LI->setAlignment(ShadowAlign);
2151     return {LI, Origin};
2152   }
2153   case 2: {
2154     IRBuilder<> IRB(Pos);
2155     Value *ShadowAddr1 = IRB.CreateGEP(DFS.PrimitiveShadowTy, ShadowAddr,
2156                                        ConstantInt::get(DFS.IntptrTy, 1));
2157     Value *Load =
2158         IRB.CreateAlignedLoad(DFS.PrimitiveShadowTy, ShadowAddr, ShadowAlign);
2159     Value *Load1 =
2160         IRB.CreateAlignedLoad(DFS.PrimitiveShadowTy, ShadowAddr1, ShadowAlign);
2161     return {combineShadows(Load, Load1, Pos), Origin};
2162   }
2163   }
2164   bool HasSizeForFastPath = DFS.hasLoadSizeForFastPath(Size);
2165 
2166   if (HasSizeForFastPath)
2167     return loadShadowFast(ShadowAddr, OriginAddr, Size, ShadowAlign,
2168                           OriginAlign, Origin, Pos);
2169 
2170   IRBuilder<> IRB(Pos);
2171   CallInst *FallbackCall = IRB.CreateCall(
2172       DFS.DFSanUnionLoadFn, {ShadowAddr, ConstantInt::get(DFS.IntptrTy, Size)});
2173   FallbackCall->addAttribute(AttributeList::ReturnIndex, Attribute::ZExt);
2174   return {FallbackCall, Origin};
2175 }
2176 
2177 std::pair<Value *, Value *> DFSanFunction::loadShadowOrigin(Value *Addr,
2178                                                             uint64_t Size,
2179                                                             Align InstAlignment,
2180                                                             Instruction *Pos) {
2181   Value *PrimitiveShadow, *Origin;
2182   std::tie(PrimitiveShadow, Origin) =
2183       loadShadowOriginSansLoadTracking(Addr, Size, InstAlignment, Pos);
2184   if (DFS.shouldTrackOrigins()) {
2185     if (ClTrackOrigins == 2) {
2186       IRBuilder<> IRB(Pos);
2187       auto *ConstantShadow = dyn_cast<Constant>(PrimitiveShadow);
2188       if (!ConstantShadow || !ConstantShadow->isZeroValue())
2189         Origin = updateOriginIfTainted(PrimitiveShadow, Origin, IRB);
2190     }
2191   }
2192   return {PrimitiveShadow, Origin};
2193 }
2194 
2195 static AtomicOrdering addAcquireOrdering(AtomicOrdering AO) {
2196   switch (AO) {
2197   case AtomicOrdering::NotAtomic:
2198     return AtomicOrdering::NotAtomic;
2199   case AtomicOrdering::Unordered:
2200   case AtomicOrdering::Monotonic:
2201   case AtomicOrdering::Acquire:
2202     return AtomicOrdering::Acquire;
2203   case AtomicOrdering::Release:
2204   case AtomicOrdering::AcquireRelease:
2205     return AtomicOrdering::AcquireRelease;
2206   case AtomicOrdering::SequentiallyConsistent:
2207     return AtomicOrdering::SequentiallyConsistent;
2208   }
2209   llvm_unreachable("Unknown ordering");
2210 }
2211 
2212 void DFSanVisitor::visitLoadInst(LoadInst &LI) {
2213   auto &DL = LI.getModule()->getDataLayout();
2214   uint64_t Size = DL.getTypeStoreSize(LI.getType());
2215   if (Size == 0) {
2216     DFSF.setShadow(&LI, DFSF.DFS.getZeroShadow(&LI));
2217     DFSF.setOrigin(&LI, DFSF.DFS.ZeroOrigin);
2218     return;
2219   }
2220 
2221   // When an application load is atomic, increase atomic ordering between
2222   // atomic application loads and stores to ensure happen-before order; load
2223   // shadow data after application data; store zero shadow data before
2224   // application data. This ensure shadow loads return either labels of the
2225   // initial application data or zeros.
2226   if (LI.isAtomic())
2227     LI.setOrdering(addAcquireOrdering(LI.getOrdering()));
2228 
2229   Instruction *Pos = LI.isAtomic() ? LI.getNextNode() : &LI;
2230   std::vector<Value *> Shadows;
2231   std::vector<Value *> Origins;
2232   Value *PrimitiveShadow, *Origin;
2233   std::tie(PrimitiveShadow, Origin) =
2234       DFSF.loadShadowOrigin(LI.getPointerOperand(), Size, LI.getAlign(), Pos);
2235   const bool ShouldTrackOrigins = DFSF.DFS.shouldTrackOrigins();
2236   if (ShouldTrackOrigins) {
2237     Shadows.push_back(PrimitiveShadow);
2238     Origins.push_back(Origin);
2239   }
2240   if (ClCombinePointerLabelsOnLoad) {
2241     Value *PtrShadow = DFSF.getShadow(LI.getPointerOperand());
2242     PrimitiveShadow = DFSF.combineShadows(PrimitiveShadow, PtrShadow, Pos);
2243     if (ShouldTrackOrigins) {
2244       Shadows.push_back(PtrShadow);
2245       Origins.push_back(DFSF.getOrigin(LI.getPointerOperand()));
2246     }
2247   }
2248   if (!DFSF.DFS.isZeroShadow(PrimitiveShadow))
2249     DFSF.NonZeroChecks.push_back(PrimitiveShadow);
2250 
2251   Value *Shadow =
2252       DFSF.expandFromPrimitiveShadow(LI.getType(), PrimitiveShadow, Pos);
2253   DFSF.setShadow(&LI, Shadow);
2254 
2255   if (ShouldTrackOrigins) {
2256     DFSF.setOrigin(&LI, DFSF.combineOrigins(Shadows, Origins, Pos));
2257   }
2258 
2259   if (ClEventCallbacks) {
2260     IRBuilder<> IRB(Pos);
2261     Value *Addr8 = IRB.CreateBitCast(LI.getPointerOperand(), DFSF.DFS.Int8Ptr);
2262     IRB.CreateCall(DFSF.DFS.DFSanLoadCallbackFn, {PrimitiveShadow, Addr8});
2263   }
2264 }
2265 
2266 Value *DFSanFunction::updateOriginIfTainted(Value *Shadow, Value *Origin,
2267                                             IRBuilder<> &IRB) {
2268   assert(DFS.shouldTrackOrigins());
2269   return IRB.CreateCall(DFS.DFSanChainOriginIfTaintedFn, {Shadow, Origin});
2270 }
2271 
2272 Value *DFSanFunction::updateOrigin(Value *V, IRBuilder<> &IRB) {
2273   if (!DFS.shouldTrackOrigins())
2274     return V;
2275   return IRB.CreateCall(DFS.DFSanChainOriginFn, V);
2276 }
2277 
2278 Value *DFSanFunction::originToIntptr(IRBuilder<> &IRB, Value *Origin) {
2279   const unsigned OriginSize = DataFlowSanitizer::OriginWidthBytes;
2280   const DataLayout &DL = F->getParent()->getDataLayout();
2281   unsigned IntptrSize = DL.getTypeStoreSize(DFS.IntptrTy);
2282   if (IntptrSize == OriginSize)
2283     return Origin;
2284   assert(IntptrSize == OriginSize * 2);
2285   Origin = IRB.CreateIntCast(Origin, DFS.IntptrTy, /* isSigned */ false);
2286   return IRB.CreateOr(Origin, IRB.CreateShl(Origin, OriginSize * 8));
2287 }
2288 
2289 void DFSanFunction::paintOrigin(IRBuilder<> &IRB, Value *Origin,
2290                                 Value *StoreOriginAddr,
2291                                 uint64_t StoreOriginSize, Align Alignment) {
2292   const unsigned OriginSize = DataFlowSanitizer::OriginWidthBytes;
2293   const DataLayout &DL = F->getParent()->getDataLayout();
2294   const Align IntptrAlignment = DL.getABITypeAlign(DFS.IntptrTy);
2295   unsigned IntptrSize = DL.getTypeStoreSize(DFS.IntptrTy);
2296   assert(IntptrAlignment >= MinOriginAlignment);
2297   assert(IntptrSize >= OriginSize);
2298 
2299   unsigned Ofs = 0;
2300   Align CurrentAlignment = Alignment;
2301   if (Alignment >= IntptrAlignment && IntptrSize > OriginSize) {
2302     Value *IntptrOrigin = originToIntptr(IRB, Origin);
2303     Value *IntptrStoreOriginPtr = IRB.CreatePointerCast(
2304         StoreOriginAddr, PointerType::get(DFS.IntptrTy, 0));
2305     for (unsigned I = 0; I < StoreOriginSize / IntptrSize; ++I) {
2306       Value *Ptr =
2307           I ? IRB.CreateConstGEP1_32(DFS.IntptrTy, IntptrStoreOriginPtr, I)
2308             : IntptrStoreOriginPtr;
2309       IRB.CreateAlignedStore(IntptrOrigin, Ptr, CurrentAlignment);
2310       Ofs += IntptrSize / OriginSize;
2311       CurrentAlignment = IntptrAlignment;
2312     }
2313   }
2314 
2315   for (unsigned I = Ofs; I < (StoreOriginSize + OriginSize - 1) / OriginSize;
2316        ++I) {
2317     Value *GEP = I ? IRB.CreateConstGEP1_32(DFS.OriginTy, StoreOriginAddr, I)
2318                    : StoreOriginAddr;
2319     IRB.CreateAlignedStore(Origin, GEP, CurrentAlignment);
2320     CurrentAlignment = MinOriginAlignment;
2321   }
2322 }
2323 
2324 Value *DFSanFunction::convertToBool(Value *V, IRBuilder<> &IRB,
2325                                     const Twine &Name) {
2326   Type *VTy = V->getType();
2327   assert(VTy->isIntegerTy());
2328   if (VTy->getIntegerBitWidth() == 1)
2329     // Just converting a bool to a bool, so do nothing.
2330     return V;
2331   return IRB.CreateICmpNE(V, ConstantInt::get(VTy, 0), Name);
2332 }
2333 
2334 void DFSanFunction::storeOrigin(Instruction *Pos, Value *Addr, uint64_t Size,
2335                                 Value *Shadow, Value *Origin,
2336                                 Value *StoreOriginAddr, Align InstAlignment) {
2337   // Do not write origins for zero shadows because we do not trace origins for
2338   // untainted sinks.
2339   const Align OriginAlignment = getOriginAlign(InstAlignment);
2340   Value *CollapsedShadow = collapseToPrimitiveShadow(Shadow, Pos);
2341   IRBuilder<> IRB(Pos);
2342   if (auto *ConstantShadow = dyn_cast<Constant>(CollapsedShadow)) {
2343     if (!ConstantShadow->isZeroValue())
2344       paintOrigin(IRB, updateOrigin(Origin, IRB), StoreOriginAddr, Size,
2345                   OriginAlignment);
2346     return;
2347   }
2348 
2349   if (shouldInstrumentWithCall()) {
2350     IRB.CreateCall(DFS.DFSanMaybeStoreOriginFn,
2351                    {CollapsedShadow,
2352                     IRB.CreatePointerCast(Addr, IRB.getInt8PtrTy()),
2353                     ConstantInt::get(DFS.IntptrTy, Size), Origin});
2354   } else {
2355     Value *Cmp = convertToBool(CollapsedShadow, IRB, "_dfscmp");
2356     Instruction *CheckTerm = SplitBlockAndInsertIfThen(
2357         Cmp, &*IRB.GetInsertPoint(), false, DFS.OriginStoreWeights, &DT);
2358     IRBuilder<> IRBNew(CheckTerm);
2359     paintOrigin(IRBNew, updateOrigin(Origin, IRBNew), StoreOriginAddr, Size,
2360                 OriginAlignment);
2361     ++NumOriginStores;
2362   }
2363 }
2364 
2365 void DFSanFunction::storeZeroPrimitiveShadow(Value *Addr, uint64_t Size,
2366                                              Align ShadowAlign,
2367                                              Instruction *Pos) {
2368   IRBuilder<> IRB(Pos);
2369   IntegerType *ShadowTy =
2370       IntegerType::get(*DFS.Ctx, Size * DFS.ShadowWidthBits);
2371   Value *ExtZeroShadow = ConstantInt::get(ShadowTy, 0);
2372   Value *ShadowAddr = DFS.getShadowAddress(Addr, Pos);
2373   Value *ExtShadowAddr =
2374       IRB.CreateBitCast(ShadowAddr, PointerType::getUnqual(ShadowTy));
2375   IRB.CreateAlignedStore(ExtZeroShadow, ExtShadowAddr, ShadowAlign);
2376   // Do not write origins for 0 shadows because we do not trace origins for
2377   // untainted sinks.
2378 }
2379 
2380 void DFSanFunction::storePrimitiveShadowOrigin(Value *Addr, uint64_t Size,
2381                                                Align InstAlignment,
2382                                                Value *PrimitiveShadow,
2383                                                Value *Origin,
2384                                                Instruction *Pos) {
2385   const bool ShouldTrackOrigins = DFS.shouldTrackOrigins() && Origin;
2386 
2387   if (AllocaInst *AI = dyn_cast<AllocaInst>(Addr)) {
2388     const auto SI = AllocaShadowMap.find(AI);
2389     if (SI != AllocaShadowMap.end()) {
2390       IRBuilder<> IRB(Pos);
2391       IRB.CreateStore(PrimitiveShadow, SI->second);
2392 
2393       // Do not write origins for 0 shadows because we do not trace origins for
2394       // untainted sinks.
2395       if (ShouldTrackOrigins && !DFS.isZeroShadow(PrimitiveShadow)) {
2396         const auto OI = AllocaOriginMap.find(AI);
2397         assert(OI != AllocaOriginMap.end() && Origin);
2398         IRB.CreateStore(Origin, OI->second);
2399       }
2400       return;
2401     }
2402   }
2403 
2404   const Align ShadowAlign = getShadowAlign(InstAlignment);
2405   if (DFS.isZeroShadow(PrimitiveShadow)) {
2406     storeZeroPrimitiveShadow(Addr, Size, ShadowAlign, Pos);
2407     return;
2408   }
2409 
2410   IRBuilder<> IRB(Pos);
2411   Value *ShadowAddr, *OriginAddr;
2412   std::tie(ShadowAddr, OriginAddr) =
2413       DFS.getShadowOriginAddress(Addr, InstAlignment, Pos);
2414 
2415   const unsigned ShadowVecSize = 8;
2416   assert(ShadowVecSize * DFS.ShadowWidthBits <= 128 &&
2417          "Shadow vector is too large!");
2418 
2419   uint64_t Offset = 0;
2420   uint64_t LeftSize = Size;
2421   if (LeftSize >= ShadowVecSize) {
2422     auto *ShadowVecTy =
2423         FixedVectorType::get(DFS.PrimitiveShadowTy, ShadowVecSize);
2424     Value *ShadowVec = UndefValue::get(ShadowVecTy);
2425     for (unsigned I = 0; I != ShadowVecSize; ++I) {
2426       ShadowVec = IRB.CreateInsertElement(
2427           ShadowVec, PrimitiveShadow,
2428           ConstantInt::get(Type::getInt32Ty(*DFS.Ctx), I));
2429     }
2430     Value *ShadowVecAddr =
2431         IRB.CreateBitCast(ShadowAddr, PointerType::getUnqual(ShadowVecTy));
2432     do {
2433       Value *CurShadowVecAddr =
2434           IRB.CreateConstGEP1_32(ShadowVecTy, ShadowVecAddr, Offset);
2435       IRB.CreateAlignedStore(ShadowVec, CurShadowVecAddr, ShadowAlign);
2436       LeftSize -= ShadowVecSize;
2437       ++Offset;
2438     } while (LeftSize >= ShadowVecSize);
2439     Offset *= ShadowVecSize;
2440   }
2441   while (LeftSize > 0) {
2442     Value *CurShadowAddr =
2443         IRB.CreateConstGEP1_32(DFS.PrimitiveShadowTy, ShadowAddr, Offset);
2444     IRB.CreateAlignedStore(PrimitiveShadow, CurShadowAddr, ShadowAlign);
2445     --LeftSize;
2446     ++Offset;
2447   }
2448 
2449   if (ShouldTrackOrigins) {
2450     storeOrigin(Pos, Addr, Size, PrimitiveShadow, Origin, OriginAddr,
2451                 InstAlignment);
2452   }
2453 }
2454 
2455 static AtomicOrdering addReleaseOrdering(AtomicOrdering AO) {
2456   switch (AO) {
2457   case AtomicOrdering::NotAtomic:
2458     return AtomicOrdering::NotAtomic;
2459   case AtomicOrdering::Unordered:
2460   case AtomicOrdering::Monotonic:
2461   case AtomicOrdering::Release:
2462     return AtomicOrdering::Release;
2463   case AtomicOrdering::Acquire:
2464   case AtomicOrdering::AcquireRelease:
2465     return AtomicOrdering::AcquireRelease;
2466   case AtomicOrdering::SequentiallyConsistent:
2467     return AtomicOrdering::SequentiallyConsistent;
2468   }
2469   llvm_unreachable("Unknown ordering");
2470 }
2471 
2472 void DFSanVisitor::visitStoreInst(StoreInst &SI) {
2473   auto &DL = SI.getModule()->getDataLayout();
2474   Value *Val = SI.getValueOperand();
2475   uint64_t Size = DL.getTypeStoreSize(Val->getType());
2476   if (Size == 0)
2477     return;
2478 
2479   // When an application store is atomic, increase atomic ordering between
2480   // atomic application loads and stores to ensure happen-before order; load
2481   // shadow data after application data; store zero shadow data before
2482   // application data. This ensure shadow loads return either labels of the
2483   // initial application data or zeros.
2484   if (SI.isAtomic())
2485     SI.setOrdering(addReleaseOrdering(SI.getOrdering()));
2486 
2487   const bool ShouldTrackOrigins =
2488       DFSF.DFS.shouldTrackOrigins() && !SI.isAtomic();
2489   std::vector<Value *> Shadows;
2490   std::vector<Value *> Origins;
2491 
2492   Value *Shadow =
2493       SI.isAtomic() ? DFSF.DFS.getZeroShadow(Val) : DFSF.getShadow(Val);
2494 
2495   if (ShouldTrackOrigins) {
2496     Shadows.push_back(Shadow);
2497     Origins.push_back(DFSF.getOrigin(Val));
2498   }
2499 
2500   Value *PrimitiveShadow;
2501   if (ClCombinePointerLabelsOnStore) {
2502     Value *PtrShadow = DFSF.getShadow(SI.getPointerOperand());
2503     if (ShouldTrackOrigins) {
2504       Shadows.push_back(PtrShadow);
2505       Origins.push_back(DFSF.getOrigin(SI.getPointerOperand()));
2506     }
2507     PrimitiveShadow = DFSF.combineShadows(Shadow, PtrShadow, &SI);
2508   } else {
2509     PrimitiveShadow = DFSF.collapseToPrimitiveShadow(Shadow, &SI);
2510   }
2511   Value *Origin = nullptr;
2512   if (ShouldTrackOrigins)
2513     Origin = DFSF.combineOrigins(Shadows, Origins, &SI);
2514   DFSF.storePrimitiveShadowOrigin(SI.getPointerOperand(), Size, SI.getAlign(),
2515                                   PrimitiveShadow, Origin, &SI);
2516   if (ClEventCallbacks) {
2517     IRBuilder<> IRB(&SI);
2518     Value *Addr8 = IRB.CreateBitCast(SI.getPointerOperand(), DFSF.DFS.Int8Ptr);
2519     IRB.CreateCall(DFSF.DFS.DFSanStoreCallbackFn, {PrimitiveShadow, Addr8});
2520   }
2521 }
2522 
2523 void DFSanVisitor::visitCASOrRMW(Align InstAlignment, Instruction &I) {
2524   assert(isa<AtomicRMWInst>(I) || isa<AtomicCmpXchgInst>(I));
2525 
2526   Value *Val = I.getOperand(1);
2527   const auto &DL = I.getModule()->getDataLayout();
2528   uint64_t Size = DL.getTypeStoreSize(Val->getType());
2529   if (Size == 0)
2530     return;
2531 
2532   // Conservatively set data at stored addresses and return with zero shadow to
2533   // prevent shadow data races.
2534   IRBuilder<> IRB(&I);
2535   Value *Addr = I.getOperand(0);
2536   const Align ShadowAlign = DFSF.getShadowAlign(InstAlignment);
2537   DFSF.storeZeroPrimitiveShadow(Addr, Size, ShadowAlign, &I);
2538   DFSF.setShadow(&I, DFSF.DFS.getZeroShadow(&I));
2539   DFSF.setOrigin(&I, DFSF.DFS.ZeroOrigin);
2540 }
2541 
2542 void DFSanVisitor::visitAtomicRMWInst(AtomicRMWInst &I) {
2543   visitCASOrRMW(I.getAlign(), I);
2544   // TODO: The ordering change follows MSan. It is possible not to change
2545   // ordering because we always set and use 0 shadows.
2546   I.setOrdering(addReleaseOrdering(I.getOrdering()));
2547 }
2548 
2549 void DFSanVisitor::visitAtomicCmpXchgInst(AtomicCmpXchgInst &I) {
2550   visitCASOrRMW(I.getAlign(), I);
2551   // TODO: The ordering change follows MSan. It is possible not to change
2552   // ordering because we always set and use 0 shadows.
2553   I.setSuccessOrdering(addReleaseOrdering(I.getSuccessOrdering()));
2554 }
2555 
2556 void DFSanVisitor::visitUnaryOperator(UnaryOperator &UO) {
2557   visitInstOperands(UO);
2558 }
2559 
2560 void DFSanVisitor::visitBinaryOperator(BinaryOperator &BO) {
2561   visitInstOperands(BO);
2562 }
2563 
2564 void DFSanVisitor::visitBitCastInst(BitCastInst &BCI) {
2565   if (DFSF.DFS.getInstrumentedABI() == DataFlowSanitizer::IA_TLS) {
2566     // Special case: if this is the bitcast (there is exactly 1 allowed) between
2567     // a musttail call and a ret, don't instrument. New instructions are not
2568     // allowed after a musttail call.
2569     if (auto *CI = dyn_cast<CallInst>(BCI.getOperand(0)))
2570       if (CI->isMustTailCall())
2571         return;
2572   }
2573   // TODO: handle musttail call returns for IA_Args.
2574   visitInstOperands(BCI);
2575 }
2576 
2577 void DFSanVisitor::visitCastInst(CastInst &CI) { visitInstOperands(CI); }
2578 
2579 void DFSanVisitor::visitCmpInst(CmpInst &CI) {
2580   visitInstOperands(CI);
2581   if (ClEventCallbacks) {
2582     IRBuilder<> IRB(&CI);
2583     Value *CombinedShadow = DFSF.getShadow(&CI);
2584     IRB.CreateCall(DFSF.DFS.DFSanCmpCallbackFn, CombinedShadow);
2585   }
2586 }
2587 
2588 void DFSanVisitor::visitLandingPadInst(LandingPadInst &LPI) {
2589   // We do not need to track data through LandingPadInst.
2590   //
2591   // For the C++ exceptions, if a value is thrown, this value will be stored
2592   // in a memory location provided by __cxa_allocate_exception(...) (on the
2593   // throw side) or  __cxa_begin_catch(...) (on the catch side).
2594   // This memory will have a shadow, so with the loads and stores we will be
2595   // able to propagate labels on data thrown through exceptions, without any
2596   // special handling of the LandingPadInst.
2597   //
2598   // The second element in the pair result of the LandingPadInst is a
2599   // register value, but it is for a type ID and should never be tainted.
2600   DFSF.setShadow(&LPI, DFSF.DFS.getZeroShadow(&LPI));
2601   DFSF.setOrigin(&LPI, DFSF.DFS.ZeroOrigin);
2602 }
2603 
2604 void DFSanVisitor::visitGetElementPtrInst(GetElementPtrInst &GEPI) {
2605   if (ClCombineOffsetLabelsOnGEP) {
2606     visitInstOperands(GEPI);
2607     return;
2608   }
2609 
2610   // Only propagate shadow/origin of base pointer value but ignore those of
2611   // offset operands.
2612   Value *BasePointer = GEPI.getPointerOperand();
2613   DFSF.setShadow(&GEPI, DFSF.getShadow(BasePointer));
2614   if (DFSF.DFS.shouldTrackOrigins())
2615     DFSF.setOrigin(&GEPI, DFSF.getOrigin(BasePointer));
2616 }
2617 
2618 void DFSanVisitor::visitExtractElementInst(ExtractElementInst &I) {
2619   visitInstOperands(I);
2620 }
2621 
2622 void DFSanVisitor::visitInsertElementInst(InsertElementInst &I) {
2623   visitInstOperands(I);
2624 }
2625 
2626 void DFSanVisitor::visitShuffleVectorInst(ShuffleVectorInst &I) {
2627   visitInstOperands(I);
2628 }
2629 
2630 void DFSanVisitor::visitExtractValueInst(ExtractValueInst &I) {
2631   if (!DFSF.DFS.shouldTrackFieldsAndIndices()) {
2632     visitInstOperands(I);
2633     return;
2634   }
2635 
2636   IRBuilder<> IRB(&I);
2637   Value *Agg = I.getAggregateOperand();
2638   Value *AggShadow = DFSF.getShadow(Agg);
2639   Value *ResShadow = IRB.CreateExtractValue(AggShadow, I.getIndices());
2640   DFSF.setShadow(&I, ResShadow);
2641   visitInstOperandOrigins(I);
2642 }
2643 
2644 void DFSanVisitor::visitInsertValueInst(InsertValueInst &I) {
2645   if (!DFSF.DFS.shouldTrackFieldsAndIndices()) {
2646     visitInstOperands(I);
2647     return;
2648   }
2649 
2650   IRBuilder<> IRB(&I);
2651   Value *AggShadow = DFSF.getShadow(I.getAggregateOperand());
2652   Value *InsShadow = DFSF.getShadow(I.getInsertedValueOperand());
2653   Value *Res = IRB.CreateInsertValue(AggShadow, InsShadow, I.getIndices());
2654   DFSF.setShadow(&I, Res);
2655   visitInstOperandOrigins(I);
2656 }
2657 
2658 void DFSanVisitor::visitAllocaInst(AllocaInst &I) {
2659   bool AllLoadsStores = true;
2660   for (User *U : I.users()) {
2661     if (isa<LoadInst>(U))
2662       continue;
2663 
2664     if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
2665       if (SI->getPointerOperand() == &I)
2666         continue;
2667     }
2668 
2669     AllLoadsStores = false;
2670     break;
2671   }
2672   if (AllLoadsStores) {
2673     IRBuilder<> IRB(&I);
2674     DFSF.AllocaShadowMap[&I] = IRB.CreateAlloca(DFSF.DFS.PrimitiveShadowTy);
2675     if (DFSF.DFS.shouldTrackOrigins()) {
2676       DFSF.AllocaOriginMap[&I] =
2677           IRB.CreateAlloca(DFSF.DFS.OriginTy, nullptr, "_dfsa");
2678     }
2679   }
2680   DFSF.setShadow(&I, DFSF.DFS.ZeroPrimitiveShadow);
2681   DFSF.setOrigin(&I, DFSF.DFS.ZeroOrigin);
2682 }
2683 
2684 void DFSanVisitor::visitSelectInst(SelectInst &I) {
2685   Value *CondShadow = DFSF.getShadow(I.getCondition());
2686   Value *TrueShadow = DFSF.getShadow(I.getTrueValue());
2687   Value *FalseShadow = DFSF.getShadow(I.getFalseValue());
2688   Value *ShadowSel = nullptr;
2689   const bool ShouldTrackOrigins = DFSF.DFS.shouldTrackOrigins();
2690   std::vector<Value *> Shadows;
2691   std::vector<Value *> Origins;
2692   Value *TrueOrigin =
2693       ShouldTrackOrigins ? DFSF.getOrigin(I.getTrueValue()) : nullptr;
2694   Value *FalseOrigin =
2695       ShouldTrackOrigins ? DFSF.getOrigin(I.getFalseValue()) : nullptr;
2696 
2697   if (isa<VectorType>(I.getCondition()->getType())) {
2698     ShadowSel = DFSF.combineShadowsThenConvert(I.getType(), TrueShadow,
2699                                                FalseShadow, &I);
2700     if (ShouldTrackOrigins) {
2701       Shadows.push_back(TrueShadow);
2702       Shadows.push_back(FalseShadow);
2703       Origins.push_back(TrueOrigin);
2704       Origins.push_back(FalseOrigin);
2705     }
2706   } else {
2707     if (TrueShadow == FalseShadow) {
2708       ShadowSel = TrueShadow;
2709       if (ShouldTrackOrigins) {
2710         Shadows.push_back(TrueShadow);
2711         Origins.push_back(TrueOrigin);
2712       }
2713     } else {
2714       ShadowSel =
2715           SelectInst::Create(I.getCondition(), TrueShadow, FalseShadow, "", &I);
2716       if (ShouldTrackOrigins) {
2717         Shadows.push_back(ShadowSel);
2718         Origins.push_back(SelectInst::Create(I.getCondition(), TrueOrigin,
2719                                              FalseOrigin, "", &I));
2720       }
2721     }
2722   }
2723   DFSF.setShadow(&I, ClTrackSelectControlFlow
2724                          ? DFSF.combineShadowsThenConvert(
2725                                I.getType(), CondShadow, ShadowSel, &I)
2726                          : ShadowSel);
2727   if (ShouldTrackOrigins) {
2728     if (ClTrackSelectControlFlow) {
2729       Shadows.push_back(CondShadow);
2730       Origins.push_back(DFSF.getOrigin(I.getCondition()));
2731     }
2732     DFSF.setOrigin(&I, DFSF.combineOrigins(Shadows, Origins, &I));
2733   }
2734 }
2735 
2736 void DFSanVisitor::visitMemSetInst(MemSetInst &I) {
2737   IRBuilder<> IRB(&I);
2738   Value *ValShadow = DFSF.getShadow(I.getValue());
2739   Value *ValOrigin = DFSF.DFS.shouldTrackOrigins()
2740                          ? DFSF.getOrigin(I.getValue())
2741                          : DFSF.DFS.ZeroOrigin;
2742   IRB.CreateCall(
2743       DFSF.DFS.DFSanSetLabelFn,
2744       {ValShadow, ValOrigin,
2745        IRB.CreateBitCast(I.getDest(), Type::getInt8PtrTy(*DFSF.DFS.Ctx)),
2746        IRB.CreateZExtOrTrunc(I.getLength(), DFSF.DFS.IntptrTy)});
2747 }
2748 
2749 void DFSanVisitor::visitMemTransferInst(MemTransferInst &I) {
2750   IRBuilder<> IRB(&I);
2751 
2752   // CopyOrMoveOrigin transfers origins by refering to their shadows. So we
2753   // need to move origins before moving shadows.
2754   if (DFSF.DFS.shouldTrackOrigins()) {
2755     IRB.CreateCall(
2756         DFSF.DFS.DFSanMemOriginTransferFn,
2757         {IRB.CreatePointerCast(I.getArgOperand(0), IRB.getInt8PtrTy()),
2758          IRB.CreatePointerCast(I.getArgOperand(1), IRB.getInt8PtrTy()),
2759          IRB.CreateIntCast(I.getArgOperand(2), DFSF.DFS.IntptrTy, false)});
2760   }
2761 
2762   Value *RawDestShadow = DFSF.DFS.getShadowAddress(I.getDest(), &I);
2763   Value *SrcShadow = DFSF.DFS.getShadowAddress(I.getSource(), &I);
2764   Value *LenShadow =
2765       IRB.CreateMul(I.getLength(), ConstantInt::get(I.getLength()->getType(),
2766                                                     DFSF.DFS.ShadowWidthBytes));
2767   Type *Int8Ptr = Type::getInt8PtrTy(*DFSF.DFS.Ctx);
2768   Value *DestShadow = IRB.CreateBitCast(RawDestShadow, Int8Ptr);
2769   SrcShadow = IRB.CreateBitCast(SrcShadow, Int8Ptr);
2770   auto *MTI = cast<MemTransferInst>(
2771       IRB.CreateCall(I.getFunctionType(), I.getCalledOperand(),
2772                      {DestShadow, SrcShadow, LenShadow, I.getVolatileCst()}));
2773   if (ClPreserveAlignment) {
2774     MTI->setDestAlignment(I.getDestAlign() * DFSF.DFS.ShadowWidthBytes);
2775     MTI->setSourceAlignment(I.getSourceAlign() * DFSF.DFS.ShadowWidthBytes);
2776   } else {
2777     MTI->setDestAlignment(Align(DFSF.DFS.ShadowWidthBytes));
2778     MTI->setSourceAlignment(Align(DFSF.DFS.ShadowWidthBytes));
2779   }
2780   if (ClEventCallbacks) {
2781     IRB.CreateCall(DFSF.DFS.DFSanMemTransferCallbackFn,
2782                    {RawDestShadow,
2783                     IRB.CreateZExtOrTrunc(I.getLength(), DFSF.DFS.IntptrTy)});
2784   }
2785 }
2786 
2787 static bool isAMustTailRetVal(Value *RetVal) {
2788   // Tail call may have a bitcast between return.
2789   if (auto *I = dyn_cast<BitCastInst>(RetVal)) {
2790     RetVal = I->getOperand(0);
2791   }
2792   if (auto *I = dyn_cast<CallInst>(RetVal)) {
2793     return I->isMustTailCall();
2794   }
2795   return false;
2796 }
2797 
2798 void DFSanVisitor::visitReturnInst(ReturnInst &RI) {
2799   if (!DFSF.IsNativeABI && RI.getReturnValue()) {
2800     switch (DFSF.IA) {
2801     case DataFlowSanitizer::IA_TLS: {
2802       // Don't emit the instrumentation for musttail call returns.
2803       if (isAMustTailRetVal(RI.getReturnValue()))
2804         return;
2805 
2806       Value *S = DFSF.getShadow(RI.getReturnValue());
2807       IRBuilder<> IRB(&RI);
2808       Type *RT = DFSF.F->getFunctionType()->getReturnType();
2809       unsigned Size =
2810           getDataLayout().getTypeAllocSize(DFSF.DFS.getShadowTy(RT));
2811       if (Size <= RetvalTLSSize) {
2812         // If the size overflows, stores nothing. At callsite, oversized return
2813         // shadows are set to zero.
2814         IRB.CreateAlignedStore(S, DFSF.getRetvalTLS(RT, IRB),
2815                                ShadowTLSAlignment);
2816       }
2817       if (DFSF.DFS.shouldTrackOrigins()) {
2818         Value *O = DFSF.getOrigin(RI.getReturnValue());
2819         IRB.CreateStore(O, DFSF.getRetvalOriginTLS());
2820       }
2821       break;
2822     }
2823     case DataFlowSanitizer::IA_Args: {
2824       // TODO: handle musttail call returns for IA_Args.
2825 
2826       IRBuilder<> IRB(&RI);
2827       Type *RT = DFSF.F->getFunctionType()->getReturnType();
2828       Value *InsVal =
2829           IRB.CreateInsertValue(UndefValue::get(RT), RI.getReturnValue(), 0);
2830       Value *InsShadow =
2831           IRB.CreateInsertValue(InsVal, DFSF.getShadow(RI.getReturnValue()), 1);
2832       RI.setOperand(0, InsShadow);
2833       break;
2834     }
2835     }
2836   }
2837 }
2838 
2839 void DFSanVisitor::addShadowArguments(Function &F, CallBase &CB,
2840                                       std::vector<Value *> &Args,
2841                                       IRBuilder<> &IRB) {
2842   FunctionType *FT = F.getFunctionType();
2843 
2844   auto *I = CB.arg_begin();
2845 
2846   // Adds non-variable argument shadows.
2847   for (unsigned N = FT->getNumParams(); N != 0; ++I, --N)
2848     Args.push_back(DFSF.collapseToPrimitiveShadow(DFSF.getShadow(*I), &CB));
2849 
2850   // Adds variable argument shadows.
2851   if (FT->isVarArg()) {
2852     auto *LabelVATy = ArrayType::get(DFSF.DFS.PrimitiveShadowTy,
2853                                      CB.arg_size() - FT->getNumParams());
2854     auto *LabelVAAlloca =
2855         new AllocaInst(LabelVATy, getDataLayout().getAllocaAddrSpace(),
2856                        "labelva", &DFSF.F->getEntryBlock().front());
2857 
2858     for (unsigned N = 0; I != CB.arg_end(); ++I, ++N) {
2859       auto *LabelVAPtr = IRB.CreateStructGEP(LabelVATy, LabelVAAlloca, N);
2860       IRB.CreateStore(DFSF.collapseToPrimitiveShadow(DFSF.getShadow(*I), &CB),
2861                       LabelVAPtr);
2862     }
2863 
2864     Args.push_back(IRB.CreateStructGEP(LabelVATy, LabelVAAlloca, 0));
2865   }
2866 
2867   // Adds the return value shadow.
2868   if (!FT->getReturnType()->isVoidTy()) {
2869     if (!DFSF.LabelReturnAlloca) {
2870       DFSF.LabelReturnAlloca = new AllocaInst(
2871           DFSF.DFS.PrimitiveShadowTy, getDataLayout().getAllocaAddrSpace(),
2872           "labelreturn", &DFSF.F->getEntryBlock().front());
2873     }
2874     Args.push_back(DFSF.LabelReturnAlloca);
2875   }
2876 }
2877 
2878 void DFSanVisitor::addOriginArguments(Function &F, CallBase &CB,
2879                                       std::vector<Value *> &Args,
2880                                       IRBuilder<> &IRB) {
2881   FunctionType *FT = F.getFunctionType();
2882 
2883   auto *I = CB.arg_begin();
2884 
2885   // Add non-variable argument origins.
2886   for (unsigned N = FT->getNumParams(); N != 0; ++I, --N)
2887     Args.push_back(DFSF.getOrigin(*I));
2888 
2889   // Add variable argument origins.
2890   if (FT->isVarArg()) {
2891     auto *OriginVATy =
2892         ArrayType::get(DFSF.DFS.OriginTy, CB.arg_size() - FT->getNumParams());
2893     auto *OriginVAAlloca =
2894         new AllocaInst(OriginVATy, getDataLayout().getAllocaAddrSpace(),
2895                        "originva", &DFSF.F->getEntryBlock().front());
2896 
2897     for (unsigned N = 0; I != CB.arg_end(); ++I, ++N) {
2898       auto *OriginVAPtr = IRB.CreateStructGEP(OriginVATy, OriginVAAlloca, N);
2899       IRB.CreateStore(DFSF.getOrigin(*I), OriginVAPtr);
2900     }
2901 
2902     Args.push_back(IRB.CreateStructGEP(OriginVATy, OriginVAAlloca, 0));
2903   }
2904 
2905   // Add the return value origin.
2906   if (!FT->getReturnType()->isVoidTy()) {
2907     if (!DFSF.OriginReturnAlloca) {
2908       DFSF.OriginReturnAlloca = new AllocaInst(
2909           DFSF.DFS.OriginTy, getDataLayout().getAllocaAddrSpace(),
2910           "originreturn", &DFSF.F->getEntryBlock().front());
2911     }
2912     Args.push_back(DFSF.OriginReturnAlloca);
2913   }
2914 }
2915 
2916 bool DFSanVisitor::visitWrappedCallBase(Function &F, CallBase &CB) {
2917   IRBuilder<> IRB(&CB);
2918   switch (DFSF.DFS.getWrapperKind(&F)) {
2919   case DataFlowSanitizer::WK_Warning:
2920     CB.setCalledFunction(&F);
2921     IRB.CreateCall(DFSF.DFS.DFSanUnimplementedFn,
2922                    IRB.CreateGlobalStringPtr(F.getName()));
2923     DFSF.setShadow(&CB, DFSF.DFS.getZeroShadow(&CB));
2924     DFSF.setOrigin(&CB, DFSF.DFS.ZeroOrigin);
2925     return true;
2926   case DataFlowSanitizer::WK_Discard:
2927     CB.setCalledFunction(&F);
2928     DFSF.setShadow(&CB, DFSF.DFS.getZeroShadow(&CB));
2929     DFSF.setOrigin(&CB, DFSF.DFS.ZeroOrigin);
2930     return true;
2931   case DataFlowSanitizer::WK_Functional:
2932     CB.setCalledFunction(&F);
2933     visitInstOperands(CB);
2934     return true;
2935   case DataFlowSanitizer::WK_Custom:
2936     // Don't try to handle invokes of custom functions, it's too complicated.
2937     // Instead, invoke the dfsw$ wrapper, which will in turn call the __dfsw_
2938     // wrapper.
2939     CallInst *CI = dyn_cast<CallInst>(&CB);
2940     if (!CI)
2941       return false;
2942 
2943     const bool ShouldTrackOrigins = DFSF.DFS.shouldTrackOrigins();
2944     FunctionType *FT = F.getFunctionType();
2945     TransformedFunction CustomFn = DFSF.DFS.getCustomFunctionType(FT);
2946     std::string CustomFName = ShouldTrackOrigins ? "__dfso_" : "__dfsw_";
2947     CustomFName += F.getName();
2948     FunctionCallee CustomF = DFSF.DFS.Mod->getOrInsertFunction(
2949         CustomFName, CustomFn.TransformedType);
2950     if (Function *CustomFn = dyn_cast<Function>(CustomF.getCallee())) {
2951       CustomFn->copyAttributesFrom(&F);
2952 
2953       // Custom functions returning non-void will write to the return label.
2954       if (!FT->getReturnType()->isVoidTy()) {
2955         CustomFn->removeAttributes(AttributeList::FunctionIndex,
2956                                    DFSF.DFS.ReadOnlyNoneAttrs);
2957       }
2958     }
2959 
2960     std::vector<Value *> Args;
2961 
2962     // Adds non-variable arguments.
2963     auto *I = CB.arg_begin();
2964     for (unsigned N = FT->getNumParams(); N != 0; ++I, --N) {
2965       Type *T = (*I)->getType();
2966       FunctionType *ParamFT;
2967       if (isa<PointerType>(T) &&
2968           (ParamFT = dyn_cast<FunctionType>(T->getPointerElementType()))) {
2969         std::string TName = "dfst";
2970         TName += utostr(FT->getNumParams() - N);
2971         TName += "$";
2972         TName += F.getName();
2973         Constant *Trampoline =
2974             DFSF.DFS.getOrBuildTrampolineFunction(ParamFT, TName);
2975         Args.push_back(Trampoline);
2976         Args.push_back(
2977             IRB.CreateBitCast(*I, Type::getInt8PtrTy(*DFSF.DFS.Ctx)));
2978       } else {
2979         Args.push_back(*I);
2980       }
2981     }
2982 
2983     // Adds shadow arguments.
2984     const unsigned ShadowArgStart = Args.size();
2985     addShadowArguments(F, CB, Args, IRB);
2986 
2987     // Adds origin arguments.
2988     const unsigned OriginArgStart = Args.size();
2989     if (ShouldTrackOrigins)
2990       addOriginArguments(F, CB, Args, IRB);
2991 
2992     // Adds variable arguments.
2993     append_range(Args, drop_begin(CB.args(), FT->getNumParams()));
2994 
2995     CallInst *CustomCI = IRB.CreateCall(CustomF, Args);
2996     CustomCI->setCallingConv(CI->getCallingConv());
2997     CustomCI->setAttributes(transformFunctionAttributes(
2998         CustomFn, CI->getContext(), CI->getAttributes()));
2999 
3000     // Update the parameter attributes of the custom call instruction to
3001     // zero extend the shadow parameters. This is required for targets
3002     // which consider PrimitiveShadowTy an illegal type.
3003     for (unsigned N = 0; N < FT->getNumParams(); N++) {
3004       const unsigned ArgNo = ShadowArgStart + N;
3005       if (CustomCI->getArgOperand(ArgNo)->getType() ==
3006           DFSF.DFS.PrimitiveShadowTy)
3007         CustomCI->addParamAttr(ArgNo, Attribute::ZExt);
3008       if (ShouldTrackOrigins) {
3009         const unsigned OriginArgNo = OriginArgStart + N;
3010         if (CustomCI->getArgOperand(OriginArgNo)->getType() ==
3011             DFSF.DFS.OriginTy)
3012           CustomCI->addParamAttr(OriginArgNo, Attribute::ZExt);
3013       }
3014     }
3015 
3016     // Loads the return value shadow and origin.
3017     if (!FT->getReturnType()->isVoidTy()) {
3018       LoadInst *LabelLoad =
3019           IRB.CreateLoad(DFSF.DFS.PrimitiveShadowTy, DFSF.LabelReturnAlloca);
3020       DFSF.setShadow(CustomCI, DFSF.expandFromPrimitiveShadow(
3021                                    FT->getReturnType(), LabelLoad, &CB));
3022       if (ShouldTrackOrigins) {
3023         LoadInst *OriginLoad =
3024             IRB.CreateLoad(DFSF.DFS.OriginTy, DFSF.OriginReturnAlloca);
3025         DFSF.setOrigin(CustomCI, OriginLoad);
3026       }
3027     }
3028 
3029     CI->replaceAllUsesWith(CustomCI);
3030     CI->eraseFromParent();
3031     return true;
3032   }
3033   return false;
3034 }
3035 
3036 void DFSanVisitor::visitCallBase(CallBase &CB) {
3037   Function *F = CB.getCalledFunction();
3038   if ((F && F->isIntrinsic()) || CB.isInlineAsm()) {
3039     visitInstOperands(CB);
3040     return;
3041   }
3042 
3043   // Calls to this function are synthesized in wrappers, and we shouldn't
3044   // instrument them.
3045   if (F == DFSF.DFS.DFSanVarargWrapperFn.getCallee()->stripPointerCasts())
3046     return;
3047 
3048   DenseMap<Value *, Function *>::iterator UnwrappedFnIt =
3049       DFSF.DFS.UnwrappedFnMap.find(CB.getCalledOperand());
3050   if (UnwrappedFnIt != DFSF.DFS.UnwrappedFnMap.end())
3051     if (visitWrappedCallBase(*UnwrappedFnIt->second, CB))
3052       return;
3053 
3054   IRBuilder<> IRB(&CB);
3055 
3056   const bool ShouldTrackOrigins = DFSF.DFS.shouldTrackOrigins();
3057   FunctionType *FT = CB.getFunctionType();
3058   if (DFSF.DFS.getInstrumentedABI() == DataFlowSanitizer::IA_TLS) {
3059     // Stores argument shadows.
3060     unsigned ArgOffset = 0;
3061     const DataLayout &DL = getDataLayout();
3062     for (unsigned I = 0, N = FT->getNumParams(); I != N; ++I) {
3063       if (ShouldTrackOrigins) {
3064         // Ignore overflowed origins
3065         Value *ArgShadow = DFSF.getShadow(CB.getArgOperand(I));
3066         if (I < DFSF.DFS.NumOfElementsInArgOrgTLS &&
3067             !DFSF.DFS.isZeroShadow(ArgShadow))
3068           IRB.CreateStore(DFSF.getOrigin(CB.getArgOperand(I)),
3069                           DFSF.getArgOriginTLS(I, IRB));
3070       }
3071 
3072       unsigned Size =
3073           DL.getTypeAllocSize(DFSF.DFS.getShadowTy(FT->getParamType(I)));
3074       // Stop storing if arguments' size overflows. Inside a function, arguments
3075       // after overflow have zero shadow values.
3076       if (ArgOffset + Size > ArgTLSSize)
3077         break;
3078       IRB.CreateAlignedStore(
3079           DFSF.getShadow(CB.getArgOperand(I)),
3080           DFSF.getArgTLS(FT->getParamType(I), ArgOffset, IRB),
3081           ShadowTLSAlignment);
3082       ArgOffset += alignTo(Size, ShadowTLSAlignment);
3083     }
3084   }
3085 
3086   Instruction *Next = nullptr;
3087   if (!CB.getType()->isVoidTy()) {
3088     if (InvokeInst *II = dyn_cast<InvokeInst>(&CB)) {
3089       if (II->getNormalDest()->getSinglePredecessor()) {
3090         Next = &II->getNormalDest()->front();
3091       } else {
3092         BasicBlock *NewBB =
3093             SplitEdge(II->getParent(), II->getNormalDest(), &DFSF.DT);
3094         Next = &NewBB->front();
3095       }
3096     } else {
3097       assert(CB.getIterator() != CB.getParent()->end());
3098       Next = CB.getNextNode();
3099     }
3100 
3101     if (DFSF.DFS.getInstrumentedABI() == DataFlowSanitizer::IA_TLS) {
3102       // Don't emit the epilogue for musttail call returns.
3103       if (isa<CallInst>(CB) && cast<CallInst>(CB).isMustTailCall())
3104         return;
3105 
3106       // Loads the return value shadow.
3107       IRBuilder<> NextIRB(Next);
3108       const DataLayout &DL = getDataLayout();
3109       unsigned Size = DL.getTypeAllocSize(DFSF.DFS.getShadowTy(&CB));
3110       if (Size > RetvalTLSSize) {
3111         // Set overflowed return shadow to be zero.
3112         DFSF.setShadow(&CB, DFSF.DFS.getZeroShadow(&CB));
3113       } else {
3114         LoadInst *LI = NextIRB.CreateAlignedLoad(
3115             DFSF.DFS.getShadowTy(&CB), DFSF.getRetvalTLS(CB.getType(), NextIRB),
3116             ShadowTLSAlignment, "_dfsret");
3117         DFSF.SkipInsts.insert(LI);
3118         DFSF.setShadow(&CB, LI);
3119         DFSF.NonZeroChecks.push_back(LI);
3120       }
3121 
3122       if (ShouldTrackOrigins) {
3123         LoadInst *LI = NextIRB.CreateLoad(
3124             DFSF.DFS.OriginTy, DFSF.getRetvalOriginTLS(), "_dfsret_o");
3125         DFSF.SkipInsts.insert(LI);
3126         DFSF.setOrigin(&CB, LI);
3127       }
3128     }
3129   }
3130 
3131   // Do all instrumentation for IA_Args down here to defer tampering with the
3132   // CFG in a way that SplitEdge may be able to detect.
3133   if (DFSF.DFS.getInstrumentedABI() == DataFlowSanitizer::IA_Args) {
3134     // TODO: handle musttail call returns for IA_Args.
3135 
3136     FunctionType *NewFT = DFSF.DFS.getArgsFunctionType(FT);
3137     Value *Func =
3138         IRB.CreateBitCast(CB.getCalledOperand(), PointerType::getUnqual(NewFT));
3139 
3140     const unsigned NumParams = FT->getNumParams();
3141 
3142     // Copy original arguments.
3143     auto *ArgIt = CB.arg_begin(), *ArgEnd = CB.arg_end();
3144     std::vector<Value *> Args(NumParams);
3145     std::copy_n(ArgIt, NumParams, Args.begin());
3146 
3147     // Add shadow arguments by transforming original arguments.
3148     std::generate_n(std::back_inserter(Args), NumParams,
3149                     [&]() { return DFSF.getShadow(*ArgIt++); });
3150 
3151     if (FT->isVarArg()) {
3152       unsigned VarArgSize = CB.arg_size() - NumParams;
3153       ArrayType *VarArgArrayTy =
3154           ArrayType::get(DFSF.DFS.PrimitiveShadowTy, VarArgSize);
3155       AllocaInst *VarArgShadow =
3156           new AllocaInst(VarArgArrayTy, getDataLayout().getAllocaAddrSpace(),
3157                          "", &DFSF.F->getEntryBlock().front());
3158       Args.push_back(IRB.CreateConstGEP2_32(VarArgArrayTy, VarArgShadow, 0, 0));
3159 
3160       // Copy remaining var args.
3161       unsigned GepIndex = 0;
3162       std::for_each(ArgIt, ArgEnd, [&](Value *Arg) {
3163         IRB.CreateStore(
3164             DFSF.getShadow(Arg),
3165             IRB.CreateConstGEP2_32(VarArgArrayTy, VarArgShadow, 0, GepIndex++));
3166         Args.push_back(Arg);
3167       });
3168     }
3169 
3170     CallBase *NewCB;
3171     if (InvokeInst *II = dyn_cast<InvokeInst>(&CB)) {
3172       NewCB = IRB.CreateInvoke(NewFT, Func, II->getNormalDest(),
3173                                II->getUnwindDest(), Args);
3174     } else {
3175       NewCB = IRB.CreateCall(NewFT, Func, Args);
3176     }
3177     NewCB->setCallingConv(CB.getCallingConv());
3178     NewCB->setAttributes(CB.getAttributes().removeAttributes(
3179         *DFSF.DFS.Ctx, AttributeList::ReturnIndex,
3180         AttributeFuncs::typeIncompatible(NewCB->getType())));
3181 
3182     if (Next) {
3183       ExtractValueInst *ExVal = ExtractValueInst::Create(NewCB, 0, "", Next);
3184       DFSF.SkipInsts.insert(ExVal);
3185       ExtractValueInst *ExShadow = ExtractValueInst::Create(NewCB, 1, "", Next);
3186       DFSF.SkipInsts.insert(ExShadow);
3187       DFSF.setShadow(ExVal, ExShadow);
3188       DFSF.NonZeroChecks.push_back(ExShadow);
3189 
3190       CB.replaceAllUsesWith(ExVal);
3191     }
3192 
3193     CB.eraseFromParent();
3194   }
3195 }
3196 
3197 void DFSanVisitor::visitPHINode(PHINode &PN) {
3198   Type *ShadowTy = DFSF.DFS.getShadowTy(&PN);
3199   PHINode *ShadowPN =
3200       PHINode::Create(ShadowTy, PN.getNumIncomingValues(), "", &PN);
3201 
3202   // Give the shadow phi node valid predecessors to fool SplitEdge into working.
3203   Value *UndefShadow = UndefValue::get(ShadowTy);
3204   for (BasicBlock *BB : PN.blocks())
3205     ShadowPN->addIncoming(UndefShadow, BB);
3206 
3207   DFSF.setShadow(&PN, ShadowPN);
3208 
3209   PHINode *OriginPN = nullptr;
3210   if (DFSF.DFS.shouldTrackOrigins()) {
3211     OriginPN =
3212         PHINode::Create(DFSF.DFS.OriginTy, PN.getNumIncomingValues(), "", &PN);
3213     Value *UndefOrigin = UndefValue::get(DFSF.DFS.OriginTy);
3214     for (BasicBlock *BB : PN.blocks())
3215       OriginPN->addIncoming(UndefOrigin, BB);
3216     DFSF.setOrigin(&PN, OriginPN);
3217   }
3218 
3219   DFSF.PHIFixups.push_back({&PN, ShadowPN, OriginPN});
3220 }
3221 
3222 namespace {
3223 class DataFlowSanitizerLegacyPass : public ModulePass {
3224 private:
3225   std::vector<std::string> ABIListFiles;
3226 
3227 public:
3228   static char ID;
3229 
3230   DataFlowSanitizerLegacyPass(
3231       const std::vector<std::string> &ABIListFiles = std::vector<std::string>())
3232       : ModulePass(ID), ABIListFiles(ABIListFiles) {}
3233 
3234   bool runOnModule(Module &M) override {
3235     return DataFlowSanitizer(ABIListFiles).runImpl(M);
3236   }
3237 };
3238 } // namespace
3239 
3240 char DataFlowSanitizerLegacyPass::ID;
3241 
3242 INITIALIZE_PASS(DataFlowSanitizerLegacyPass, "dfsan",
3243                 "DataFlowSanitizer: dynamic data flow analysis.", false, false)
3244 
3245 ModulePass *llvm::createDataFlowSanitizerLegacyPassPass(
3246     const std::vector<std::string> &ABIListFiles) {
3247   return new DataFlowSanitizerLegacyPass(ABIListFiles);
3248 }
3249 
3250 PreservedAnalyses DataFlowSanitizerPass::run(Module &M,
3251                                              ModuleAnalysisManager &AM) {
3252   if (DataFlowSanitizer(ABIListFiles).runImpl(M)) {
3253     return PreservedAnalyses::none();
3254   }
3255   return PreservedAnalyses::all();
3256 }
3257