LLVM API Documentation
00001 //===-- MemorySanitizer.cpp - detector of uninitialized reads -------------===// 00002 // 00003 // The LLVM Compiler Infrastructure 00004 // 00005 // This file is distributed under the University of Illinois Open Source 00006 // License. See LICENSE.TXT for details. 00007 // 00008 //===----------------------------------------------------------------------===// 00009 /// \file 00010 /// This file is a part of MemorySanitizer, a detector of uninitialized 00011 /// reads. 00012 /// 00013 /// Status: early prototype. 00014 /// 00015 /// The algorithm of the tool is similar to Memcheck 00016 /// (http://goo.gl/QKbem). We associate a few shadow bits with every 00017 /// byte of the application memory, poison the shadow of the malloc-ed 00018 /// or alloca-ed memory, load the shadow bits on every memory read, 00019 /// propagate the shadow bits through some of the arithmetic 00020 /// instruction (including MOV), store the shadow bits on every memory 00021 /// write, report a bug on some other instructions (e.g. JMP) if the 00022 /// associated shadow is poisoned. 00023 /// 00024 /// But there are differences too. The first and the major one: 00025 /// compiler instrumentation instead of binary instrumentation. This 00026 /// gives us much better register allocation, possible compiler 00027 /// optimizations and a fast start-up. But this brings the major issue 00028 /// as well: msan needs to see all program events, including system 00029 /// calls and reads/writes in system libraries, so we either need to 00030 /// compile *everything* with msan or use a binary translation 00031 /// component (e.g. DynamoRIO) to instrument pre-built libraries. 00032 /// Another difference from Memcheck is that we use 8 shadow bits per 00033 /// byte of application memory and use a direct shadow mapping. This 00034 /// greatly simplifies the instrumentation code and avoids races on 00035 /// shadow updates (Memcheck is single-threaded so races are not a 00036 /// concern there. Memcheck uses 2 shadow bits per byte with a slow 00037 /// path storage that uses 8 bits per byte). 00038 /// 00039 /// The default value of shadow is 0, which means "clean" (not poisoned). 00040 /// 00041 /// Every module initializer should call __msan_init to ensure that the 00042 /// shadow memory is ready. On error, __msan_warning is called. Since 00043 /// parameters and return values may be passed via registers, we have a 00044 /// specialized thread-local shadow for return values 00045 /// (__msan_retval_tls) and parameters (__msan_param_tls). 00046 /// 00047 /// Origin tracking. 00048 /// 00049 /// MemorySanitizer can track origins (allocation points) of all uninitialized 00050 /// values. This behavior is controlled with a flag (msan-track-origins) and is 00051 /// disabled by default. 00052 /// 00053 /// Origins are 4-byte values created and interpreted by the runtime library. 00054 /// They are stored in a second shadow mapping, one 4-byte value for 4 bytes 00055 /// of application memory. Propagation of origins is basically a bunch of 00056 /// "select" instructions that pick the origin of a dirty argument, if an 00057 /// instruction has one. 00058 /// 00059 /// Every 4 aligned, consecutive bytes of application memory have one origin 00060 /// value associated with them. If these bytes contain uninitialized data 00061 /// coming from 2 different allocations, the last store wins. Because of this, 00062 /// MemorySanitizer reports can show unrelated origins, but this is unlikely in 00063 /// practice. 00064 /// 00065 /// Origins are meaningless for fully initialized values, so MemorySanitizer 00066 /// avoids storing origin to memory when a fully initialized value is stored. 00067 /// This way it avoids needless overwritting origin of the 4-byte region on 00068 /// a short (i.e. 1 byte) clean store, and it is also good for performance. 00069 //===----------------------------------------------------------------------===// 00070 00071 #define DEBUG_TYPE "msan" 00072 00073 #include "llvm/Transforms/Instrumentation.h" 00074 #include "llvm/ADT/DepthFirstIterator.h" 00075 #include "llvm/ADT/SmallString.h" 00076 #include "llvm/ADT/SmallVector.h" 00077 #include "llvm/ADT/Triple.h" 00078 #include "llvm/ADT/ValueMap.h" 00079 #include "llvm/IR/DataLayout.h" 00080 #include "llvm/IR/Function.h" 00081 #include "llvm/IR/IRBuilder.h" 00082 #include "llvm/IR/InlineAsm.h" 00083 #include "llvm/IR/IntrinsicInst.h" 00084 #include "llvm/IR/LLVMContext.h" 00085 #include "llvm/IR/MDBuilder.h" 00086 #include "llvm/IR/Module.h" 00087 #include "llvm/IR/Type.h" 00088 #include "llvm/InstVisitor.h" 00089 #include "llvm/Support/CommandLine.h" 00090 #include "llvm/Support/Compiler.h" 00091 #include "llvm/Support/Debug.h" 00092 #include "llvm/Support/raw_ostream.h" 00093 #include "llvm/Transforms/Utils/BasicBlockUtils.h" 00094 #include "llvm/Transforms/Utils/BlackList.h" 00095 #include "llvm/Transforms/Utils/Local.h" 00096 #include "llvm/Transforms/Utils/ModuleUtils.h" 00097 00098 using namespace llvm; 00099 00100 static const uint64_t kShadowMask32 = 1ULL << 31; 00101 static const uint64_t kShadowMask64 = 1ULL << 46; 00102 static const uint64_t kOriginOffset32 = 1ULL << 30; 00103 static const uint64_t kOriginOffset64 = 1ULL << 45; 00104 static const unsigned kMinOriginAlignment = 4; 00105 static const unsigned kShadowTLSAlignment = 8; 00106 00107 /// \brief Track origins of uninitialized values. 00108 /// 00109 /// Adds a section to MemorySanitizer report that points to the allocation 00110 /// (stack or heap) the uninitialized bits came from originally. 00111 static cl::opt<bool> ClTrackOrigins("msan-track-origins", 00112 cl::desc("Track origins (allocation sites) of poisoned memory"), 00113 cl::Hidden, cl::init(false)); 00114 static cl::opt<bool> ClKeepGoing("msan-keep-going", 00115 cl::desc("keep going after reporting a UMR"), 00116 cl::Hidden, cl::init(false)); 00117 static cl::opt<bool> ClPoisonStack("msan-poison-stack", 00118 cl::desc("poison uninitialized stack variables"), 00119 cl::Hidden, cl::init(true)); 00120 static cl::opt<bool> ClPoisonStackWithCall("msan-poison-stack-with-call", 00121 cl::desc("poison uninitialized stack variables with a call"), 00122 cl::Hidden, cl::init(false)); 00123 static cl::opt<int> ClPoisonStackPattern("msan-poison-stack-pattern", 00124 cl::desc("poison uninitialized stack variables with the given patter"), 00125 cl::Hidden, cl::init(0xff)); 00126 static cl::opt<bool> ClPoisonUndef("msan-poison-undef", 00127 cl::desc("poison undef temps"), 00128 cl::Hidden, cl::init(true)); 00129 00130 static cl::opt<bool> ClHandleICmp("msan-handle-icmp", 00131 cl::desc("propagate shadow through ICmpEQ and ICmpNE"), 00132 cl::Hidden, cl::init(true)); 00133 00134 static cl::opt<bool> ClHandleICmpExact("msan-handle-icmp-exact", 00135 cl::desc("exact handling of relational integer ICmp"), 00136 cl::Hidden, cl::init(false)); 00137 00138 static cl::opt<bool> ClStoreCleanOrigin("msan-store-clean-origin", 00139 cl::desc("store origin for clean (fully initialized) values"), 00140 cl::Hidden, cl::init(false)); 00141 00142 // This flag controls whether we check the shadow of the address 00143 // operand of load or store. Such bugs are very rare, since load from 00144 // a garbage address typically results in SEGV, but still happen 00145 // (e.g. only lower bits of address are garbage, or the access happens 00146 // early at program startup where malloc-ed memory is more likely to 00147 // be zeroed. As of 2012-08-28 this flag adds 20% slowdown. 00148 static cl::opt<bool> ClCheckAccessAddress("msan-check-access-address", 00149 cl::desc("report accesses through a pointer which has poisoned shadow"), 00150 cl::Hidden, cl::init(true)); 00151 00152 static cl::opt<bool> ClDumpStrictInstructions("msan-dump-strict-instructions", 00153 cl::desc("print out instructions with default strict semantics"), 00154 cl::Hidden, cl::init(false)); 00155 00156 static cl::opt<std::string> ClBlacklistFile("msan-blacklist", 00157 cl::desc("File containing the list of functions where MemorySanitizer " 00158 "should not report bugs"), cl::Hidden); 00159 00160 namespace { 00161 00162 /// \brief An instrumentation pass implementing detection of uninitialized 00163 /// reads. 00164 /// 00165 /// MemorySanitizer: instrument the code in module to find 00166 /// uninitialized reads. 00167 class MemorySanitizer : public FunctionPass { 00168 public: 00169 MemorySanitizer(bool TrackOrigins = false, 00170 StringRef BlacklistFile = StringRef()) 00171 : FunctionPass(ID), 00172 TrackOrigins(TrackOrigins || ClTrackOrigins), 00173 TD(0), 00174 WarningFn(0), 00175 BlacklistFile(BlacklistFile.empty() ? ClBlacklistFile 00176 : BlacklistFile) { } 00177 const char *getPassName() const { return "MemorySanitizer"; } 00178 bool runOnFunction(Function &F); 00179 bool doInitialization(Module &M); 00180 static char ID; // Pass identification, replacement for typeid. 00181 00182 private: 00183 void initializeCallbacks(Module &M); 00184 00185 /// \brief Track origins (allocation points) of uninitialized values. 00186 bool TrackOrigins; 00187 00188 DataLayout *TD; 00189 LLVMContext *C; 00190 Type *IntptrTy; 00191 Type *OriginTy; 00192 /// \brief Thread-local shadow storage for function parameters. 00193 GlobalVariable *ParamTLS; 00194 /// \brief Thread-local origin storage for function parameters. 00195 GlobalVariable *ParamOriginTLS; 00196 /// \brief Thread-local shadow storage for function return value. 00197 GlobalVariable *RetvalTLS; 00198 /// \brief Thread-local origin storage for function return value. 00199 GlobalVariable *RetvalOriginTLS; 00200 /// \brief Thread-local shadow storage for in-register va_arg function 00201 /// parameters (x86_64-specific). 00202 GlobalVariable *VAArgTLS; 00203 /// \brief Thread-local shadow storage for va_arg overflow area 00204 /// (x86_64-specific). 00205 GlobalVariable *VAArgOverflowSizeTLS; 00206 /// \brief Thread-local space used to pass origin value to the UMR reporting 00207 /// function. 00208 GlobalVariable *OriginTLS; 00209 00210 /// \brief The run-time callback to print a warning. 00211 Value *WarningFn; 00212 /// \brief Run-time helper that copies origin info for a memory range. 00213 Value *MsanCopyOriginFn; 00214 /// \brief Run-time helper that generates a new origin value for a stack 00215 /// allocation. 00216 Value *MsanSetAllocaOriginFn; 00217 /// \brief Run-time helper that poisons stack on function entry. 00218 Value *MsanPoisonStackFn; 00219 /// \brief MSan runtime replacements for memmove, memcpy and memset. 00220 Value *MemmoveFn, *MemcpyFn, *MemsetFn; 00221 00222 /// \brief Address mask used in application-to-shadow address calculation. 00223 /// ShadowAddr is computed as ApplicationAddr & ~ShadowMask. 00224 uint64_t ShadowMask; 00225 /// \brief Offset of the origin shadow from the "normal" shadow. 00226 /// OriginAddr is computed as (ShadowAddr + OriginOffset) & ~3ULL 00227 uint64_t OriginOffset; 00228 /// \brief Branch weights for error reporting. 00229 MDNode *ColdCallWeights; 00230 /// \brief Branch weights for origin store. 00231 MDNode *OriginStoreWeights; 00232 /// \brief Path to blacklist file. 00233 SmallString<64> BlacklistFile; 00234 /// \brief The blacklist. 00235 OwningPtr<BlackList> BL; 00236 /// \brief An empty volatile inline asm that prevents callback merge. 00237 InlineAsm *EmptyAsm; 00238 00239 friend struct MemorySanitizerVisitor; 00240 friend struct VarArgAMD64Helper; 00241 }; 00242 } // namespace 00243 00244 char MemorySanitizer::ID = 0; 00245 INITIALIZE_PASS(MemorySanitizer, "msan", 00246 "MemorySanitizer: detects uninitialized reads.", 00247 false, false) 00248 00249 FunctionPass *llvm::createMemorySanitizerPass(bool TrackOrigins, 00250 StringRef BlacklistFile) { 00251 return new MemorySanitizer(TrackOrigins, BlacklistFile); 00252 } 00253 00254 /// \brief Create a non-const global initialized with the given string. 00255 /// 00256 /// Creates a writable global for Str so that we can pass it to the 00257 /// run-time lib. Runtime uses first 4 bytes of the string to store the 00258 /// frame ID, so the string needs to be mutable. 00259 static GlobalVariable *createPrivateNonConstGlobalForString(Module &M, 00260 StringRef Str) { 00261 Constant *StrConst = ConstantDataArray::getString(M.getContext(), Str); 00262 return new GlobalVariable(M, StrConst->getType(), /*isConstant=*/false, 00263 GlobalValue::PrivateLinkage, StrConst, ""); 00264 } 00265 00266 00267 /// \brief Insert extern declaration of runtime-provided functions and globals. 00268 void MemorySanitizer::initializeCallbacks(Module &M) { 00269 // Only do this once. 00270 if (WarningFn) 00271 return; 00272 00273 IRBuilder<> IRB(*C); 00274 // Create the callback. 00275 // FIXME: this function should have "Cold" calling conv, 00276 // which is not yet implemented. 00277 StringRef WarningFnName = ClKeepGoing ? "__msan_warning" 00278 : "__msan_warning_noreturn"; 00279 WarningFn = M.getOrInsertFunction(WarningFnName, IRB.getVoidTy(), NULL); 00280 00281 MsanCopyOriginFn = M.getOrInsertFunction( 00282 "__msan_copy_origin", IRB.getVoidTy(), IRB.getInt8PtrTy(), 00283 IRB.getInt8PtrTy(), IntptrTy, NULL); 00284 MsanSetAllocaOriginFn = M.getOrInsertFunction( 00285 "__msan_set_alloca_origin", IRB.getVoidTy(), IRB.getInt8PtrTy(), IntptrTy, 00286 IRB.getInt8PtrTy(), NULL); 00287 MsanPoisonStackFn = M.getOrInsertFunction( 00288 "__msan_poison_stack", IRB.getVoidTy(), IRB.getInt8PtrTy(), IntptrTy, NULL); 00289 MemmoveFn = M.getOrInsertFunction( 00290 "__msan_memmove", IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), 00291 IRB.getInt8PtrTy(), IntptrTy, NULL); 00292 MemcpyFn = M.getOrInsertFunction( 00293 "__msan_memcpy", IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), 00294 IntptrTy, NULL); 00295 MemsetFn = M.getOrInsertFunction( 00296 "__msan_memset", IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IRB.getInt32Ty(), 00297 IntptrTy, NULL); 00298 00299 // Create globals. 00300 RetvalTLS = new GlobalVariable( 00301 M, ArrayType::get(IRB.getInt64Ty(), 8), false, 00302 GlobalVariable::ExternalLinkage, 0, "__msan_retval_tls", 0, 00303 GlobalVariable::InitialExecTLSModel); 00304 RetvalOriginTLS = new GlobalVariable( 00305 M, OriginTy, false, GlobalVariable::ExternalLinkage, 0, 00306 "__msan_retval_origin_tls", 0, GlobalVariable::InitialExecTLSModel); 00307 00308 ParamTLS = new GlobalVariable( 00309 M, ArrayType::get(IRB.getInt64Ty(), 1000), false, 00310 GlobalVariable::ExternalLinkage, 0, "__msan_param_tls", 0, 00311 GlobalVariable::InitialExecTLSModel); 00312 ParamOriginTLS = new GlobalVariable( 00313 M, ArrayType::get(OriginTy, 1000), false, GlobalVariable::ExternalLinkage, 00314 0, "__msan_param_origin_tls", 0, GlobalVariable::InitialExecTLSModel); 00315 00316 VAArgTLS = new GlobalVariable( 00317 M, ArrayType::get(IRB.getInt64Ty(), 1000), false, 00318 GlobalVariable::ExternalLinkage, 0, "__msan_va_arg_tls", 0, 00319 GlobalVariable::InitialExecTLSModel); 00320 VAArgOverflowSizeTLS = new GlobalVariable( 00321 M, IRB.getInt64Ty(), false, GlobalVariable::ExternalLinkage, 0, 00322 "__msan_va_arg_overflow_size_tls", 0, 00323 GlobalVariable::InitialExecTLSModel); 00324 OriginTLS = new GlobalVariable( 00325 M, IRB.getInt32Ty(), false, GlobalVariable::ExternalLinkage, 0, 00326 "__msan_origin_tls", 0, GlobalVariable::InitialExecTLSModel); 00327 00328 // We insert an empty inline asm after __msan_report* to avoid callback merge. 00329 EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false), 00330 StringRef(""), StringRef(""), 00331 /*hasSideEffects=*/true); 00332 } 00333 00334 /// \brief Module-level initialization. 00335 /// 00336 /// inserts a call to __msan_init to the module's constructor list. 00337 bool MemorySanitizer::doInitialization(Module &M) { 00338 TD = getAnalysisIfAvailable<DataLayout>(); 00339 if (!TD) 00340 return false; 00341 BL.reset(new BlackList(BlacklistFile)); 00342 C = &(M.getContext()); 00343 unsigned PtrSize = TD->getPointerSizeInBits(/* AddressSpace */0); 00344 switch (PtrSize) { 00345 case 64: 00346 ShadowMask = kShadowMask64; 00347 OriginOffset = kOriginOffset64; 00348 break; 00349 case 32: 00350 ShadowMask = kShadowMask32; 00351 OriginOffset = kOriginOffset32; 00352 break; 00353 default: 00354 report_fatal_error("unsupported pointer size"); 00355 break; 00356 } 00357 00358 IRBuilder<> IRB(*C); 00359 IntptrTy = IRB.getIntPtrTy(TD); 00360 OriginTy = IRB.getInt32Ty(); 00361 00362 ColdCallWeights = MDBuilder(*C).createBranchWeights(1, 1000); 00363 OriginStoreWeights = MDBuilder(*C).createBranchWeights(1, 1000); 00364 00365 // Insert a call to __msan_init/__msan_track_origins into the module's CTORs. 00366 appendToGlobalCtors(M, cast<Function>(M.getOrInsertFunction( 00367 "__msan_init", IRB.getVoidTy(), NULL)), 0); 00368 00369 new GlobalVariable(M, IRB.getInt32Ty(), true, GlobalValue::WeakODRLinkage, 00370 IRB.getInt32(TrackOrigins), "__msan_track_origins"); 00371 00372 new GlobalVariable(M, IRB.getInt32Ty(), true, GlobalValue::WeakODRLinkage, 00373 IRB.getInt32(ClKeepGoing), "__msan_keep_going"); 00374 00375 return true; 00376 } 00377 00378 namespace { 00379 00380 /// \brief A helper class that handles instrumentation of VarArg 00381 /// functions on a particular platform. 00382 /// 00383 /// Implementations are expected to insert the instrumentation 00384 /// necessary to propagate argument shadow through VarArg function 00385 /// calls. Visit* methods are called during an InstVisitor pass over 00386 /// the function, and should avoid creating new basic blocks. A new 00387 /// instance of this class is created for each instrumented function. 00388 struct VarArgHelper { 00389 /// \brief Visit a CallSite. 00390 virtual void visitCallSite(CallSite &CS, IRBuilder<> &IRB) = 0; 00391 00392 /// \brief Visit a va_start call. 00393 virtual void visitVAStartInst(VAStartInst &I) = 0; 00394 00395 /// \brief Visit a va_copy call. 00396 virtual void visitVACopyInst(VACopyInst &I) = 0; 00397 00398 /// \brief Finalize function instrumentation. 00399 /// 00400 /// This method is called after visiting all interesting (see above) 00401 /// instructions in a function. 00402 virtual void finalizeInstrumentation() = 0; 00403 00404 virtual ~VarArgHelper() {} 00405 }; 00406 00407 struct MemorySanitizerVisitor; 00408 00409 VarArgHelper* 00410 CreateVarArgHelper(Function &Func, MemorySanitizer &Msan, 00411 MemorySanitizerVisitor &Visitor); 00412 00413 /// This class does all the work for a given function. Store and Load 00414 /// instructions store and load corresponding shadow and origin 00415 /// values. Most instructions propagate shadow from arguments to their 00416 /// return values. Certain instructions (most importantly, BranchInst) 00417 /// test their argument shadow and print reports (with a runtime call) if it's 00418 /// non-zero. 00419 struct MemorySanitizerVisitor : public InstVisitor<MemorySanitizerVisitor> { 00420 Function &F; 00421 MemorySanitizer &MS; 00422 SmallVector<PHINode *, 16> ShadowPHINodes, OriginPHINodes; 00423 ValueMap<Value*, Value*> ShadowMap, OriginMap; 00424 bool InsertChecks; 00425 bool LoadShadow; 00426 OwningPtr<VarArgHelper> VAHelper; 00427 00428 struct ShadowOriginAndInsertPoint { 00429 Instruction *Shadow; 00430 Instruction *Origin; 00431 Instruction *OrigIns; 00432 ShadowOriginAndInsertPoint(Instruction *S, Instruction *O, Instruction *I) 00433 : Shadow(S), Origin(O), OrigIns(I) { } 00434 ShadowOriginAndInsertPoint() : Shadow(0), Origin(0), OrigIns(0) { } 00435 }; 00436 SmallVector<ShadowOriginAndInsertPoint, 16> InstrumentationList; 00437 SmallVector<Instruction*, 16> StoreList; 00438 00439 MemorySanitizerVisitor(Function &F, MemorySanitizer &MS) 00440 : F(F), MS(MS), VAHelper(CreateVarArgHelper(F, MS, *this)) { 00441 LoadShadow = InsertChecks = 00442 !MS.BL->isIn(F) && 00443 F.getAttributes().hasAttribute(AttributeSet::FunctionIndex, 00444 Attribute::SanitizeMemory); 00445 00446 DEBUG(if (!InsertChecks) 00447 dbgs() << "MemorySanitizer is not inserting checks into '" 00448 << F.getName() << "'\n"); 00449 } 00450 00451 void materializeStores() { 00452 for (size_t i = 0, n = StoreList.size(); i < n; i++) { 00453 StoreInst& I = *dyn_cast<StoreInst>(StoreList[i]); 00454 00455 IRBuilder<> IRB(&I); 00456 Value *Val = I.getValueOperand(); 00457 Value *Addr = I.getPointerOperand(); 00458 Value *Shadow = getShadow(Val); 00459 Value *ShadowPtr = getShadowPtr(Addr, Shadow->getType(), IRB); 00460 00461 StoreInst *NewSI = 00462 IRB.CreateAlignedStore(Shadow, ShadowPtr, I.getAlignment()); 00463 DEBUG(dbgs() << " STORE: " << *NewSI << "\n"); 00464 (void)NewSI; 00465 00466 if (ClCheckAccessAddress) 00467 insertCheck(Addr, &I); 00468 00469 if (MS.TrackOrigins) { 00470 unsigned Alignment = std::max(kMinOriginAlignment, I.getAlignment()); 00471 if (ClStoreCleanOrigin || isa<StructType>(Shadow->getType())) { 00472 IRB.CreateAlignedStore(getOrigin(Val), getOriginPtr(Addr, IRB), 00473 Alignment); 00474 } else { 00475 Value *ConvertedShadow = convertToShadowTyNoVec(Shadow, IRB); 00476 00477 Constant *Cst = dyn_cast_or_null<Constant>(ConvertedShadow); 00478 // TODO(eugenis): handle non-zero constant shadow by inserting an 00479 // unconditional check (can not simply fail compilation as this could 00480 // be in the dead code). 00481 if (Cst) 00482 continue; 00483 00484 Value *Cmp = IRB.CreateICmpNE(ConvertedShadow, 00485 getCleanShadow(ConvertedShadow), "_mscmp"); 00486 Instruction *CheckTerm = 00487 SplitBlockAndInsertIfThen(cast<Instruction>(Cmp), false, 00488 MS.OriginStoreWeights); 00489 IRBuilder<> IRBNew(CheckTerm); 00490 IRBNew.CreateAlignedStore(getOrigin(Val), getOriginPtr(Addr, IRBNew), 00491 Alignment); 00492 } 00493 } 00494 } 00495 } 00496 00497 void materializeChecks() { 00498 for (size_t i = 0, n = InstrumentationList.size(); i < n; i++) { 00499 Instruction *Shadow = InstrumentationList[i].Shadow; 00500 Instruction *OrigIns = InstrumentationList[i].OrigIns; 00501 IRBuilder<> IRB(OrigIns); 00502 DEBUG(dbgs() << " SHAD0 : " << *Shadow << "\n"); 00503 Value *ConvertedShadow = convertToShadowTyNoVec(Shadow, IRB); 00504 DEBUG(dbgs() << " SHAD1 : " << *ConvertedShadow << "\n"); 00505 Value *Cmp = IRB.CreateICmpNE(ConvertedShadow, 00506 getCleanShadow(ConvertedShadow), "_mscmp"); 00507 Instruction *CheckTerm = 00508 SplitBlockAndInsertIfThen(cast<Instruction>(Cmp), 00509 /* Unreachable */ !ClKeepGoing, 00510 MS.ColdCallWeights); 00511 00512 IRB.SetInsertPoint(CheckTerm); 00513 if (MS.TrackOrigins) { 00514 Instruction *Origin = InstrumentationList[i].Origin; 00515 IRB.CreateStore(Origin ? (Value*)Origin : (Value*)IRB.getInt32(0), 00516 MS.OriginTLS); 00517 } 00518 CallInst *Call = IRB.CreateCall(MS.WarningFn); 00519 Call->setDebugLoc(OrigIns->getDebugLoc()); 00520 IRB.CreateCall(MS.EmptyAsm); 00521 DEBUG(dbgs() << " CHECK: " << *Cmp << "\n"); 00522 } 00523 DEBUG(dbgs() << "DONE:\n" << F); 00524 } 00525 00526 /// \brief Add MemorySanitizer instrumentation to a function. 00527 bool runOnFunction() { 00528 MS.initializeCallbacks(*F.getParent()); 00529 if (!MS.TD) return false; 00530 00531 // In the presence of unreachable blocks, we may see Phi nodes with 00532 // incoming nodes from such blocks. Since InstVisitor skips unreachable 00533 // blocks, such nodes will not have any shadow value associated with them. 00534 // It's easier to remove unreachable blocks than deal with missing shadow. 00535 removeUnreachableBlocks(F); 00536 00537 // Iterate all BBs in depth-first order and create shadow instructions 00538 // for all instructions (where applicable). 00539 // For PHI nodes we create dummy shadow PHIs which will be finalized later. 00540 for (df_iterator<BasicBlock*> DI = df_begin(&F.getEntryBlock()), 00541 DE = df_end(&F.getEntryBlock()); DI != DE; ++DI) { 00542 BasicBlock *BB = *DI; 00543 visit(*BB); 00544 } 00545 00546 // Finalize PHI nodes. 00547 for (size_t i = 0, n = ShadowPHINodes.size(); i < n; i++) { 00548 PHINode *PN = ShadowPHINodes[i]; 00549 PHINode *PNS = cast<PHINode>(getShadow(PN)); 00550 PHINode *PNO = MS.TrackOrigins ? cast<PHINode>(getOrigin(PN)) : 0; 00551 size_t NumValues = PN->getNumIncomingValues(); 00552 for (size_t v = 0; v < NumValues; v++) { 00553 PNS->addIncoming(getShadow(PN, v), PN->getIncomingBlock(v)); 00554 if (PNO) 00555 PNO->addIncoming(getOrigin(PN, v), PN->getIncomingBlock(v)); 00556 } 00557 } 00558 00559 VAHelper->finalizeInstrumentation(); 00560 00561 // Delayed instrumentation of StoreInst. 00562 // This may add new checks to be inserted later. 00563 materializeStores(); 00564 00565 // Insert shadow value checks. 00566 materializeChecks(); 00567 00568 return true; 00569 } 00570 00571 /// \brief Compute the shadow type that corresponds to a given Value. 00572 Type *getShadowTy(Value *V) { 00573 return getShadowTy(V->getType()); 00574 } 00575 00576 /// \brief Compute the shadow type that corresponds to a given Type. 00577 Type *getShadowTy(Type *OrigTy) { 00578 if (!OrigTy->isSized()) { 00579 return 0; 00580 } 00581 // For integer type, shadow is the same as the original type. 00582 // This may return weird-sized types like i1. 00583 if (IntegerType *IT = dyn_cast<IntegerType>(OrigTy)) 00584 return IT; 00585 if (VectorType *VT = dyn_cast<VectorType>(OrigTy)) { 00586 uint32_t EltSize = MS.TD->getTypeSizeInBits(VT->getElementType()); 00587 return VectorType::get(IntegerType::get(*MS.C, EltSize), 00588 VT->getNumElements()); 00589 } 00590 if (StructType *ST = dyn_cast<StructType>(OrigTy)) { 00591 SmallVector<Type*, 4> Elements; 00592 for (unsigned i = 0, n = ST->getNumElements(); i < n; i++) 00593 Elements.push_back(getShadowTy(ST->getElementType(i))); 00594 StructType *Res = StructType::get(*MS.C, Elements, ST->isPacked()); 00595 DEBUG(dbgs() << "getShadowTy: " << *ST << " ===> " << *Res << "\n"); 00596 return Res; 00597 } 00598 uint32_t TypeSize = MS.TD->getTypeSizeInBits(OrigTy); 00599 return IntegerType::get(*MS.C, TypeSize); 00600 } 00601 00602 /// \brief Flatten a vector type. 00603 Type *getShadowTyNoVec(Type *ty) { 00604 if (VectorType *vt = dyn_cast<VectorType>(ty)) 00605 return IntegerType::get(*MS.C, vt->getBitWidth()); 00606 return ty; 00607 } 00608 00609 /// \brief Convert a shadow value to it's flattened variant. 00610 Value *convertToShadowTyNoVec(Value *V, IRBuilder<> &IRB) { 00611 Type *Ty = V->getType(); 00612 Type *NoVecTy = getShadowTyNoVec(Ty); 00613 if (Ty == NoVecTy) return V; 00614 return IRB.CreateBitCast(V, NoVecTy); 00615 } 00616 00617 /// \brief Compute the shadow address that corresponds to a given application 00618 /// address. 00619 /// 00620 /// Shadow = Addr & ~ShadowMask. 00621 Value *getShadowPtr(Value *Addr, Type *ShadowTy, 00622 IRBuilder<> &IRB) { 00623 Value *ShadowLong = 00624 IRB.CreateAnd(IRB.CreatePointerCast(Addr, MS.IntptrTy), 00625 ConstantInt::get(MS.IntptrTy, ~MS.ShadowMask)); 00626 return IRB.CreateIntToPtr(ShadowLong, PointerType::get(ShadowTy, 0)); 00627 } 00628 00629 /// \brief Compute the origin address that corresponds to a given application 00630 /// address. 00631 /// 00632 /// OriginAddr = (ShadowAddr + OriginOffset) & ~3ULL 00633 Value *getOriginPtr(Value *Addr, IRBuilder<> &IRB) { 00634 Value *ShadowLong = 00635 IRB.CreateAnd(IRB.CreatePointerCast(Addr, MS.IntptrTy), 00636 ConstantInt::get(MS.IntptrTy, ~MS.ShadowMask)); 00637 Value *Add = 00638 IRB.CreateAdd(ShadowLong, 00639 ConstantInt::get(MS.IntptrTy, MS.OriginOffset)); 00640 Value *SecondAnd = 00641 IRB.CreateAnd(Add, ConstantInt::get(MS.IntptrTy, ~3ULL)); 00642 return IRB.CreateIntToPtr(SecondAnd, PointerType::get(IRB.getInt32Ty(), 0)); 00643 } 00644 00645 /// \brief Compute the shadow address for a given function argument. 00646 /// 00647 /// Shadow = ParamTLS+ArgOffset. 00648 Value *getShadowPtrForArgument(Value *A, IRBuilder<> &IRB, 00649 int ArgOffset) { 00650 Value *Base = IRB.CreatePointerCast(MS.ParamTLS, MS.IntptrTy); 00651 Base = IRB.CreateAdd(Base, ConstantInt::get(MS.IntptrTy, ArgOffset)); 00652 return IRB.CreateIntToPtr(Base, PointerType::get(getShadowTy(A), 0), 00653 "_msarg"); 00654 } 00655 00656 /// \brief Compute the origin address for a given function argument. 00657 Value *getOriginPtrForArgument(Value *A, IRBuilder<> &IRB, 00658 int ArgOffset) { 00659 if (!MS.TrackOrigins) return 0; 00660 Value *Base = IRB.CreatePointerCast(MS.ParamOriginTLS, MS.IntptrTy); 00661 Base = IRB.CreateAdd(Base, ConstantInt::get(MS.IntptrTy, ArgOffset)); 00662 return IRB.CreateIntToPtr(Base, PointerType::get(MS.OriginTy, 0), 00663 "_msarg_o"); 00664 } 00665 00666 /// \brief Compute the shadow address for a retval. 00667 Value *getShadowPtrForRetval(Value *A, IRBuilder<> &IRB) { 00668 Value *Base = IRB.CreatePointerCast(MS.RetvalTLS, MS.IntptrTy); 00669 return IRB.CreateIntToPtr(Base, PointerType::get(getShadowTy(A), 0), 00670 "_msret"); 00671 } 00672 00673 /// \brief Compute the origin address for a retval. 00674 Value *getOriginPtrForRetval(IRBuilder<> &IRB) { 00675 // We keep a single origin for the entire retval. Might be too optimistic. 00676 return MS.RetvalOriginTLS; 00677 } 00678 00679 /// \brief Set SV to be the shadow value for V. 00680 void setShadow(Value *V, Value *SV) { 00681 assert(!ShadowMap.count(V) && "Values may only have one shadow"); 00682 ShadowMap[V] = SV; 00683 } 00684 00685 /// \brief Set Origin to be the origin value for V. 00686 void setOrigin(Value *V, Value *Origin) { 00687 if (!MS.TrackOrigins) return; 00688 assert(!OriginMap.count(V) && "Values may only have one origin"); 00689 DEBUG(dbgs() << "ORIGIN: " << *V << " ==> " << *Origin << "\n"); 00690 OriginMap[V] = Origin; 00691 } 00692 00693 /// \brief Create a clean shadow value for a given value. 00694 /// 00695 /// Clean shadow (all zeroes) means all bits of the value are defined 00696 /// (initialized). 00697 Constant *getCleanShadow(Value *V) { 00698 Type *ShadowTy = getShadowTy(V); 00699 if (!ShadowTy) 00700 return 0; 00701 return Constant::getNullValue(ShadowTy); 00702 } 00703 00704 /// \brief Create a dirty shadow of a given shadow type. 00705 Constant *getPoisonedShadow(Type *ShadowTy) { 00706 assert(ShadowTy); 00707 if (isa<IntegerType>(ShadowTy) || isa<VectorType>(ShadowTy)) 00708 return Constant::getAllOnesValue(ShadowTy); 00709 StructType *ST = cast<StructType>(ShadowTy); 00710 SmallVector<Constant *, 4> Vals; 00711 for (unsigned i = 0, n = ST->getNumElements(); i < n; i++) 00712 Vals.push_back(getPoisonedShadow(ST->getElementType(i))); 00713 return ConstantStruct::get(ST, Vals); 00714 } 00715 00716 /// \brief Create a dirty shadow for a given value. 00717 Constant *getPoisonedShadow(Value *V) { 00718 Type *ShadowTy = getShadowTy(V); 00719 if (!ShadowTy) 00720 return 0; 00721 return getPoisonedShadow(ShadowTy); 00722 } 00723 00724 /// \brief Create a clean (zero) origin. 00725 Value *getCleanOrigin() { 00726 return Constant::getNullValue(MS.OriginTy); 00727 } 00728 00729 /// \brief Get the shadow value for a given Value. 00730 /// 00731 /// This function either returns the value set earlier with setShadow, 00732 /// or extracts if from ParamTLS (for function arguments). 00733 Value *getShadow(Value *V) { 00734 if (Instruction *I = dyn_cast<Instruction>(V)) { 00735 // For instructions the shadow is already stored in the map. 00736 Value *Shadow = ShadowMap[V]; 00737 if (!Shadow) { 00738 DEBUG(dbgs() << "No shadow: " << *V << "\n" << *(I->getParent())); 00739 (void)I; 00740 assert(Shadow && "No shadow for a value"); 00741 } 00742 return Shadow; 00743 } 00744 if (UndefValue *U = dyn_cast<UndefValue>(V)) { 00745 Value *AllOnes = ClPoisonUndef ? getPoisonedShadow(V) : getCleanShadow(V); 00746 DEBUG(dbgs() << "Undef: " << *U << " ==> " << *AllOnes << "\n"); 00747 (void)U; 00748 return AllOnes; 00749 } 00750 if (Argument *A = dyn_cast<Argument>(V)) { 00751 // For arguments we compute the shadow on demand and store it in the map. 00752 Value **ShadowPtr = &ShadowMap[V]; 00753 if (*ShadowPtr) 00754 return *ShadowPtr; 00755 Function *F = A->getParent(); 00756 IRBuilder<> EntryIRB(F->getEntryBlock().getFirstNonPHI()); 00757 unsigned ArgOffset = 0; 00758 for (Function::arg_iterator AI = F->arg_begin(), AE = F->arg_end(); 00759 AI != AE; ++AI) { 00760 if (!AI->getType()->isSized()) { 00761 DEBUG(dbgs() << "Arg is not sized\n"); 00762 continue; 00763 } 00764 unsigned Size = AI->hasByValAttr() 00765 ? MS.TD->getTypeAllocSize(AI->getType()->getPointerElementType()) 00766 : MS.TD->getTypeAllocSize(AI->getType()); 00767 if (A == AI) { 00768 Value *Base = getShadowPtrForArgument(AI, EntryIRB, ArgOffset); 00769 if (AI->hasByValAttr()) { 00770 // ByVal pointer itself has clean shadow. We copy the actual 00771 // argument shadow to the underlying memory. 00772 Value *Cpy = EntryIRB.CreateMemCpy( 00773 getShadowPtr(V, EntryIRB.getInt8Ty(), EntryIRB), 00774 Base, Size, AI->getParamAlignment()); 00775 DEBUG(dbgs() << " ByValCpy: " << *Cpy << "\n"); 00776 (void)Cpy; 00777 *ShadowPtr = getCleanShadow(V); 00778 } else { 00779 *ShadowPtr = EntryIRB.CreateLoad(Base); 00780 } 00781 DEBUG(dbgs() << " ARG: " << *AI << " ==> " << 00782 **ShadowPtr << "\n"); 00783 if (MS.TrackOrigins) { 00784 Value* OriginPtr = getOriginPtrForArgument(AI, EntryIRB, ArgOffset); 00785 setOrigin(A, EntryIRB.CreateLoad(OriginPtr)); 00786 } 00787 } 00788 ArgOffset += DataLayout::RoundUpAlignment(Size, 8); 00789 } 00790 assert(*ShadowPtr && "Could not find shadow for an argument"); 00791 return *ShadowPtr; 00792 } 00793 // For everything else the shadow is zero. 00794 return getCleanShadow(V); 00795 } 00796 00797 /// \brief Get the shadow for i-th argument of the instruction I. 00798 Value *getShadow(Instruction *I, int i) { 00799 return getShadow(I->getOperand(i)); 00800 } 00801 00802 /// \brief Get the origin for a value. 00803 Value *getOrigin(Value *V) { 00804 if (!MS.TrackOrigins) return 0; 00805 if (isa<Instruction>(V) || isa<Argument>(V)) { 00806 Value *Origin = OriginMap[V]; 00807 if (!Origin) { 00808 DEBUG(dbgs() << "NO ORIGIN: " << *V << "\n"); 00809 Origin = getCleanOrigin(); 00810 } 00811 return Origin; 00812 } 00813 return getCleanOrigin(); 00814 } 00815 00816 /// \brief Get the origin for i-th argument of the instruction I. 00817 Value *getOrigin(Instruction *I, int i) { 00818 return getOrigin(I->getOperand(i)); 00819 } 00820 00821 /// \brief Remember the place where a shadow check should be inserted. 00822 /// 00823 /// This location will be later instrumented with a check that will print a 00824 /// UMR warning in runtime if the value is not fully defined. 00825 void insertCheck(Value *Val, Instruction *OrigIns) { 00826 assert(Val); 00827 if (!InsertChecks) return; 00828 Instruction *Shadow = dyn_cast_or_null<Instruction>(getShadow(Val)); 00829 if (!Shadow) return; 00830 #ifndef NDEBUG 00831 Type *ShadowTy = Shadow->getType(); 00832 assert((isa<IntegerType>(ShadowTy) || isa<VectorType>(ShadowTy)) && 00833 "Can only insert checks for integer and vector shadow types"); 00834 #endif 00835 Instruction *Origin = dyn_cast_or_null<Instruction>(getOrigin(Val)); 00836 InstrumentationList.push_back( 00837 ShadowOriginAndInsertPoint(Shadow, Origin, OrigIns)); 00838 } 00839 00840 // ------------------- Visitors. 00841 00842 /// \brief Instrument LoadInst 00843 /// 00844 /// Loads the corresponding shadow and (optionally) origin. 00845 /// Optionally, checks that the load address is fully defined. 00846 void visitLoadInst(LoadInst &I) { 00847 assert(I.getType()->isSized() && "Load type must have size"); 00848 IRBuilder<> IRB(&I); 00849 Type *ShadowTy = getShadowTy(&I); 00850 Value *Addr = I.getPointerOperand(); 00851 if (LoadShadow) { 00852 Value *ShadowPtr = getShadowPtr(Addr, ShadowTy, IRB); 00853 setShadow(&I, 00854 IRB.CreateAlignedLoad(ShadowPtr, I.getAlignment(), "_msld")); 00855 } else { 00856 setShadow(&I, getCleanShadow(&I)); 00857 } 00858 00859 if (ClCheckAccessAddress) 00860 insertCheck(I.getPointerOperand(), &I); 00861 00862 if (MS.TrackOrigins) { 00863 if (LoadShadow) { 00864 unsigned Alignment = std::max(kMinOriginAlignment, I.getAlignment()); 00865 setOrigin(&I, 00866 IRB.CreateAlignedLoad(getOriginPtr(Addr, IRB), Alignment)); 00867 } else { 00868 setOrigin(&I, getCleanOrigin()); 00869 } 00870 } 00871 } 00872 00873 /// \brief Instrument StoreInst 00874 /// 00875 /// Stores the corresponding shadow and (optionally) origin. 00876 /// Optionally, checks that the store address is fully defined. 00877 void visitStoreInst(StoreInst &I) { 00878 StoreList.push_back(&I); 00879 } 00880 00881 // Vector manipulation. 00882 void visitExtractElementInst(ExtractElementInst &I) { 00883 insertCheck(I.getOperand(1), &I); 00884 IRBuilder<> IRB(&I); 00885 setShadow(&I, IRB.CreateExtractElement(getShadow(&I, 0), I.getOperand(1), 00886 "_msprop")); 00887 setOrigin(&I, getOrigin(&I, 0)); 00888 } 00889 00890 void visitInsertElementInst(InsertElementInst &I) { 00891 insertCheck(I.getOperand(2), &I); 00892 IRBuilder<> IRB(&I); 00893 setShadow(&I, IRB.CreateInsertElement(getShadow(&I, 0), getShadow(&I, 1), 00894 I.getOperand(2), "_msprop")); 00895 setOriginForNaryOp(I); 00896 } 00897 00898 void visitShuffleVectorInst(ShuffleVectorInst &I) { 00899 insertCheck(I.getOperand(2), &I); 00900 IRBuilder<> IRB(&I); 00901 setShadow(&I, IRB.CreateShuffleVector(getShadow(&I, 0), getShadow(&I, 1), 00902 I.getOperand(2), "_msprop")); 00903 setOriginForNaryOp(I); 00904 } 00905 00906 // Casts. 00907 void visitSExtInst(SExtInst &I) { 00908 IRBuilder<> IRB(&I); 00909 setShadow(&I, IRB.CreateSExt(getShadow(&I, 0), I.getType(), "_msprop")); 00910 setOrigin(&I, getOrigin(&I, 0)); 00911 } 00912 00913 void visitZExtInst(ZExtInst &I) { 00914 IRBuilder<> IRB(&I); 00915 setShadow(&I, IRB.CreateZExt(getShadow(&I, 0), I.getType(), "_msprop")); 00916 setOrigin(&I, getOrigin(&I, 0)); 00917 } 00918 00919 void visitTruncInst(TruncInst &I) { 00920 IRBuilder<> IRB(&I); 00921 setShadow(&I, IRB.CreateTrunc(getShadow(&I, 0), I.getType(), "_msprop")); 00922 setOrigin(&I, getOrigin(&I, 0)); 00923 } 00924 00925 void visitBitCastInst(BitCastInst &I) { 00926 IRBuilder<> IRB(&I); 00927 setShadow(&I, IRB.CreateBitCast(getShadow(&I, 0), getShadowTy(&I))); 00928 setOrigin(&I, getOrigin(&I, 0)); 00929 } 00930 00931 void visitPtrToIntInst(PtrToIntInst &I) { 00932 IRBuilder<> IRB(&I); 00933 setShadow(&I, IRB.CreateIntCast(getShadow(&I, 0), getShadowTy(&I), false, 00934 "_msprop_ptrtoint")); 00935 setOrigin(&I, getOrigin(&I, 0)); 00936 } 00937 00938 void visitIntToPtrInst(IntToPtrInst &I) { 00939 IRBuilder<> IRB(&I); 00940 setShadow(&I, IRB.CreateIntCast(getShadow(&I, 0), getShadowTy(&I), false, 00941 "_msprop_inttoptr")); 00942 setOrigin(&I, getOrigin(&I, 0)); 00943 } 00944 00945 void visitFPToSIInst(CastInst& I) { handleShadowOr(I); } 00946 void visitFPToUIInst(CastInst& I) { handleShadowOr(I); } 00947 void visitSIToFPInst(CastInst& I) { handleShadowOr(I); } 00948 void visitUIToFPInst(CastInst& I) { handleShadowOr(I); } 00949 void visitFPExtInst(CastInst& I) { handleShadowOr(I); } 00950 void visitFPTruncInst(CastInst& I) { handleShadowOr(I); } 00951 00952 /// \brief Propagate shadow for bitwise AND. 00953 /// 00954 /// This code is exact, i.e. if, for example, a bit in the left argument 00955 /// is defined and 0, then neither the value not definedness of the 00956 /// corresponding bit in B don't affect the resulting shadow. 00957 void visitAnd(BinaryOperator &I) { 00958 IRBuilder<> IRB(&I); 00959 // "And" of 0 and a poisoned value results in unpoisoned value. 00960 // 1&1 => 1; 0&1 => 0; p&1 => p; 00961 // 1&0 => 0; 0&0 => 0; p&0 => 0; 00962 // 1&p => p; 0&p => 0; p&p => p; 00963 // S = (S1 & S2) | (V1 & S2) | (S1 & V2) 00964 Value *S1 = getShadow(&I, 0); 00965 Value *S2 = getShadow(&I, 1); 00966 Value *V1 = I.getOperand(0); 00967 Value *V2 = I.getOperand(1); 00968 if (V1->getType() != S1->getType()) { 00969 V1 = IRB.CreateIntCast(V1, S1->getType(), false); 00970 V2 = IRB.CreateIntCast(V2, S2->getType(), false); 00971 } 00972 Value *S1S2 = IRB.CreateAnd(S1, S2); 00973 Value *V1S2 = IRB.CreateAnd(V1, S2); 00974 Value *S1V2 = IRB.CreateAnd(S1, V2); 00975 setShadow(&I, IRB.CreateOr(S1S2, IRB.CreateOr(V1S2, S1V2))); 00976 setOriginForNaryOp(I); 00977 } 00978 00979 void visitOr(BinaryOperator &I) { 00980 IRBuilder<> IRB(&I); 00981 // "Or" of 1 and a poisoned value results in unpoisoned value. 00982 // 1|1 => 1; 0|1 => 1; p|1 => 1; 00983 // 1|0 => 1; 0|0 => 0; p|0 => p; 00984 // 1|p => 1; 0|p => p; p|p => p; 00985 // S = (S1 & S2) | (~V1 & S2) | (S1 & ~V2) 00986 Value *S1 = getShadow(&I, 0); 00987 Value *S2 = getShadow(&I, 1); 00988 Value *V1 = IRB.CreateNot(I.getOperand(0)); 00989 Value *V2 = IRB.CreateNot(I.getOperand(1)); 00990 if (V1->getType() != S1->getType()) { 00991 V1 = IRB.CreateIntCast(V1, S1->getType(), false); 00992 V2 = IRB.CreateIntCast(V2, S2->getType(), false); 00993 } 00994 Value *S1S2 = IRB.CreateAnd(S1, S2); 00995 Value *V1S2 = IRB.CreateAnd(V1, S2); 00996 Value *S1V2 = IRB.CreateAnd(S1, V2); 00997 setShadow(&I, IRB.CreateOr(S1S2, IRB.CreateOr(V1S2, S1V2))); 00998 setOriginForNaryOp(I); 00999 } 01000 01001 /// \brief Default propagation of shadow and/or origin. 01002 /// 01003 /// This class implements the general case of shadow propagation, used in all 01004 /// cases where we don't know and/or don't care about what the operation 01005 /// actually does. It converts all input shadow values to a common type 01006 /// (extending or truncating as necessary), and bitwise OR's them. 01007 /// 01008 /// This is much cheaper than inserting checks (i.e. requiring inputs to be 01009 /// fully initialized), and less prone to false positives. 01010 /// 01011 /// This class also implements the general case of origin propagation. For a 01012 /// Nary operation, result origin is set to the origin of an argument that is 01013 /// not entirely initialized. If there is more than one such arguments, the 01014 /// rightmost of them is picked. It does not matter which one is picked if all 01015 /// arguments are initialized. 01016 template <bool CombineShadow> 01017 class Combiner { 01018 Value *Shadow; 01019 Value *Origin; 01020 IRBuilder<> &IRB; 01021 MemorySanitizerVisitor *MSV; 01022 01023 public: 01024 Combiner(MemorySanitizerVisitor *MSV, IRBuilder<> &IRB) : 01025 Shadow(0), Origin(0), IRB(IRB), MSV(MSV) {} 01026 01027 /// \brief Add a pair of shadow and origin values to the mix. 01028 Combiner &Add(Value *OpShadow, Value *OpOrigin) { 01029 if (CombineShadow) { 01030 assert(OpShadow); 01031 if (!Shadow) 01032 Shadow = OpShadow; 01033 else { 01034 OpShadow = MSV->CreateShadowCast(IRB, OpShadow, Shadow->getType()); 01035 Shadow = IRB.CreateOr(Shadow, OpShadow, "_msprop"); 01036 } 01037 } 01038 01039 if (MSV->MS.TrackOrigins) { 01040 assert(OpOrigin); 01041 if (!Origin) { 01042 Origin = OpOrigin; 01043 } else { 01044 Value *FlatShadow = MSV->convertToShadowTyNoVec(OpShadow, IRB); 01045 Value *Cond = IRB.CreateICmpNE(FlatShadow, 01046 MSV->getCleanShadow(FlatShadow)); 01047 Origin = IRB.CreateSelect(Cond, OpOrigin, Origin); 01048 } 01049 } 01050 return *this; 01051 } 01052 01053 /// \brief Add an application value to the mix. 01054 Combiner &Add(Value *V) { 01055 Value *OpShadow = MSV->getShadow(V); 01056 Value *OpOrigin = MSV->MS.TrackOrigins ? MSV->getOrigin(V) : 0; 01057 return Add(OpShadow, OpOrigin); 01058 } 01059 01060 /// \brief Set the current combined values as the given instruction's shadow 01061 /// and origin. 01062 void Done(Instruction *I) { 01063 if (CombineShadow) { 01064 assert(Shadow); 01065 Shadow = MSV->CreateShadowCast(IRB, Shadow, MSV->getShadowTy(I)); 01066 MSV->setShadow(I, Shadow); 01067 } 01068 if (MSV->MS.TrackOrigins) { 01069 assert(Origin); 01070 MSV->setOrigin(I, Origin); 01071 } 01072 } 01073 }; 01074 01075 typedef Combiner<true> ShadowAndOriginCombiner; 01076 typedef Combiner<false> OriginCombiner; 01077 01078 /// \brief Propagate origin for arbitrary operation. 01079 void setOriginForNaryOp(Instruction &I) { 01080 if (!MS.TrackOrigins) return; 01081 IRBuilder<> IRB(&I); 01082 OriginCombiner OC(this, IRB); 01083 for (Instruction::op_iterator OI = I.op_begin(); OI != I.op_end(); ++OI) 01084 OC.Add(OI->get()); 01085 OC.Done(&I); 01086 } 01087 01088 size_t VectorOrPrimitiveTypeSizeInBits(Type *Ty) { 01089 assert(!(Ty->isVectorTy() && Ty->getScalarType()->isPointerTy()) && 01090 "Vector of pointers is not a valid shadow type"); 01091 return Ty->isVectorTy() ? 01092 Ty->getVectorNumElements() * Ty->getScalarSizeInBits() : 01093 Ty->getPrimitiveSizeInBits(); 01094 } 01095 01096 /// \brief Cast between two shadow types, extending or truncating as 01097 /// necessary. 01098 Value *CreateShadowCast(IRBuilder<> &IRB, Value *V, Type *dstTy) { 01099 Type *srcTy = V->getType(); 01100 if (dstTy->isIntegerTy() && srcTy->isIntegerTy()) 01101 return IRB.CreateIntCast(V, dstTy, false); 01102 if (dstTy->isVectorTy() && srcTy->isVectorTy() && 01103 dstTy->getVectorNumElements() == srcTy->getVectorNumElements()) 01104 return IRB.CreateIntCast(V, dstTy, false); 01105 size_t srcSizeInBits = VectorOrPrimitiveTypeSizeInBits(srcTy); 01106 size_t dstSizeInBits = VectorOrPrimitiveTypeSizeInBits(dstTy); 01107 Value *V1 = IRB.CreateBitCast(V, Type::getIntNTy(*MS.C, srcSizeInBits)); 01108 Value *V2 = 01109 IRB.CreateIntCast(V1, Type::getIntNTy(*MS.C, dstSizeInBits), false); 01110 return IRB.CreateBitCast(V2, dstTy); 01111 // TODO: handle struct types. 01112 } 01113 01114 /// \brief Propagate shadow for arbitrary operation. 01115 void handleShadowOr(Instruction &I) { 01116 IRBuilder<> IRB(&I); 01117 ShadowAndOriginCombiner SC(this, IRB); 01118 for (Instruction::op_iterator OI = I.op_begin(); OI != I.op_end(); ++OI) 01119 SC.Add(OI->get()); 01120 SC.Done(&I); 01121 } 01122 01123 void visitFAdd(BinaryOperator &I) { handleShadowOr(I); } 01124 void visitFSub(BinaryOperator &I) { handleShadowOr(I); } 01125 void visitFMul(BinaryOperator &I) { handleShadowOr(I); } 01126 void visitAdd(BinaryOperator &I) { handleShadowOr(I); } 01127 void visitSub(BinaryOperator &I) { handleShadowOr(I); } 01128 void visitXor(BinaryOperator &I) { handleShadowOr(I); } 01129 void visitMul(BinaryOperator &I) { handleShadowOr(I); } 01130 01131 void handleDiv(Instruction &I) { 01132 IRBuilder<> IRB(&I); 01133 // Strict on the second argument. 01134 insertCheck(I.getOperand(1), &I); 01135 setShadow(&I, getShadow(&I, 0)); 01136 setOrigin(&I, getOrigin(&I, 0)); 01137 } 01138 01139 void visitUDiv(BinaryOperator &I) { handleDiv(I); } 01140 void visitSDiv(BinaryOperator &I) { handleDiv(I); } 01141 void visitFDiv(BinaryOperator &I) { handleDiv(I); } 01142 void visitURem(BinaryOperator &I) { handleDiv(I); } 01143 void visitSRem(BinaryOperator &I) { handleDiv(I); } 01144 void visitFRem(BinaryOperator &I) { handleDiv(I); } 01145 01146 /// \brief Instrument == and != comparisons. 01147 /// 01148 /// Sometimes the comparison result is known even if some of the bits of the 01149 /// arguments are not. 01150 void handleEqualityComparison(ICmpInst &I) { 01151 IRBuilder<> IRB(&I); 01152 Value *A = I.getOperand(0); 01153 Value *B = I.getOperand(1); 01154 Value *Sa = getShadow(A); 01155 Value *Sb = getShadow(B); 01156 01157 // Get rid of pointers and vectors of pointers. 01158 // For ints (and vectors of ints), types of A and Sa match, 01159 // and this is a no-op. 01160 A = IRB.CreatePointerCast(A, Sa->getType()); 01161 B = IRB.CreatePointerCast(B, Sb->getType()); 01162 01163 // A == B <==> (C = A^B) == 0 01164 // A != B <==> (C = A^B) != 0 01165 // Sc = Sa | Sb 01166 Value *C = IRB.CreateXor(A, B); 01167 Value *Sc = IRB.CreateOr(Sa, Sb); 01168 // Now dealing with i = (C == 0) comparison (or C != 0, does not matter now) 01169 // Result is defined if one of the following is true 01170 // * there is a defined 1 bit in C 01171 // * C is fully defined 01172 // Si = !(C & ~Sc) && Sc 01173 Value *Zero = Constant::getNullValue(Sc->getType()); 01174 Value *MinusOne = Constant::getAllOnesValue(Sc->getType()); 01175 Value *Si = 01176 IRB.CreateAnd(IRB.CreateICmpNE(Sc, Zero), 01177 IRB.CreateICmpEQ( 01178 IRB.CreateAnd(IRB.CreateXor(Sc, MinusOne), C), Zero)); 01179 Si->setName("_msprop_icmp"); 01180 setShadow(&I, Si); 01181 setOriginForNaryOp(I); 01182 } 01183 01184 /// \brief Build the lowest possible value of V, taking into account V's 01185 /// uninitialized bits. 01186 Value *getLowestPossibleValue(IRBuilder<> &IRB, Value *A, Value *Sa, 01187 bool isSigned) { 01188 if (isSigned) { 01189 // Split shadow into sign bit and other bits. 01190 Value *SaOtherBits = IRB.CreateLShr(IRB.CreateShl(Sa, 1), 1); 01191 Value *SaSignBit = IRB.CreateXor(Sa, SaOtherBits); 01192 // Maximise the undefined shadow bit, minimize other undefined bits. 01193 return 01194 IRB.CreateOr(IRB.CreateAnd(A, IRB.CreateNot(SaOtherBits)), SaSignBit); 01195 } else { 01196 // Minimize undefined bits. 01197 return IRB.CreateAnd(A, IRB.CreateNot(Sa)); 01198 } 01199 } 01200 01201 /// \brief Build the highest possible value of V, taking into account V's 01202 /// uninitialized bits. 01203 Value *getHighestPossibleValue(IRBuilder<> &IRB, Value *A, Value *Sa, 01204 bool isSigned) { 01205 if (isSigned) { 01206 // Split shadow into sign bit and other bits. 01207 Value *SaOtherBits = IRB.CreateLShr(IRB.CreateShl(Sa, 1), 1); 01208 Value *SaSignBit = IRB.CreateXor(Sa, SaOtherBits); 01209 // Minimise the undefined shadow bit, maximise other undefined bits. 01210 return 01211 IRB.CreateOr(IRB.CreateAnd(A, IRB.CreateNot(SaSignBit)), SaOtherBits); 01212 } else { 01213 // Maximize undefined bits. 01214 return IRB.CreateOr(A, Sa); 01215 } 01216 } 01217 01218 /// \brief Instrument relational comparisons. 01219 /// 01220 /// This function does exact shadow propagation for all relational 01221 /// comparisons of integers, pointers and vectors of those. 01222 /// FIXME: output seems suboptimal when one of the operands is a constant 01223 void handleRelationalComparisonExact(ICmpInst &I) { 01224 IRBuilder<> IRB(&I); 01225 Value *A = I.getOperand(0); 01226 Value *B = I.getOperand(1); 01227 Value *Sa = getShadow(A); 01228 Value *Sb = getShadow(B); 01229 01230 // Get rid of pointers and vectors of pointers. 01231 // For ints (and vectors of ints), types of A and Sa match, 01232 // and this is a no-op. 01233 A = IRB.CreatePointerCast(A, Sa->getType()); 01234 B = IRB.CreatePointerCast(B, Sb->getType()); 01235 01236 // Let [a0, a1] be the interval of possible values of A, taking into account 01237 // its undefined bits. Let [b0, b1] be the interval of possible values of B. 01238 // Then (A cmp B) is defined iff (a0 cmp b1) == (a1 cmp b0). 01239 bool IsSigned = I.isSigned(); 01240 Value *S1 = IRB.CreateICmp(I.getPredicate(), 01241 getLowestPossibleValue(IRB, A, Sa, IsSigned), 01242 getHighestPossibleValue(IRB, B, Sb, IsSigned)); 01243 Value *S2 = IRB.CreateICmp(I.getPredicate(), 01244 getHighestPossibleValue(IRB, A, Sa, IsSigned), 01245 getLowestPossibleValue(IRB, B, Sb, IsSigned)); 01246 Value *Si = IRB.CreateXor(S1, S2); 01247 setShadow(&I, Si); 01248 setOriginForNaryOp(I); 01249 } 01250 01251 /// \brief Instrument signed relational comparisons. 01252 /// 01253 /// Handle (x<0) and (x>=0) comparisons (essentially, sign bit tests) by 01254 /// propagating the highest bit of the shadow. Everything else is delegated 01255 /// to handleShadowOr(). 01256 void handleSignedRelationalComparison(ICmpInst &I) { 01257 Constant *constOp0 = dyn_cast<Constant>(I.getOperand(0)); 01258 Constant *constOp1 = dyn_cast<Constant>(I.getOperand(1)); 01259 Value* op = NULL; 01260 CmpInst::Predicate pre = I.getPredicate(); 01261 if (constOp0 && constOp0->isNullValue() && 01262 (pre == CmpInst::ICMP_SGT || pre == CmpInst::ICMP_SLE)) { 01263 op = I.getOperand(1); 01264 } else if (constOp1 && constOp1->isNullValue() && 01265 (pre == CmpInst::ICMP_SLT || pre == CmpInst::ICMP_SGE)) { 01266 op = I.getOperand(0); 01267 } 01268 if (op) { 01269 IRBuilder<> IRB(&I); 01270 Value* Shadow = 01271 IRB.CreateICmpSLT(getShadow(op), getCleanShadow(op), "_msprop_icmpslt"); 01272 setShadow(&I, Shadow); 01273 setOrigin(&I, getOrigin(op)); 01274 } else { 01275 handleShadowOr(I); 01276 } 01277 } 01278 01279 void visitICmpInst(ICmpInst &I) { 01280 if (!ClHandleICmp) { 01281 handleShadowOr(I); 01282 return; 01283 } 01284 if (I.isEquality()) { 01285 handleEqualityComparison(I); 01286 return; 01287 } 01288 01289 assert(I.isRelational()); 01290 if (ClHandleICmpExact) { 01291 handleRelationalComparisonExact(I); 01292 return; 01293 } 01294 if (I.isSigned()) { 01295 handleSignedRelationalComparison(I); 01296 return; 01297 } 01298 01299 assert(I.isUnsigned()); 01300 if ((isa<Constant>(I.getOperand(0)) || isa<Constant>(I.getOperand(1)))) { 01301 handleRelationalComparisonExact(I); 01302 return; 01303 } 01304 01305 handleShadowOr(I); 01306 } 01307 01308 void visitFCmpInst(FCmpInst &I) { 01309 handleShadowOr(I); 01310 } 01311 01312 void handleShift(BinaryOperator &I) { 01313 IRBuilder<> IRB(&I); 01314 // If any of the S2 bits are poisoned, the whole thing is poisoned. 01315 // Otherwise perform the same shift on S1. 01316 Value *S1 = getShadow(&I, 0); 01317 Value *S2 = getShadow(&I, 1); 01318 Value *S2Conv = IRB.CreateSExt(IRB.CreateICmpNE(S2, getCleanShadow(S2)), 01319 S2->getType()); 01320 Value *V2 = I.getOperand(1); 01321 Value *Shift = IRB.CreateBinOp(I.getOpcode(), S1, V2); 01322 setShadow(&I, IRB.CreateOr(Shift, S2Conv)); 01323 setOriginForNaryOp(I); 01324 } 01325 01326 void visitShl(BinaryOperator &I) { handleShift(I); } 01327 void visitAShr(BinaryOperator &I) { handleShift(I); } 01328 void visitLShr(BinaryOperator &I) { handleShift(I); } 01329 01330 /// \brief Instrument llvm.memmove 01331 /// 01332 /// At this point we don't know if llvm.memmove will be inlined or not. 01333 /// If we don't instrument it and it gets inlined, 01334 /// our interceptor will not kick in and we will lose the memmove. 01335 /// If we instrument the call here, but it does not get inlined, 01336 /// we will memove the shadow twice: which is bad in case 01337 /// of overlapping regions. So, we simply lower the intrinsic to a call. 01338 /// 01339 /// Similar situation exists for memcpy and memset. 01340 void visitMemMoveInst(MemMoveInst &I) { 01341 IRBuilder<> IRB(&I); 01342 IRB.CreateCall3( 01343 MS.MemmoveFn, 01344 IRB.CreatePointerCast(I.getArgOperand(0), IRB.getInt8PtrTy()), 01345 IRB.CreatePointerCast(I.getArgOperand(1), IRB.getInt8PtrTy()), 01346 IRB.CreateIntCast(I.getArgOperand(2), MS.IntptrTy, false)); 01347 I.eraseFromParent(); 01348 } 01349 01350 // Similar to memmove: avoid copying shadow twice. 01351 // This is somewhat unfortunate as it may slowdown small constant memcpys. 01352 // FIXME: consider doing manual inline for small constant sizes and proper 01353 // alignment. 01354 void visitMemCpyInst(MemCpyInst &I) { 01355 IRBuilder<> IRB(&I); 01356 IRB.CreateCall3( 01357 MS.MemcpyFn, 01358 IRB.CreatePointerCast(I.getArgOperand(0), IRB.getInt8PtrTy()), 01359 IRB.CreatePointerCast(I.getArgOperand(1), IRB.getInt8PtrTy()), 01360 IRB.CreateIntCast(I.getArgOperand(2), MS.IntptrTy, false)); 01361 I.eraseFromParent(); 01362 } 01363 01364 // Same as memcpy. 01365 void visitMemSetInst(MemSetInst &I) { 01366 IRBuilder<> IRB(&I); 01367 IRB.CreateCall3( 01368 MS.MemsetFn, 01369 IRB.CreatePointerCast(I.getArgOperand(0), IRB.getInt8PtrTy()), 01370 IRB.CreateIntCast(I.getArgOperand(1), IRB.getInt32Ty(), false), 01371 IRB.CreateIntCast(I.getArgOperand(2), MS.IntptrTy, false)); 01372 I.eraseFromParent(); 01373 } 01374 01375 void visitVAStartInst(VAStartInst &I) { 01376 VAHelper->visitVAStartInst(I); 01377 } 01378 01379 void visitVACopyInst(VACopyInst &I) { 01380 VAHelper->visitVACopyInst(I); 01381 } 01382 01383 enum IntrinsicKind { 01384 IK_DoesNotAccessMemory, 01385 IK_OnlyReadsMemory, 01386 IK_WritesMemory 01387 }; 01388 01389 static IntrinsicKind getIntrinsicKind(Intrinsic::ID iid) { 01390 const int DoesNotAccessMemory = IK_DoesNotAccessMemory; 01391 const int OnlyReadsArgumentPointees = IK_OnlyReadsMemory; 01392 const int OnlyReadsMemory = IK_OnlyReadsMemory; 01393 const int OnlyAccessesArgumentPointees = IK_WritesMemory; 01394 const int UnknownModRefBehavior = IK_WritesMemory; 01395 #define GET_INTRINSIC_MODREF_BEHAVIOR 01396 #define ModRefBehavior IntrinsicKind 01397 #include "llvm/IR/Intrinsics.gen" 01398 #undef ModRefBehavior 01399 #undef GET_INTRINSIC_MODREF_BEHAVIOR 01400 } 01401 01402 /// \brief Handle vector store-like intrinsics. 01403 /// 01404 /// Instrument intrinsics that look like a simple SIMD store: writes memory, 01405 /// has 1 pointer argument and 1 vector argument, returns void. 01406 bool handleVectorStoreIntrinsic(IntrinsicInst &I) { 01407 IRBuilder<> IRB(&I); 01408 Value* Addr = I.getArgOperand(0); 01409 Value *Shadow = getShadow(&I, 1); 01410 Value *ShadowPtr = getShadowPtr(Addr, Shadow->getType(), IRB); 01411 01412 // We don't know the pointer alignment (could be unaligned SSE store!). 01413 // Have to assume to worst case. 01414 IRB.CreateAlignedStore(Shadow, ShadowPtr, 1); 01415 01416 if (ClCheckAccessAddress) 01417 insertCheck(Addr, &I); 01418 01419 // FIXME: use ClStoreCleanOrigin 01420 // FIXME: factor out common code from materializeStores 01421 if (MS.TrackOrigins) 01422 IRB.CreateStore(getOrigin(&I, 1), getOriginPtr(Addr, IRB)); 01423 return true; 01424 } 01425 01426 /// \brief Handle vector load-like intrinsics. 01427 /// 01428 /// Instrument intrinsics that look like a simple SIMD load: reads memory, 01429 /// has 1 pointer argument, returns a vector. 01430 bool handleVectorLoadIntrinsic(IntrinsicInst &I) { 01431 IRBuilder<> IRB(&I); 01432 Value *Addr = I.getArgOperand(0); 01433 01434 Type *ShadowTy = getShadowTy(&I); 01435 if (LoadShadow) { 01436 Value *ShadowPtr = getShadowPtr(Addr, ShadowTy, IRB); 01437 // We don't know the pointer alignment (could be unaligned SSE load!). 01438 // Have to assume to worst case. 01439 setShadow(&I, IRB.CreateAlignedLoad(ShadowPtr, 1, "_msld")); 01440 } else { 01441 setShadow(&I, getCleanShadow(&I)); 01442 } 01443 01444 01445 if (ClCheckAccessAddress) 01446 insertCheck(Addr, &I); 01447 01448 if (MS.TrackOrigins) { 01449 if (LoadShadow) 01450 setOrigin(&I, IRB.CreateLoad(getOriginPtr(Addr, IRB))); 01451 else 01452 setOrigin(&I, getCleanOrigin()); 01453 } 01454 return true; 01455 } 01456 01457 /// \brief Handle (SIMD arithmetic)-like intrinsics. 01458 /// 01459 /// Instrument intrinsics with any number of arguments of the same type, 01460 /// equal to the return type. The type should be simple (no aggregates or 01461 /// pointers; vectors are fine). 01462 /// Caller guarantees that this intrinsic does not access memory. 01463 bool maybeHandleSimpleNomemIntrinsic(IntrinsicInst &I) { 01464 Type *RetTy = I.getType(); 01465 if (!(RetTy->isIntOrIntVectorTy() || 01466 RetTy->isFPOrFPVectorTy() || 01467 RetTy->isX86_MMXTy())) 01468 return false; 01469 01470 unsigned NumArgOperands = I.getNumArgOperands(); 01471 01472 for (unsigned i = 0; i < NumArgOperands; ++i) { 01473 Type *Ty = I.getArgOperand(i)->getType(); 01474 if (Ty != RetTy) 01475 return false; 01476 } 01477 01478 IRBuilder<> IRB(&I); 01479 ShadowAndOriginCombiner SC(this, IRB); 01480 for (unsigned i = 0; i < NumArgOperands; ++i) 01481 SC.Add(I.getArgOperand(i)); 01482 SC.Done(&I); 01483 01484 return true; 01485 } 01486 01487 /// \brief Heuristically instrument unknown intrinsics. 01488 /// 01489 /// The main purpose of this code is to do something reasonable with all 01490 /// random intrinsics we might encounter, most importantly - SIMD intrinsics. 01491 /// We recognize several classes of intrinsics by their argument types and 01492 /// ModRefBehaviour and apply special intrumentation when we are reasonably 01493 /// sure that we know what the intrinsic does. 01494 /// 01495 /// We special-case intrinsics where this approach fails. See llvm.bswap 01496 /// handling as an example of that. 01497 bool handleUnknownIntrinsic(IntrinsicInst &I) { 01498 unsigned NumArgOperands = I.getNumArgOperands(); 01499 if (NumArgOperands == 0) 01500 return false; 01501 01502 Intrinsic::ID iid = I.getIntrinsicID(); 01503 IntrinsicKind IK = getIntrinsicKind(iid); 01504 bool OnlyReadsMemory = IK == IK_OnlyReadsMemory; 01505 bool WritesMemory = IK == IK_WritesMemory; 01506 assert(!(OnlyReadsMemory && WritesMemory)); 01507 01508 if (NumArgOperands == 2 && 01509 I.getArgOperand(0)->getType()->isPointerTy() && 01510 I.getArgOperand(1)->getType()->isVectorTy() && 01511 I.getType()->isVoidTy() && 01512 WritesMemory) { 01513 // This looks like a vector store. 01514 return handleVectorStoreIntrinsic(I); 01515 } 01516 01517 if (NumArgOperands == 1 && 01518 I.getArgOperand(0)->getType()->isPointerTy() && 01519 I.getType()->isVectorTy() && 01520 OnlyReadsMemory) { 01521 // This looks like a vector load. 01522 return handleVectorLoadIntrinsic(I); 01523 } 01524 01525 if (!OnlyReadsMemory && !WritesMemory) 01526 if (maybeHandleSimpleNomemIntrinsic(I)) 01527 return true; 01528 01529 // FIXME: detect and handle SSE maskstore/maskload 01530 return false; 01531 } 01532 01533 void handleBswap(IntrinsicInst &I) { 01534 IRBuilder<> IRB(&I); 01535 Value *Op = I.getArgOperand(0); 01536 Type *OpType = Op->getType(); 01537 Function *BswapFunc = Intrinsic::getDeclaration( 01538 F.getParent(), Intrinsic::bswap, ArrayRef<Type*>(&OpType, 1)); 01539 setShadow(&I, IRB.CreateCall(BswapFunc, getShadow(Op))); 01540 setOrigin(&I, getOrigin(Op)); 01541 } 01542 01543 void visitIntrinsicInst(IntrinsicInst &I) { 01544 switch (I.getIntrinsicID()) { 01545 case llvm::Intrinsic::bswap: 01546 handleBswap(I); 01547 break; 01548 default: 01549 if (!handleUnknownIntrinsic(I)) 01550 visitInstruction(I); 01551 break; 01552 } 01553 } 01554 01555 void visitCallSite(CallSite CS) { 01556 Instruction &I = *CS.getInstruction(); 01557 assert((CS.isCall() || CS.isInvoke()) && "Unknown type of CallSite"); 01558 if (CS.isCall()) { 01559 CallInst *Call = cast<CallInst>(&I); 01560 01561 // For inline asm, do the usual thing: check argument shadow and mark all 01562 // outputs as clean. Note that any side effects of the inline asm that are 01563 // not immediately visible in its constraints are not handled. 01564 if (Call->isInlineAsm()) { 01565 visitInstruction(I); 01566 return; 01567 } 01568 01569 // Allow only tail calls with the same types, otherwise 01570 // we may have a false positive: shadow for a non-void RetVal 01571 // will get propagated to a void RetVal. 01572 if (Call->isTailCall() && Call->getType() != Call->getParent()->getType()) 01573 Call->setTailCall(false); 01574 01575 assert(!isa<IntrinsicInst>(&I) && "intrinsics are handled elsewhere"); 01576 01577 // We are going to insert code that relies on the fact that the callee 01578 // will become a non-readonly function after it is instrumented by us. To 01579 // prevent this code from being optimized out, mark that function 01580 // non-readonly in advance. 01581 if (Function *Func = Call->getCalledFunction()) { 01582 // Clear out readonly/readnone attributes. 01583 AttrBuilder B; 01584 B.addAttribute(Attribute::ReadOnly) 01585 .addAttribute(Attribute::ReadNone); 01586 Func->removeAttributes(AttributeSet::FunctionIndex, 01587 AttributeSet::get(Func->getContext(), 01588 AttributeSet::FunctionIndex, 01589 B)); 01590 } 01591 } 01592 IRBuilder<> IRB(&I); 01593 unsigned ArgOffset = 0; 01594 DEBUG(dbgs() << " CallSite: " << I << "\n"); 01595 for (CallSite::arg_iterator ArgIt = CS.arg_begin(), End = CS.arg_end(); 01596 ArgIt != End; ++ArgIt) { 01597 Value *A = *ArgIt; 01598 unsigned i = ArgIt - CS.arg_begin(); 01599 if (!A->getType()->isSized()) { 01600 DEBUG(dbgs() << "Arg " << i << " is not sized: " << I << "\n"); 01601 continue; 01602 } 01603 unsigned Size = 0; 01604 Value *Store = 0; 01605 // Compute the Shadow for arg even if it is ByVal, because 01606 // in that case getShadow() will copy the actual arg shadow to 01607 // __msan_param_tls. 01608 Value *ArgShadow = getShadow(A); 01609 Value *ArgShadowBase = getShadowPtrForArgument(A, IRB, ArgOffset); 01610 DEBUG(dbgs() << " Arg#" << i << ": " << *A << 01611 " Shadow: " << *ArgShadow << "\n"); 01612 if (CS.paramHasAttr(i + 1, Attribute::ByVal)) { 01613 assert(A->getType()->isPointerTy() && 01614 "ByVal argument is not a pointer!"); 01615 Size = MS.TD->getTypeAllocSize(A->getType()->getPointerElementType()); 01616 unsigned Alignment = CS.getParamAlignment(i + 1); 01617 Store = IRB.CreateMemCpy(ArgShadowBase, 01618 getShadowPtr(A, Type::getInt8Ty(*MS.C), IRB), 01619 Size, Alignment); 01620 } else { 01621 Size = MS.TD->getTypeAllocSize(A->getType()); 01622 Store = IRB.CreateAlignedStore(ArgShadow, ArgShadowBase, 01623 kShadowTLSAlignment); 01624 } 01625 if (MS.TrackOrigins) 01626 IRB.CreateStore(getOrigin(A), 01627 getOriginPtrForArgument(A, IRB, ArgOffset)); 01628 (void)Store; 01629 assert(Size != 0 && Store != 0); 01630 DEBUG(dbgs() << " Param:" << *Store << "\n"); 01631 ArgOffset += DataLayout::RoundUpAlignment(Size, 8); 01632 } 01633 DEBUG(dbgs() << " done with call args\n"); 01634 01635 FunctionType *FT = 01636 cast<FunctionType>(CS.getCalledValue()->getType()-> getContainedType(0)); 01637 if (FT->isVarArg()) { 01638 VAHelper->visitCallSite(CS, IRB); 01639 } 01640 01641 // Now, get the shadow for the RetVal. 01642 if (!I.getType()->isSized()) return; 01643 IRBuilder<> IRBBefore(&I); 01644 // Untill we have full dynamic coverage, make sure the retval shadow is 0. 01645 Value *Base = getShadowPtrForRetval(&I, IRBBefore); 01646 IRBBefore.CreateAlignedStore(getCleanShadow(&I), Base, kShadowTLSAlignment); 01647 Instruction *NextInsn = 0; 01648 if (CS.isCall()) { 01649 NextInsn = I.getNextNode(); 01650 } else { 01651 BasicBlock *NormalDest = cast<InvokeInst>(&I)->getNormalDest(); 01652 if (!NormalDest->getSinglePredecessor()) { 01653 // FIXME: this case is tricky, so we are just conservative here. 01654 // Perhaps we need to split the edge between this BB and NormalDest, 01655 // but a naive attempt to use SplitEdge leads to a crash. 01656 setShadow(&I, getCleanShadow(&I)); 01657 setOrigin(&I, getCleanOrigin()); 01658 return; 01659 } 01660 NextInsn = NormalDest->getFirstInsertionPt(); 01661 assert(NextInsn && 01662 "Could not find insertion point for retval shadow load"); 01663 } 01664 IRBuilder<> IRBAfter(NextInsn); 01665 Value *RetvalShadow = 01666 IRBAfter.CreateAlignedLoad(getShadowPtrForRetval(&I, IRBAfter), 01667 kShadowTLSAlignment, "_msret"); 01668 setShadow(&I, RetvalShadow); 01669 if (MS.TrackOrigins) 01670 setOrigin(&I, IRBAfter.CreateLoad(getOriginPtrForRetval(IRBAfter))); 01671 } 01672 01673 void visitReturnInst(ReturnInst &I) { 01674 IRBuilder<> IRB(&I); 01675 if (Value *RetVal = I.getReturnValue()) { 01676 // Set the shadow for the RetVal. 01677 Value *Shadow = getShadow(RetVal); 01678 Value *ShadowPtr = getShadowPtrForRetval(RetVal, IRB); 01679 DEBUG(dbgs() << "Return: " << *Shadow << "\n" << *ShadowPtr << "\n"); 01680 IRB.CreateAlignedStore(Shadow, ShadowPtr, kShadowTLSAlignment); 01681 if (MS.TrackOrigins) 01682 IRB.CreateStore(getOrigin(RetVal), getOriginPtrForRetval(IRB)); 01683 } 01684 } 01685 01686 void visitPHINode(PHINode &I) { 01687 IRBuilder<> IRB(&I); 01688 ShadowPHINodes.push_back(&I); 01689 setShadow(&I, IRB.CreatePHI(getShadowTy(&I), I.getNumIncomingValues(), 01690 "_msphi_s")); 01691 if (MS.TrackOrigins) 01692 setOrigin(&I, IRB.CreatePHI(MS.OriginTy, I.getNumIncomingValues(), 01693 "_msphi_o")); 01694 } 01695 01696 void visitAllocaInst(AllocaInst &I) { 01697 setShadow(&I, getCleanShadow(&I)); 01698 if (!ClPoisonStack) return; 01699 IRBuilder<> IRB(I.getNextNode()); 01700 uint64_t Size = MS.TD->getTypeAllocSize(I.getAllocatedType()); 01701 if (ClPoisonStackWithCall) { 01702 IRB.CreateCall2(MS.MsanPoisonStackFn, 01703 IRB.CreatePointerCast(&I, IRB.getInt8PtrTy()), 01704 ConstantInt::get(MS.IntptrTy, Size)); 01705 } else { 01706 Value *ShadowBase = getShadowPtr(&I, Type::getInt8PtrTy(*MS.C), IRB); 01707 IRB.CreateMemSet(ShadowBase, IRB.getInt8(ClPoisonStackPattern), 01708 Size, I.getAlignment()); 01709 } 01710 01711 if (MS.TrackOrigins) { 01712 setOrigin(&I, getCleanOrigin()); 01713 SmallString<2048> StackDescriptionStorage; 01714 raw_svector_ostream StackDescription(StackDescriptionStorage); 01715 // We create a string with a description of the stack allocation and 01716 // pass it into __msan_set_alloca_origin. 01717 // It will be printed by the run-time if stack-originated UMR is found. 01718 // The first 4 bytes of the string are set to '----' and will be replaced 01719 // by __msan_va_arg_overflow_size_tls at the first call. 01720 StackDescription << "----" << I.getName() << "@" << F.getName(); 01721 Value *Descr = 01722 createPrivateNonConstGlobalForString(*F.getParent(), 01723 StackDescription.str()); 01724 IRB.CreateCall3(MS.MsanSetAllocaOriginFn, 01725 IRB.CreatePointerCast(&I, IRB.getInt8PtrTy()), 01726 ConstantInt::get(MS.IntptrTy, Size), 01727 IRB.CreatePointerCast(Descr, IRB.getInt8PtrTy())); 01728 } 01729 } 01730 01731 void visitSelectInst(SelectInst& I) { 01732 IRBuilder<> IRB(&I); 01733 setShadow(&I, IRB.CreateSelect(I.getCondition(), 01734 getShadow(I.getTrueValue()), getShadow(I.getFalseValue()), 01735 "_msprop")); 01736 if (MS.TrackOrigins) { 01737 // Origins are always i32, so any vector conditions must be flattened. 01738 // FIXME: consider tracking vector origins for app vectors? 01739 Value *Cond = I.getCondition(); 01740 if (Cond->getType()->isVectorTy()) { 01741 Value *ConvertedShadow = convertToShadowTyNoVec(Cond, IRB); 01742 Cond = IRB.CreateICmpNE(ConvertedShadow, 01743 getCleanShadow(ConvertedShadow), "_mso_select"); 01744 } 01745 setOrigin(&I, IRB.CreateSelect(Cond, 01746 getOrigin(I.getTrueValue()), getOrigin(I.getFalseValue()))); 01747 } 01748 } 01749 01750 void visitLandingPadInst(LandingPadInst &I) { 01751 // Do nothing. 01752 // See http://code.google.com/p/memory-sanitizer/issues/detail?id=1 01753 setShadow(&I, getCleanShadow(&I)); 01754 setOrigin(&I, getCleanOrigin()); 01755 } 01756 01757 void visitGetElementPtrInst(GetElementPtrInst &I) { 01758 handleShadowOr(I); 01759 } 01760 01761 void visitExtractValueInst(ExtractValueInst &I) { 01762 IRBuilder<> IRB(&I); 01763 Value *Agg = I.getAggregateOperand(); 01764 DEBUG(dbgs() << "ExtractValue: " << I << "\n"); 01765 Value *AggShadow = getShadow(Agg); 01766 DEBUG(dbgs() << " AggShadow: " << *AggShadow << "\n"); 01767 Value *ResShadow = IRB.CreateExtractValue(AggShadow, I.getIndices()); 01768 DEBUG(dbgs() << " ResShadow: " << *ResShadow << "\n"); 01769 setShadow(&I, ResShadow); 01770 setOrigin(&I, getCleanOrigin()); 01771 } 01772 01773 void visitInsertValueInst(InsertValueInst &I) { 01774 IRBuilder<> IRB(&I); 01775 DEBUG(dbgs() << "InsertValue: " << I << "\n"); 01776 Value *AggShadow = getShadow(I.getAggregateOperand()); 01777 Value *InsShadow = getShadow(I.getInsertedValueOperand()); 01778 DEBUG(dbgs() << " AggShadow: " << *AggShadow << "\n"); 01779 DEBUG(dbgs() << " InsShadow: " << *InsShadow << "\n"); 01780 Value *Res = IRB.CreateInsertValue(AggShadow, InsShadow, I.getIndices()); 01781 DEBUG(dbgs() << " Res: " << *Res << "\n"); 01782 setShadow(&I, Res); 01783 setOrigin(&I, getCleanOrigin()); 01784 } 01785 01786 void dumpInst(Instruction &I) { 01787 if (CallInst *CI = dyn_cast<CallInst>(&I)) { 01788 errs() << "ZZZ call " << CI->getCalledFunction()->getName() << "\n"; 01789 } else { 01790 errs() << "ZZZ " << I.getOpcodeName() << "\n"; 01791 } 01792 errs() << "QQQ " << I << "\n"; 01793 } 01794 01795 void visitResumeInst(ResumeInst &I) { 01796 DEBUG(dbgs() << "Resume: " << I << "\n"); 01797 // Nothing to do here. 01798 } 01799 01800 void visitInstruction(Instruction &I) { 01801 // Everything else: stop propagating and check for poisoned shadow. 01802 if (ClDumpStrictInstructions) 01803 dumpInst(I); 01804 DEBUG(dbgs() << "DEFAULT: " << I << "\n"); 01805 for (size_t i = 0, n = I.getNumOperands(); i < n; i++) 01806 insertCheck(I.getOperand(i), &I); 01807 setShadow(&I, getCleanShadow(&I)); 01808 setOrigin(&I, getCleanOrigin()); 01809 } 01810 }; 01811 01812 /// \brief AMD64-specific implementation of VarArgHelper. 01813 struct VarArgAMD64Helper : public VarArgHelper { 01814 // An unfortunate workaround for asymmetric lowering of va_arg stuff. 01815 // See a comment in visitCallSite for more details. 01816 static const unsigned AMD64GpEndOffset = 48; // AMD64 ABI Draft 0.99.6 p3.5.7 01817 static const unsigned AMD64FpEndOffset = 176; 01818 01819 Function &F; 01820 MemorySanitizer &MS; 01821 MemorySanitizerVisitor &MSV; 01822 Value *VAArgTLSCopy; 01823 Value *VAArgOverflowSize; 01824 01825 SmallVector<CallInst*, 16> VAStartInstrumentationList; 01826 01827 VarArgAMD64Helper(Function &F, MemorySanitizer &MS, 01828 MemorySanitizerVisitor &MSV) 01829 : F(F), MS(MS), MSV(MSV), VAArgTLSCopy(0), VAArgOverflowSize(0) { } 01830 01831 enum ArgKind { AK_GeneralPurpose, AK_FloatingPoint, AK_Memory }; 01832 01833 ArgKind classifyArgument(Value* arg) { 01834 // A very rough approximation of X86_64 argument classification rules. 01835 Type *T = arg->getType(); 01836 if (T->isFPOrFPVectorTy() || T->isX86_MMXTy()) 01837 return AK_FloatingPoint; 01838 if (T->isIntegerTy() && T->getPrimitiveSizeInBits() <= 64) 01839 return AK_GeneralPurpose; 01840 if (T->isPointerTy()) 01841 return AK_GeneralPurpose; 01842 return AK_Memory; 01843 } 01844 01845 // For VarArg functions, store the argument shadow in an ABI-specific format 01846 // that corresponds to va_list layout. 01847 // We do this because Clang lowers va_arg in the frontend, and this pass 01848 // only sees the low level code that deals with va_list internals. 01849 // A much easier alternative (provided that Clang emits va_arg instructions) 01850 // would have been to associate each live instance of va_list with a copy of 01851 // MSanParamTLS, and extract shadow on va_arg() call in the argument list 01852 // order. 01853 void visitCallSite(CallSite &CS, IRBuilder<> &IRB) { 01854 unsigned GpOffset = 0; 01855 unsigned FpOffset = AMD64GpEndOffset; 01856 unsigned OverflowOffset = AMD64FpEndOffset; 01857 for (CallSite::arg_iterator ArgIt = CS.arg_begin(), End = CS.arg_end(); 01858 ArgIt != End; ++ArgIt) { 01859 Value *A = *ArgIt; 01860 ArgKind AK = classifyArgument(A); 01861 if (AK == AK_GeneralPurpose && GpOffset >= AMD64GpEndOffset) 01862 AK = AK_Memory; 01863 if (AK == AK_FloatingPoint && FpOffset >= AMD64FpEndOffset) 01864 AK = AK_Memory; 01865 Value *Base; 01866 switch (AK) { 01867 case AK_GeneralPurpose: 01868 Base = getShadowPtrForVAArgument(A, IRB, GpOffset); 01869 GpOffset += 8; 01870 break; 01871 case AK_FloatingPoint: 01872 Base = getShadowPtrForVAArgument(A, IRB, FpOffset); 01873 FpOffset += 16; 01874 break; 01875 case AK_Memory: 01876 uint64_t ArgSize = MS.TD->getTypeAllocSize(A->getType()); 01877 Base = getShadowPtrForVAArgument(A, IRB, OverflowOffset); 01878 OverflowOffset += DataLayout::RoundUpAlignment(ArgSize, 8); 01879 } 01880 IRB.CreateAlignedStore(MSV.getShadow(A), Base, kShadowTLSAlignment); 01881 } 01882 Constant *OverflowSize = 01883 ConstantInt::get(IRB.getInt64Ty(), OverflowOffset - AMD64FpEndOffset); 01884 IRB.CreateStore(OverflowSize, MS.VAArgOverflowSizeTLS); 01885 } 01886 01887 /// \brief Compute the shadow address for a given va_arg. 01888 Value *getShadowPtrForVAArgument(Value *A, IRBuilder<> &IRB, 01889 int ArgOffset) { 01890 Value *Base = IRB.CreatePointerCast(MS.VAArgTLS, MS.IntptrTy); 01891 Base = IRB.CreateAdd(Base, ConstantInt::get(MS.IntptrTy, ArgOffset)); 01892 return IRB.CreateIntToPtr(Base, PointerType::get(MSV.getShadowTy(A), 0), 01893 "_msarg"); 01894 } 01895 01896 void visitVAStartInst(VAStartInst &I) { 01897 IRBuilder<> IRB(&I); 01898 VAStartInstrumentationList.push_back(&I); 01899 Value *VAListTag = I.getArgOperand(0); 01900 Value *ShadowPtr = MSV.getShadowPtr(VAListTag, IRB.getInt8Ty(), IRB); 01901 01902 // Unpoison the whole __va_list_tag. 01903 // FIXME: magic ABI constants. 01904 IRB.CreateMemSet(ShadowPtr, Constant::getNullValue(IRB.getInt8Ty()), 01905 /* size */24, /* alignment */8, false); 01906 } 01907 01908 void visitVACopyInst(VACopyInst &I) { 01909 IRBuilder<> IRB(&I); 01910 Value *VAListTag = I.getArgOperand(0); 01911 Value *ShadowPtr = MSV.getShadowPtr(VAListTag, IRB.getInt8Ty(), IRB); 01912 01913 // Unpoison the whole __va_list_tag. 01914 // FIXME: magic ABI constants. 01915 IRB.CreateMemSet(ShadowPtr, Constant::getNullValue(IRB.getInt8Ty()), 01916 /* size */24, /* alignment */8, false); 01917 } 01918 01919 void finalizeInstrumentation() { 01920 assert(!VAArgOverflowSize && !VAArgTLSCopy && 01921 "finalizeInstrumentation called twice"); 01922 if (!VAStartInstrumentationList.empty()) { 01923 // If there is a va_start in this function, make a backup copy of 01924 // va_arg_tls somewhere in the function entry block. 01925 IRBuilder<> IRB(F.getEntryBlock().getFirstNonPHI()); 01926 VAArgOverflowSize = IRB.CreateLoad(MS.VAArgOverflowSizeTLS); 01927 Value *CopySize = 01928 IRB.CreateAdd(ConstantInt::get(MS.IntptrTy, AMD64FpEndOffset), 01929 VAArgOverflowSize); 01930 VAArgTLSCopy = IRB.CreateAlloca(Type::getInt8Ty(*MS.C), CopySize); 01931 IRB.CreateMemCpy(VAArgTLSCopy, MS.VAArgTLS, CopySize, 8); 01932 } 01933 01934 // Instrument va_start. 01935 // Copy va_list shadow from the backup copy of the TLS contents. 01936 for (size_t i = 0, n = VAStartInstrumentationList.size(); i < n; i++) { 01937 CallInst *OrigInst = VAStartInstrumentationList[i]; 01938 IRBuilder<> IRB(OrigInst->getNextNode()); 01939 Value *VAListTag = OrigInst->getArgOperand(0); 01940 01941 Value *RegSaveAreaPtrPtr = 01942 IRB.CreateIntToPtr( 01943 IRB.CreateAdd(IRB.CreatePtrToInt(VAListTag, MS.IntptrTy), 01944 ConstantInt::get(MS.IntptrTy, 16)), 01945 Type::getInt64PtrTy(*MS.C)); 01946 Value *RegSaveAreaPtr = IRB.CreateLoad(RegSaveAreaPtrPtr); 01947 Value *RegSaveAreaShadowPtr = 01948 MSV.getShadowPtr(RegSaveAreaPtr, IRB.getInt8Ty(), IRB); 01949 IRB.CreateMemCpy(RegSaveAreaShadowPtr, VAArgTLSCopy, 01950 AMD64FpEndOffset, 16); 01951 01952 Value *OverflowArgAreaPtrPtr = 01953 IRB.CreateIntToPtr( 01954 IRB.CreateAdd(IRB.CreatePtrToInt(VAListTag, MS.IntptrTy), 01955 ConstantInt::get(MS.IntptrTy, 8)), 01956 Type::getInt64PtrTy(*MS.C)); 01957 Value *OverflowArgAreaPtr = IRB.CreateLoad(OverflowArgAreaPtrPtr); 01958 Value *OverflowArgAreaShadowPtr = 01959 MSV.getShadowPtr(OverflowArgAreaPtr, IRB.getInt8Ty(), IRB); 01960 Value *SrcPtr = 01961 getShadowPtrForVAArgument(VAArgTLSCopy, IRB, AMD64FpEndOffset); 01962 IRB.CreateMemCpy(OverflowArgAreaShadowPtr, SrcPtr, VAArgOverflowSize, 16); 01963 } 01964 } 01965 }; 01966 01967 /// \brief A no-op implementation of VarArgHelper. 01968 struct VarArgNoOpHelper : public VarArgHelper { 01969 VarArgNoOpHelper(Function &F, MemorySanitizer &MS, 01970 MemorySanitizerVisitor &MSV) {} 01971 01972 void visitCallSite(CallSite &CS, IRBuilder<> &IRB) {} 01973 01974 void visitVAStartInst(VAStartInst &I) {} 01975 01976 void visitVACopyInst(VACopyInst &I) {} 01977 01978 void finalizeInstrumentation() {} 01979 }; 01980 01981 VarArgHelper *CreateVarArgHelper(Function &Func, MemorySanitizer &Msan, 01982 MemorySanitizerVisitor &Visitor) { 01983 // VarArg handling is only implemented on AMD64. False positives are possible 01984 // on other platforms. 01985 llvm::Triple TargetTriple(Func.getParent()->getTargetTriple()); 01986 if (TargetTriple.getArch() == llvm::Triple::x86_64) 01987 return new VarArgAMD64Helper(Func, Msan, Visitor); 01988 else 01989 return new VarArgNoOpHelper(Func, Msan, Visitor); 01990 } 01991 01992 } // namespace 01993 01994 bool MemorySanitizer::runOnFunction(Function &F) { 01995 MemorySanitizerVisitor Visitor(F, *this); 01996 01997 // Clear out readonly/readnone attributes. 01998 AttrBuilder B; 01999 B.addAttribute(Attribute::ReadOnly) 02000 .addAttribute(Attribute::ReadNone); 02001 F.removeAttributes(AttributeSet::FunctionIndex, 02002 AttributeSet::get(F.getContext(), 02003 AttributeSet::FunctionIndex, B)); 02004 02005 return Visitor.runOnFunction(); 02006 }