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