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