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