1 //===- ThreadSafety.cpp ----------------------------------------*- C++ --*-===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // A intra-procedural analysis for thread safety (e.g. deadlocks and race 11 // conditions), based off of an annotation system. 12 // 13 // See http://clang.llvm.org/docs/LanguageExtensions.html#thread-safety-annotation-checking 14 // for more information. 15 // 16 //===----------------------------------------------------------------------===// 17 18 #include "clang/Analysis/Analyses/ThreadSafety.h" 19 #include "clang/AST/Attr.h" 20 #include "clang/AST/DeclCXX.h" 21 #include "clang/AST/ExprCXX.h" 22 #include "clang/AST/StmtCXX.h" 23 #include "clang/AST/StmtVisitor.h" 24 #include "clang/Analysis/Analyses/PostOrderCFGView.h" 25 #include "clang/Analysis/AnalysisContext.h" 26 #include "clang/Analysis/CFG.h" 27 #include "clang/Analysis/CFGStmtMap.h" 28 #include "clang/Basic/OperatorKinds.h" 29 #include "clang/Basic/SourceLocation.h" 30 #include "clang/Basic/SourceManager.h" 31 #include "llvm/ADT/BitVector.h" 32 #include "llvm/ADT/FoldingSet.h" 33 #include "llvm/ADT/ImmutableMap.h" 34 #include "llvm/ADT/PostOrderIterator.h" 35 #include "llvm/ADT/SmallVector.h" 36 #include "llvm/ADT/StringRef.h" 37 #include "llvm/Support/raw_ostream.h" 38 #include <algorithm> 39 #include <utility> 40 #include <vector> 41 42 using namespace clang; 43 using namespace thread_safety; 44 45 // Key method definition 46 ThreadSafetyHandler::~ThreadSafetyHandler() {} 47 48 namespace { 49 50 /// SExpr implements a simple expression language that is used to store, 51 /// compare, and pretty-print C++ expressions. Unlike a clang Expr, a SExpr 52 /// does not capture surface syntax, and it does not distinguish between 53 /// C++ concepts, like pointers and references, that have no real semantic 54 /// differences. This simplicity allows SExprs to be meaningfully compared, 55 /// e.g. 56 /// (x) = x 57 /// (*this).foo = this->foo 58 /// *&a = a 59 /// 60 /// Thread-safety analysis works by comparing lock expressions. Within the 61 /// body of a function, an expression such as "x->foo->bar.mu" will resolve to 62 /// a particular mutex object at run-time. Subsequent occurrences of the same 63 /// expression (where "same" means syntactic equality) will refer to the same 64 /// run-time object if three conditions hold: 65 /// (1) Local variables in the expression, such as "x" have not changed. 66 /// (2) Values on the heap that affect the expression have not changed. 67 /// (3) The expression involves only pure function calls. 68 /// 69 /// The current implementation assumes, but does not verify, that multiple uses 70 /// of the same lock expression satisfies these criteria. 71 class SExpr { 72 private: 73 enum ExprOp { 74 EOP_Nop, ///< No-op 75 EOP_Wildcard, ///< Matches anything. 76 EOP_Universal, ///< Universal lock. 77 EOP_This, ///< This keyword. 78 EOP_NVar, ///< Named variable. 79 EOP_LVar, ///< Local variable. 80 EOP_Dot, ///< Field access 81 EOP_Call, ///< Function call 82 EOP_MCall, ///< Method call 83 EOP_Index, ///< Array index 84 EOP_Unary, ///< Unary operation 85 EOP_Binary, ///< Binary operation 86 EOP_Unknown ///< Catchall for everything else 87 }; 88 89 90 class SExprNode { 91 private: 92 unsigned char Op; ///< Opcode of the root node 93 unsigned char Flags; ///< Additional opcode-specific data 94 unsigned short Sz; ///< Number of child nodes 95 const void* Data; ///< Additional opcode-specific data 96 97 public: 98 SExprNode(ExprOp O, unsigned F, const void* D) 99 : Op(static_cast<unsigned char>(O)), 100 Flags(static_cast<unsigned char>(F)), Sz(1), Data(D) 101 { } 102 103 unsigned size() const { return Sz; } 104 void setSize(unsigned S) { Sz = S; } 105 106 ExprOp kind() const { return static_cast<ExprOp>(Op); } 107 108 const NamedDecl* getNamedDecl() const { 109 assert(Op == EOP_NVar || Op == EOP_LVar || Op == EOP_Dot); 110 return reinterpret_cast<const NamedDecl*>(Data); 111 } 112 113 const NamedDecl* getFunctionDecl() const { 114 assert(Op == EOP_Call || Op == EOP_MCall); 115 return reinterpret_cast<const NamedDecl*>(Data); 116 } 117 118 bool isArrow() const { return Op == EOP_Dot && Flags == 1; } 119 void setArrow(bool A) { Flags = A ? 1 : 0; } 120 121 unsigned arity() const { 122 switch (Op) { 123 case EOP_Nop: return 0; 124 case EOP_Wildcard: return 0; 125 case EOP_Universal: return 0; 126 case EOP_NVar: return 0; 127 case EOP_LVar: return 0; 128 case EOP_This: return 0; 129 case EOP_Dot: return 1; 130 case EOP_Call: return Flags+1; // First arg is function. 131 case EOP_MCall: return Flags+1; // First arg is implicit obj. 132 case EOP_Index: return 2; 133 case EOP_Unary: return 1; 134 case EOP_Binary: return 2; 135 case EOP_Unknown: return Flags; 136 } 137 return 0; 138 } 139 140 bool operator==(const SExprNode& Other) const { 141 // Ignore flags and size -- they don't matter. 142 return (Op == Other.Op && 143 Data == Other.Data); 144 } 145 146 bool operator!=(const SExprNode& Other) const { 147 return !(*this == Other); 148 } 149 150 bool matches(const SExprNode& Other) const { 151 return (*this == Other) || 152 (Op == EOP_Wildcard) || 153 (Other.Op == EOP_Wildcard); 154 } 155 }; 156 157 158 /// \brief Encapsulates the lexical context of a function call. The lexical 159 /// context includes the arguments to the call, including the implicit object 160 /// argument. When an attribute containing a mutex expression is attached to 161 /// a method, the expression may refer to formal parameters of the method. 162 /// Actual arguments must be substituted for formal parameters to derive 163 /// the appropriate mutex expression in the lexical context where the function 164 /// is called. PrevCtx holds the context in which the arguments themselves 165 /// should be evaluated; multiple calling contexts can be chained together 166 /// by the lock_returned attribute. 167 struct CallingContext { 168 const NamedDecl* AttrDecl; // The decl to which the attribute is attached. 169 const Expr* SelfArg; // Implicit object argument -- e.g. 'this' 170 bool SelfArrow; // is Self referred to with -> or .? 171 unsigned NumArgs; // Number of funArgs 172 const Expr* const* FunArgs; // Function arguments 173 CallingContext* PrevCtx; // The previous context; or 0 if none. 174 175 CallingContext(const NamedDecl *D) 176 : AttrDecl(D), SelfArg(0), SelfArrow(false), NumArgs(0), FunArgs(0), 177 PrevCtx(0) {} 178 }; 179 180 typedef SmallVector<SExprNode, 4> NodeVector; 181 182 private: 183 // A SExpr is a list of SExprNodes in prefix order. The Size field allows 184 // the list to be traversed as a tree. 185 NodeVector NodeVec; 186 187 private: 188 unsigned make(ExprOp O, unsigned F = 0, const void *D = 0) { 189 NodeVec.push_back(SExprNode(O, F, D)); 190 return NodeVec.size() - 1; 191 } 192 193 unsigned makeNop() { 194 return make(EOP_Nop); 195 } 196 197 unsigned makeWildcard() { 198 return make(EOP_Wildcard); 199 } 200 201 unsigned makeUniversal() { 202 return make(EOP_Universal); 203 } 204 205 unsigned makeNamedVar(const NamedDecl *D) { 206 return make(EOP_NVar, 0, D); 207 } 208 209 unsigned makeLocalVar(const NamedDecl *D) { 210 return make(EOP_LVar, 0, D); 211 } 212 213 unsigned makeThis() { 214 return make(EOP_This); 215 } 216 217 unsigned makeDot(const NamedDecl *D, bool Arrow) { 218 return make(EOP_Dot, Arrow ? 1 : 0, D); 219 } 220 221 unsigned makeCall(unsigned NumArgs, const NamedDecl *D) { 222 return make(EOP_Call, NumArgs, D); 223 } 224 225 // Grab the very first declaration of virtual method D 226 const CXXMethodDecl* getFirstVirtualDecl(const CXXMethodDecl *D) { 227 while (true) { 228 D = D->getCanonicalDecl(); 229 CXXMethodDecl::method_iterator I = D->begin_overridden_methods(), 230 E = D->end_overridden_methods(); 231 if (I == E) 232 return D; // Method does not override anything 233 D = *I; // FIXME: this does not work with multiple inheritance. 234 } 235 return 0; 236 } 237 238 unsigned makeMCall(unsigned NumArgs, const CXXMethodDecl *D) { 239 return make(EOP_MCall, NumArgs, getFirstVirtualDecl(D)); 240 } 241 242 unsigned makeIndex() { 243 return make(EOP_Index); 244 } 245 246 unsigned makeUnary() { 247 return make(EOP_Unary); 248 } 249 250 unsigned makeBinary() { 251 return make(EOP_Binary); 252 } 253 254 unsigned makeUnknown(unsigned Arity) { 255 return make(EOP_Unknown, Arity); 256 } 257 258 inline bool isCalleeArrow(const Expr *E) { 259 const MemberExpr *ME = dyn_cast<MemberExpr>(E->IgnoreParenCasts()); 260 return ME ? ME->isArrow() : false; 261 } 262 263 /// Build an SExpr from the given C++ expression. 264 /// Recursive function that terminates on DeclRefExpr. 265 /// Note: this function merely creates a SExpr; it does not check to 266 /// ensure that the original expression is a valid mutex expression. 267 /// 268 /// NDeref returns the number of Derefence and AddressOf operations 269 /// preceding the Expr; this is used to decide whether to pretty-print 270 /// SExprs with . or ->. 271 unsigned buildSExpr(const Expr *Exp, CallingContext* CallCtx, 272 int* NDeref = 0) { 273 if (!Exp) 274 return 0; 275 276 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp)) { 277 const NamedDecl *ND = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl()); 278 const ParmVarDecl *PV = dyn_cast_or_null<ParmVarDecl>(ND); 279 if (PV) { 280 const FunctionDecl *FD = 281 cast<FunctionDecl>(PV->getDeclContext())->getCanonicalDecl(); 282 unsigned i = PV->getFunctionScopeIndex(); 283 284 if (CallCtx && CallCtx->FunArgs && 285 FD == CallCtx->AttrDecl->getCanonicalDecl()) { 286 // Substitute call arguments for references to function parameters 287 assert(i < CallCtx->NumArgs); 288 return buildSExpr(CallCtx->FunArgs[i], CallCtx->PrevCtx, NDeref); 289 } 290 // Map the param back to the param of the original function declaration. 291 makeNamedVar(FD->getParamDecl(i)); 292 return 1; 293 } 294 // Not a function parameter -- just store the reference. 295 makeNamedVar(ND); 296 return 1; 297 } else if (isa<CXXThisExpr>(Exp)) { 298 // Substitute parent for 'this' 299 if (CallCtx && CallCtx->SelfArg) { 300 if (!CallCtx->SelfArrow && NDeref) 301 // 'this' is a pointer, but self is not, so need to take address. 302 --(*NDeref); 303 return buildSExpr(CallCtx->SelfArg, CallCtx->PrevCtx, NDeref); 304 } 305 else { 306 makeThis(); 307 return 1; 308 } 309 } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(Exp)) { 310 const NamedDecl *ND = ME->getMemberDecl(); 311 int ImplicitDeref = ME->isArrow() ? 1 : 0; 312 unsigned Root = makeDot(ND, false); 313 unsigned Sz = buildSExpr(ME->getBase(), CallCtx, &ImplicitDeref); 314 NodeVec[Root].setArrow(ImplicitDeref > 0); 315 NodeVec[Root].setSize(Sz + 1); 316 return Sz + 1; 317 } else if (const CXXMemberCallExpr *CMCE = dyn_cast<CXXMemberCallExpr>(Exp)) { 318 // When calling a function with a lock_returned attribute, replace 319 // the function call with the expression in lock_returned. 320 const CXXMethodDecl *MD = CMCE->getMethodDecl()->getMostRecentDecl(); 321 if (LockReturnedAttr* At = MD->getAttr<LockReturnedAttr>()) { 322 CallingContext LRCallCtx(CMCE->getMethodDecl()); 323 LRCallCtx.SelfArg = CMCE->getImplicitObjectArgument(); 324 LRCallCtx.SelfArrow = isCalleeArrow(CMCE->getCallee()); 325 LRCallCtx.NumArgs = CMCE->getNumArgs(); 326 LRCallCtx.FunArgs = CMCE->getArgs(); 327 LRCallCtx.PrevCtx = CallCtx; 328 return buildSExpr(At->getArg(), &LRCallCtx); 329 } 330 // Hack to treat smart pointers and iterators as pointers; 331 // ignore any method named get(). 332 if (CMCE->getMethodDecl()->getNameAsString() == "get" && 333 CMCE->getNumArgs() == 0) { 334 if (NDeref && isCalleeArrow(CMCE->getCallee())) 335 ++(*NDeref); 336 return buildSExpr(CMCE->getImplicitObjectArgument(), CallCtx, NDeref); 337 } 338 unsigned NumCallArgs = CMCE->getNumArgs(); 339 unsigned Root = makeMCall(NumCallArgs, CMCE->getMethodDecl()); 340 unsigned Sz = buildSExpr(CMCE->getImplicitObjectArgument(), CallCtx); 341 const Expr* const* CallArgs = CMCE->getArgs(); 342 for (unsigned i = 0; i < NumCallArgs; ++i) { 343 Sz += buildSExpr(CallArgs[i], CallCtx); 344 } 345 NodeVec[Root].setSize(Sz + 1); 346 return Sz + 1; 347 } else if (const CallExpr *CE = dyn_cast<CallExpr>(Exp)) { 348 const FunctionDecl *FD = CE->getDirectCallee()->getMostRecentDecl(); 349 if (LockReturnedAttr* At = FD->getAttr<LockReturnedAttr>()) { 350 CallingContext LRCallCtx(CE->getDirectCallee()); 351 LRCallCtx.NumArgs = CE->getNumArgs(); 352 LRCallCtx.FunArgs = CE->getArgs(); 353 LRCallCtx.PrevCtx = CallCtx; 354 return buildSExpr(At->getArg(), &LRCallCtx); 355 } 356 // Treat smart pointers and iterators as pointers; 357 // ignore the * and -> operators. 358 if (const CXXOperatorCallExpr *OE = dyn_cast<CXXOperatorCallExpr>(CE)) { 359 OverloadedOperatorKind k = OE->getOperator(); 360 if (k == OO_Star) { 361 if (NDeref) ++(*NDeref); 362 return buildSExpr(OE->getArg(0), CallCtx, NDeref); 363 } 364 else if (k == OO_Arrow) { 365 return buildSExpr(OE->getArg(0), CallCtx, NDeref); 366 } 367 } 368 unsigned NumCallArgs = CE->getNumArgs(); 369 unsigned Root = makeCall(NumCallArgs, 0); 370 unsigned Sz = buildSExpr(CE->getCallee(), CallCtx); 371 const Expr* const* CallArgs = CE->getArgs(); 372 for (unsigned i = 0; i < NumCallArgs; ++i) { 373 Sz += buildSExpr(CallArgs[i], CallCtx); 374 } 375 NodeVec[Root].setSize(Sz+1); 376 return Sz+1; 377 } else if (const BinaryOperator *BOE = dyn_cast<BinaryOperator>(Exp)) { 378 unsigned Root = makeBinary(); 379 unsigned Sz = buildSExpr(BOE->getLHS(), CallCtx); 380 Sz += buildSExpr(BOE->getRHS(), CallCtx); 381 NodeVec[Root].setSize(Sz); 382 return Sz; 383 } else if (const UnaryOperator *UOE = dyn_cast<UnaryOperator>(Exp)) { 384 // Ignore & and * operators -- they're no-ops. 385 // However, we try to figure out whether the expression is a pointer, 386 // so we can use . and -> appropriately in error messages. 387 if (UOE->getOpcode() == UO_Deref) { 388 if (NDeref) ++(*NDeref); 389 return buildSExpr(UOE->getSubExpr(), CallCtx, NDeref); 390 } 391 if (UOE->getOpcode() == UO_AddrOf) { 392 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(UOE->getSubExpr())) { 393 if (DRE->getDecl()->isCXXInstanceMember()) { 394 // This is a pointer-to-member expression, e.g. &MyClass::mu_. 395 // We interpret this syntax specially, as a wildcard. 396 unsigned Root = makeDot(DRE->getDecl(), false); 397 makeWildcard(); 398 NodeVec[Root].setSize(2); 399 return 2; 400 } 401 } 402 if (NDeref) --(*NDeref); 403 return buildSExpr(UOE->getSubExpr(), CallCtx, NDeref); 404 } 405 unsigned Root = makeUnary(); 406 unsigned Sz = buildSExpr(UOE->getSubExpr(), CallCtx); 407 NodeVec[Root].setSize(Sz); 408 return Sz; 409 } else if (const ArraySubscriptExpr *ASE = 410 dyn_cast<ArraySubscriptExpr>(Exp)) { 411 unsigned Root = makeIndex(); 412 unsigned Sz = buildSExpr(ASE->getBase(), CallCtx); 413 Sz += buildSExpr(ASE->getIdx(), CallCtx); 414 NodeVec[Root].setSize(Sz); 415 return Sz; 416 } else if (const AbstractConditionalOperator *CE = 417 dyn_cast<AbstractConditionalOperator>(Exp)) { 418 unsigned Root = makeUnknown(3); 419 unsigned Sz = buildSExpr(CE->getCond(), CallCtx); 420 Sz += buildSExpr(CE->getTrueExpr(), CallCtx); 421 Sz += buildSExpr(CE->getFalseExpr(), CallCtx); 422 NodeVec[Root].setSize(Sz); 423 return Sz; 424 } else if (const ChooseExpr *CE = dyn_cast<ChooseExpr>(Exp)) { 425 unsigned Root = makeUnknown(3); 426 unsigned Sz = buildSExpr(CE->getCond(), CallCtx); 427 Sz += buildSExpr(CE->getLHS(), CallCtx); 428 Sz += buildSExpr(CE->getRHS(), CallCtx); 429 NodeVec[Root].setSize(Sz); 430 return Sz; 431 } else if (const CastExpr *CE = dyn_cast<CastExpr>(Exp)) { 432 return buildSExpr(CE->getSubExpr(), CallCtx, NDeref); 433 } else if (const ParenExpr *PE = dyn_cast<ParenExpr>(Exp)) { 434 return buildSExpr(PE->getSubExpr(), CallCtx, NDeref); 435 } else if (const ExprWithCleanups *EWC = dyn_cast<ExprWithCleanups>(Exp)) { 436 return buildSExpr(EWC->getSubExpr(), CallCtx, NDeref); 437 } else if (const CXXBindTemporaryExpr *E = dyn_cast<CXXBindTemporaryExpr>(Exp)) { 438 return buildSExpr(E->getSubExpr(), CallCtx, NDeref); 439 } else if (isa<CharacterLiteral>(Exp) || 440 isa<CXXNullPtrLiteralExpr>(Exp) || 441 isa<GNUNullExpr>(Exp) || 442 isa<CXXBoolLiteralExpr>(Exp) || 443 isa<FloatingLiteral>(Exp) || 444 isa<ImaginaryLiteral>(Exp) || 445 isa<IntegerLiteral>(Exp) || 446 isa<StringLiteral>(Exp) || 447 isa<ObjCStringLiteral>(Exp)) { 448 makeNop(); 449 return 1; // FIXME: Ignore literals for now 450 } else { 451 makeNop(); 452 return 1; // Ignore. FIXME: mark as invalid expression? 453 } 454 } 455 456 /// \brief Construct a SExpr from an expression. 457 /// \param MutexExp The original mutex expression within an attribute 458 /// \param DeclExp An expression involving the Decl on which the attribute 459 /// occurs. 460 /// \param D The declaration to which the lock/unlock attribute is attached. 461 void buildSExprFromExpr(const Expr *MutexExp, const Expr *DeclExp, 462 const NamedDecl *D, VarDecl *SelfDecl = 0) { 463 CallingContext CallCtx(D); 464 465 if (MutexExp) { 466 if (const StringLiteral* SLit = dyn_cast<StringLiteral>(MutexExp)) { 467 if (SLit->getString() == StringRef("*")) 468 // The "*" expr is a universal lock, which essentially turns off 469 // checks until it is removed from the lockset. 470 makeUniversal(); 471 else 472 // Ignore other string literals for now. 473 makeNop(); 474 return; 475 } 476 } 477 478 // If we are processing a raw attribute expression, with no substitutions. 479 if (DeclExp == 0) { 480 buildSExpr(MutexExp, 0); 481 return; 482 } 483 484 // Examine DeclExp to find SelfArg and FunArgs, which are used to substitute 485 // for formal parameters when we call buildMutexID later. 486 if (const MemberExpr *ME = dyn_cast<MemberExpr>(DeclExp)) { 487 CallCtx.SelfArg = ME->getBase(); 488 CallCtx.SelfArrow = ME->isArrow(); 489 } else if (const CXXMemberCallExpr *CE = 490 dyn_cast<CXXMemberCallExpr>(DeclExp)) { 491 CallCtx.SelfArg = CE->getImplicitObjectArgument(); 492 CallCtx.SelfArrow = isCalleeArrow(CE->getCallee()); 493 CallCtx.NumArgs = CE->getNumArgs(); 494 CallCtx.FunArgs = CE->getArgs(); 495 } else if (const CallExpr *CE = dyn_cast<CallExpr>(DeclExp)) { 496 CallCtx.NumArgs = CE->getNumArgs(); 497 CallCtx.FunArgs = CE->getArgs(); 498 } else if (const CXXConstructExpr *CE = 499 dyn_cast<CXXConstructExpr>(DeclExp)) { 500 CallCtx.SelfArg = 0; // Will be set below 501 CallCtx.NumArgs = CE->getNumArgs(); 502 CallCtx.FunArgs = CE->getArgs(); 503 } else if (D && isa<CXXDestructorDecl>(D)) { 504 // There's no such thing as a "destructor call" in the AST. 505 CallCtx.SelfArg = DeclExp; 506 } 507 508 // Hack to handle constructors, where self cannot be recovered from 509 // the expression. 510 if (SelfDecl && !CallCtx.SelfArg) { 511 DeclRefExpr SelfDRE(SelfDecl, false, SelfDecl->getType(), VK_LValue, 512 SelfDecl->getLocation()); 513 CallCtx.SelfArg = &SelfDRE; 514 515 // If the attribute has no arguments, then assume the argument is "this". 516 if (MutexExp == 0) 517 buildSExpr(CallCtx.SelfArg, 0); 518 else // For most attributes. 519 buildSExpr(MutexExp, &CallCtx); 520 return; 521 } 522 523 // If the attribute has no arguments, then assume the argument is "this". 524 if (MutexExp == 0) 525 buildSExpr(CallCtx.SelfArg, 0); 526 else // For most attributes. 527 buildSExpr(MutexExp, &CallCtx); 528 } 529 530 /// \brief Get index of next sibling of node i. 531 unsigned getNextSibling(unsigned i) const { 532 return i + NodeVec[i].size(); 533 } 534 535 public: 536 explicit SExpr(clang::Decl::EmptyShell e) { NodeVec.clear(); } 537 538 /// \param MutexExp The original mutex expression within an attribute 539 /// \param DeclExp An expression involving the Decl on which the attribute 540 /// occurs. 541 /// \param D The declaration to which the lock/unlock attribute is attached. 542 /// Caller must check isValid() after construction. 543 SExpr(const Expr* MutexExp, const Expr *DeclExp, const NamedDecl* D, 544 VarDecl *SelfDecl=0) { 545 buildSExprFromExpr(MutexExp, DeclExp, D, SelfDecl); 546 } 547 548 /// Return true if this is a valid decl sequence. 549 /// Caller must call this by hand after construction to handle errors. 550 bool isValid() const { 551 return !NodeVec.empty(); 552 } 553 554 bool shouldIgnore() const { 555 // Nop is a mutex that we have decided to deliberately ignore. 556 assert(NodeVec.size() > 0 && "Invalid Mutex"); 557 return NodeVec[0].kind() == EOP_Nop; 558 } 559 560 bool isUniversal() const { 561 assert(NodeVec.size() > 0 && "Invalid Mutex"); 562 return NodeVec[0].kind() == EOP_Universal; 563 } 564 565 /// Issue a warning about an invalid lock expression 566 static void warnInvalidLock(ThreadSafetyHandler &Handler, 567 const Expr *MutexExp, 568 const Expr *DeclExp, const NamedDecl* D) { 569 SourceLocation Loc; 570 if (DeclExp) 571 Loc = DeclExp->getExprLoc(); 572 573 // FIXME: add a note about the attribute location in MutexExp or D 574 if (Loc.isValid()) 575 Handler.handleInvalidLockExp(Loc); 576 } 577 578 bool operator==(const SExpr &other) const { 579 return NodeVec == other.NodeVec; 580 } 581 582 bool operator!=(const SExpr &other) const { 583 return !(*this == other); 584 } 585 586 bool matches(const SExpr &Other, unsigned i = 0, unsigned j = 0) const { 587 if (NodeVec[i].matches(Other.NodeVec[j])) { 588 unsigned ni = NodeVec[i].arity(); 589 unsigned nj = Other.NodeVec[j].arity(); 590 unsigned n = (ni < nj) ? ni : nj; 591 bool Result = true; 592 unsigned ci = i+1; // first child of i 593 unsigned cj = j+1; // first child of j 594 for (unsigned k = 0; k < n; 595 ++k, ci=getNextSibling(ci), cj = Other.getNextSibling(cj)) { 596 Result = Result && matches(Other, ci, cj); 597 } 598 return Result; 599 } 600 return false; 601 } 602 603 // A partial match between a.mu and b.mu returns true a and b have the same 604 // type (and thus mu refers to the same mutex declaration), regardless of 605 // whether a and b are different objects or not. 606 bool partiallyMatches(const SExpr &Other) const { 607 if (NodeVec[0].kind() == EOP_Dot) 608 return NodeVec[0].matches(Other.NodeVec[0]); 609 return false; 610 } 611 612 /// \brief Pretty print a lock expression for use in error messages. 613 std::string toString(unsigned i = 0) const { 614 assert(isValid()); 615 if (i >= NodeVec.size()) 616 return ""; 617 618 const SExprNode* N = &NodeVec[i]; 619 switch (N->kind()) { 620 case EOP_Nop: 621 return "_"; 622 case EOP_Wildcard: 623 return "(?)"; 624 case EOP_Universal: 625 return "*"; 626 case EOP_This: 627 return "this"; 628 case EOP_NVar: 629 case EOP_LVar: { 630 return N->getNamedDecl()->getNameAsString(); 631 } 632 case EOP_Dot: { 633 if (NodeVec[i+1].kind() == EOP_Wildcard) { 634 std::string S = "&"; 635 S += N->getNamedDecl()->getQualifiedNameAsString(); 636 return S; 637 } 638 std::string FieldName = N->getNamedDecl()->getNameAsString(); 639 if (NodeVec[i+1].kind() == EOP_This) 640 return FieldName; 641 642 std::string S = toString(i+1); 643 if (N->isArrow()) 644 return S + "->" + FieldName; 645 else 646 return S + "." + FieldName; 647 } 648 case EOP_Call: { 649 std::string S = toString(i+1) + "("; 650 unsigned NumArgs = N->arity()-1; 651 unsigned ci = getNextSibling(i+1); 652 for (unsigned k=0; k<NumArgs; ++k, ci = getNextSibling(ci)) { 653 S += toString(ci); 654 if (k+1 < NumArgs) S += ","; 655 } 656 S += ")"; 657 return S; 658 } 659 case EOP_MCall: { 660 std::string S = ""; 661 if (NodeVec[i+1].kind() != EOP_This) 662 S = toString(i+1) + "."; 663 if (const NamedDecl *D = N->getFunctionDecl()) 664 S += D->getNameAsString() + "("; 665 else 666 S += "#("; 667 unsigned NumArgs = N->arity()-1; 668 unsigned ci = getNextSibling(i+1); 669 for (unsigned k=0; k<NumArgs; ++k, ci = getNextSibling(ci)) { 670 S += toString(ci); 671 if (k+1 < NumArgs) S += ","; 672 } 673 S += ")"; 674 return S; 675 } 676 case EOP_Index: { 677 std::string S1 = toString(i+1); 678 std::string S2 = toString(i+1 + NodeVec[i+1].size()); 679 return S1 + "[" + S2 + "]"; 680 } 681 case EOP_Unary: { 682 std::string S = toString(i+1); 683 return "#" + S; 684 } 685 case EOP_Binary: { 686 std::string S1 = toString(i+1); 687 std::string S2 = toString(i+1 + NodeVec[i+1].size()); 688 return "(" + S1 + "#" + S2 + ")"; 689 } 690 case EOP_Unknown: { 691 unsigned NumChildren = N->arity(); 692 if (NumChildren == 0) 693 return "(...)"; 694 std::string S = "("; 695 unsigned ci = i+1; 696 for (unsigned j = 0; j < NumChildren; ++j, ci = getNextSibling(ci)) { 697 S += toString(ci); 698 if (j+1 < NumChildren) S += "#"; 699 } 700 S += ")"; 701 return S; 702 } 703 } 704 return ""; 705 } 706 }; 707 708 /// \brief A short list of SExprs 709 class MutexIDList : public SmallVector<SExpr, 3> { 710 public: 711 /// \brief Push M onto list, but discard duplicates. 712 void push_back_nodup(const SExpr& M) { 713 if (end() == std::find(begin(), end(), M)) 714 push_back(M); 715 } 716 }; 717 718 /// \brief This is a helper class that stores info about the most recent 719 /// accquire of a Lock. 720 /// 721 /// The main body of the analysis maps MutexIDs to LockDatas. 722 struct LockData { 723 SourceLocation AcquireLoc; 724 725 /// \brief LKind stores whether a lock is held shared or exclusively. 726 /// Note that this analysis does not currently support either re-entrant 727 /// locking or lock "upgrading" and "downgrading" between exclusive and 728 /// shared. 729 /// 730 /// FIXME: add support for re-entrant locking and lock up/downgrading 731 LockKind LKind; 732 bool Asserted; // for asserted locks 733 bool Managed; // for ScopedLockable objects 734 SExpr UnderlyingMutex; // for ScopedLockable objects 735 736 LockData(SourceLocation AcquireLoc, LockKind LKind, bool M=false, 737 bool Asrt=false) 738 : AcquireLoc(AcquireLoc), LKind(LKind), Asserted(Asrt), Managed(M), 739 UnderlyingMutex(Decl::EmptyShell()) 740 {} 741 742 LockData(SourceLocation AcquireLoc, LockKind LKind, const SExpr &Mu) 743 : AcquireLoc(AcquireLoc), LKind(LKind), Asserted(false), Managed(false), 744 UnderlyingMutex(Mu) 745 {} 746 747 bool operator==(const LockData &other) const { 748 return AcquireLoc == other.AcquireLoc && LKind == other.LKind; 749 } 750 751 bool operator!=(const LockData &other) const { 752 return !(*this == other); 753 } 754 755 void Profile(llvm::FoldingSetNodeID &ID) const { 756 ID.AddInteger(AcquireLoc.getRawEncoding()); 757 ID.AddInteger(LKind); 758 } 759 760 bool isAtLeast(LockKind LK) { 761 return (LK == LK_Shared) || (LKind == LK_Exclusive); 762 } 763 }; 764 765 766 /// \brief A FactEntry stores a single fact that is known at a particular point 767 /// in the program execution. Currently, this is information regarding a lock 768 /// that is held at that point. 769 struct FactEntry { 770 SExpr MutID; 771 LockData LDat; 772 773 FactEntry(const SExpr& M, const LockData& L) 774 : MutID(M), LDat(L) 775 { } 776 }; 777 778 779 typedef unsigned short FactID; 780 781 /// \brief FactManager manages the memory for all facts that are created during 782 /// the analysis of a single routine. 783 class FactManager { 784 private: 785 std::vector<FactEntry> Facts; 786 787 public: 788 FactID newLock(const SExpr& M, const LockData& L) { 789 Facts.push_back(FactEntry(M,L)); 790 return static_cast<unsigned short>(Facts.size() - 1); 791 } 792 793 const FactEntry& operator[](FactID F) const { return Facts[F]; } 794 FactEntry& operator[](FactID F) { return Facts[F]; } 795 }; 796 797 798 /// \brief A FactSet is the set of facts that are known to be true at a 799 /// particular program point. FactSets must be small, because they are 800 /// frequently copied, and are thus implemented as a set of indices into a 801 /// table maintained by a FactManager. A typical FactSet only holds 1 or 2 802 /// locks, so we can get away with doing a linear search for lookup. Note 803 /// that a hashtable or map is inappropriate in this case, because lookups 804 /// may involve partial pattern matches, rather than exact matches. 805 class FactSet { 806 private: 807 typedef SmallVector<FactID, 4> FactVec; 808 809 FactVec FactIDs; 810 811 public: 812 typedef FactVec::iterator iterator; 813 typedef FactVec::const_iterator const_iterator; 814 815 iterator begin() { return FactIDs.begin(); } 816 const_iterator begin() const { return FactIDs.begin(); } 817 818 iterator end() { return FactIDs.end(); } 819 const_iterator end() const { return FactIDs.end(); } 820 821 bool isEmpty() const { return FactIDs.size() == 0; } 822 823 FactID addLock(FactManager& FM, const SExpr& M, const LockData& L) { 824 FactID F = FM.newLock(M, L); 825 FactIDs.push_back(F); 826 return F; 827 } 828 829 bool removeLock(FactManager& FM, const SExpr& M) { 830 unsigned n = FactIDs.size(); 831 if (n == 0) 832 return false; 833 834 for (unsigned i = 0; i < n-1; ++i) { 835 if (FM[FactIDs[i]].MutID.matches(M)) { 836 FactIDs[i] = FactIDs[n-1]; 837 FactIDs.pop_back(); 838 return true; 839 } 840 } 841 if (FM[FactIDs[n-1]].MutID.matches(M)) { 842 FactIDs.pop_back(); 843 return true; 844 } 845 return false; 846 } 847 848 // Returns an iterator 849 iterator findLockIter(FactManager &FM, const SExpr &M) { 850 for (iterator I = begin(), E = end(); I != E; ++I) { 851 const SExpr &Exp = FM[*I].MutID; 852 if (Exp.matches(M)) 853 return I; 854 } 855 return end(); 856 } 857 858 LockData* findLock(FactManager &FM, const SExpr &M) const { 859 for (const_iterator I = begin(), E = end(); I != E; ++I) { 860 const SExpr &Exp = FM[*I].MutID; 861 if (Exp.matches(M)) 862 return &FM[*I].LDat; 863 } 864 return 0; 865 } 866 867 LockData* findLockUniv(FactManager &FM, const SExpr &M) const { 868 for (const_iterator I = begin(), E = end(); I != E; ++I) { 869 const SExpr &Exp = FM[*I].MutID; 870 if (Exp.matches(M) || Exp.isUniversal()) 871 return &FM[*I].LDat; 872 } 873 return 0; 874 } 875 876 FactEntry* findPartialMatch(FactManager &FM, const SExpr &M) const { 877 for (const_iterator I=begin(), E=end(); I != E; ++I) { 878 const SExpr& Exp = FM[*I].MutID; 879 if (Exp.partiallyMatches(M)) return &FM[*I]; 880 } 881 return 0; 882 } 883 }; 884 885 886 887 /// A Lockset maps each SExpr (defined above) to information about how it has 888 /// been locked. 889 typedef llvm::ImmutableMap<SExpr, LockData> Lockset; 890 typedef llvm::ImmutableMap<const NamedDecl*, unsigned> LocalVarContext; 891 892 class LocalVariableMap; 893 894 /// A side (entry or exit) of a CFG node. 895 enum CFGBlockSide { CBS_Entry, CBS_Exit }; 896 897 /// CFGBlockInfo is a struct which contains all the information that is 898 /// maintained for each block in the CFG. See LocalVariableMap for more 899 /// information about the contexts. 900 struct CFGBlockInfo { 901 FactSet EntrySet; // Lockset held at entry to block 902 FactSet ExitSet; // Lockset held at exit from block 903 LocalVarContext EntryContext; // Context held at entry to block 904 LocalVarContext ExitContext; // Context held at exit from block 905 SourceLocation EntryLoc; // Location of first statement in block 906 SourceLocation ExitLoc; // Location of last statement in block. 907 unsigned EntryIndex; // Used to replay contexts later 908 bool Reachable; // Is this block reachable? 909 910 const FactSet &getSet(CFGBlockSide Side) const { 911 return Side == CBS_Entry ? EntrySet : ExitSet; 912 } 913 SourceLocation getLocation(CFGBlockSide Side) const { 914 return Side == CBS_Entry ? EntryLoc : ExitLoc; 915 } 916 917 private: 918 CFGBlockInfo(LocalVarContext EmptyCtx) 919 : EntryContext(EmptyCtx), ExitContext(EmptyCtx), Reachable(false) 920 { } 921 922 public: 923 static CFGBlockInfo getEmptyBlockInfo(LocalVariableMap &M); 924 }; 925 926 927 928 // A LocalVariableMap maintains a map from local variables to their currently 929 // valid definitions. It provides SSA-like functionality when traversing the 930 // CFG. Like SSA, each definition or assignment to a variable is assigned a 931 // unique name (an integer), which acts as the SSA name for that definition. 932 // The total set of names is shared among all CFG basic blocks. 933 // Unlike SSA, we do not rewrite expressions to replace local variables declrefs 934 // with their SSA-names. Instead, we compute a Context for each point in the 935 // code, which maps local variables to the appropriate SSA-name. This map 936 // changes with each assignment. 937 // 938 // The map is computed in a single pass over the CFG. Subsequent analyses can 939 // then query the map to find the appropriate Context for a statement, and use 940 // that Context to look up the definitions of variables. 941 class LocalVariableMap { 942 public: 943 typedef LocalVarContext Context; 944 945 /// A VarDefinition consists of an expression, representing the value of the 946 /// variable, along with the context in which that expression should be 947 /// interpreted. A reference VarDefinition does not itself contain this 948 /// information, but instead contains a pointer to a previous VarDefinition. 949 struct VarDefinition { 950 public: 951 friend class LocalVariableMap; 952 953 const NamedDecl *Dec; // The original declaration for this variable. 954 const Expr *Exp; // The expression for this variable, OR 955 unsigned Ref; // Reference to another VarDefinition 956 Context Ctx; // The map with which Exp should be interpreted. 957 958 bool isReference() { return !Exp; } 959 960 private: 961 // Create ordinary variable definition 962 VarDefinition(const NamedDecl *D, const Expr *E, Context C) 963 : Dec(D), Exp(E), Ref(0), Ctx(C) 964 { } 965 966 // Create reference to previous definition 967 VarDefinition(const NamedDecl *D, unsigned R, Context C) 968 : Dec(D), Exp(0), Ref(R), Ctx(C) 969 { } 970 }; 971 972 private: 973 Context::Factory ContextFactory; 974 std::vector<VarDefinition> VarDefinitions; 975 std::vector<unsigned> CtxIndices; 976 std::vector<std::pair<Stmt*, Context> > SavedContexts; 977 978 public: 979 LocalVariableMap() { 980 // index 0 is a placeholder for undefined variables (aka phi-nodes). 981 VarDefinitions.push_back(VarDefinition(0, 0u, getEmptyContext())); 982 } 983 984 /// Look up a definition, within the given context. 985 const VarDefinition* lookup(const NamedDecl *D, Context Ctx) { 986 const unsigned *i = Ctx.lookup(D); 987 if (!i) 988 return 0; 989 assert(*i < VarDefinitions.size()); 990 return &VarDefinitions[*i]; 991 } 992 993 /// Look up the definition for D within the given context. Returns 994 /// NULL if the expression is not statically known. If successful, also 995 /// modifies Ctx to hold the context of the return Expr. 996 const Expr* lookupExpr(const NamedDecl *D, Context &Ctx) { 997 const unsigned *P = Ctx.lookup(D); 998 if (!P) 999 return 0; 1000 1001 unsigned i = *P; 1002 while (i > 0) { 1003 if (VarDefinitions[i].Exp) { 1004 Ctx = VarDefinitions[i].Ctx; 1005 return VarDefinitions[i].Exp; 1006 } 1007 i = VarDefinitions[i].Ref; 1008 } 1009 return 0; 1010 } 1011 1012 Context getEmptyContext() { return ContextFactory.getEmptyMap(); } 1013 1014 /// Return the next context after processing S. This function is used by 1015 /// clients of the class to get the appropriate context when traversing the 1016 /// CFG. It must be called for every assignment or DeclStmt. 1017 Context getNextContext(unsigned &CtxIndex, Stmt *S, Context C) { 1018 if (SavedContexts[CtxIndex+1].first == S) { 1019 CtxIndex++; 1020 Context Result = SavedContexts[CtxIndex].second; 1021 return Result; 1022 } 1023 return C; 1024 } 1025 1026 void dumpVarDefinitionName(unsigned i) { 1027 if (i == 0) { 1028 llvm::errs() << "Undefined"; 1029 return; 1030 } 1031 const NamedDecl *Dec = VarDefinitions[i].Dec; 1032 if (!Dec) { 1033 llvm::errs() << "<<NULL>>"; 1034 return; 1035 } 1036 Dec->printName(llvm::errs()); 1037 llvm::errs() << "." << i << " " << ((const void*) Dec); 1038 } 1039 1040 /// Dumps an ASCII representation of the variable map to llvm::errs() 1041 void dump() { 1042 for (unsigned i = 1, e = VarDefinitions.size(); i < e; ++i) { 1043 const Expr *Exp = VarDefinitions[i].Exp; 1044 unsigned Ref = VarDefinitions[i].Ref; 1045 1046 dumpVarDefinitionName(i); 1047 llvm::errs() << " = "; 1048 if (Exp) Exp->dump(); 1049 else { 1050 dumpVarDefinitionName(Ref); 1051 llvm::errs() << "\n"; 1052 } 1053 } 1054 } 1055 1056 /// Dumps an ASCII representation of a Context to llvm::errs() 1057 void dumpContext(Context C) { 1058 for (Context::iterator I = C.begin(), E = C.end(); I != E; ++I) { 1059 const NamedDecl *D = I.getKey(); 1060 D->printName(llvm::errs()); 1061 const unsigned *i = C.lookup(D); 1062 llvm::errs() << " -> "; 1063 dumpVarDefinitionName(*i); 1064 llvm::errs() << "\n"; 1065 } 1066 } 1067 1068 /// Builds the variable map. 1069 void traverseCFG(CFG *CFGraph, PostOrderCFGView *SortedGraph, 1070 std::vector<CFGBlockInfo> &BlockInfo); 1071 1072 protected: 1073 // Get the current context index 1074 unsigned getContextIndex() { return SavedContexts.size()-1; } 1075 1076 // Save the current context for later replay 1077 void saveContext(Stmt *S, Context C) { 1078 SavedContexts.push_back(std::make_pair(S,C)); 1079 } 1080 1081 // Adds a new definition to the given context, and returns a new context. 1082 // This method should be called when declaring a new variable. 1083 Context addDefinition(const NamedDecl *D, Expr *Exp, Context Ctx) { 1084 assert(!Ctx.contains(D)); 1085 unsigned newID = VarDefinitions.size(); 1086 Context NewCtx = ContextFactory.add(Ctx, D, newID); 1087 VarDefinitions.push_back(VarDefinition(D, Exp, Ctx)); 1088 return NewCtx; 1089 } 1090 1091 // Add a new reference to an existing definition. 1092 Context addReference(const NamedDecl *D, unsigned i, Context Ctx) { 1093 unsigned newID = VarDefinitions.size(); 1094 Context NewCtx = ContextFactory.add(Ctx, D, newID); 1095 VarDefinitions.push_back(VarDefinition(D, i, Ctx)); 1096 return NewCtx; 1097 } 1098 1099 // Updates a definition only if that definition is already in the map. 1100 // This method should be called when assigning to an existing variable. 1101 Context updateDefinition(const NamedDecl *D, Expr *Exp, Context Ctx) { 1102 if (Ctx.contains(D)) { 1103 unsigned newID = VarDefinitions.size(); 1104 Context NewCtx = ContextFactory.remove(Ctx, D); 1105 NewCtx = ContextFactory.add(NewCtx, D, newID); 1106 VarDefinitions.push_back(VarDefinition(D, Exp, Ctx)); 1107 return NewCtx; 1108 } 1109 return Ctx; 1110 } 1111 1112 // Removes a definition from the context, but keeps the variable name 1113 // as a valid variable. The index 0 is a placeholder for cleared definitions. 1114 Context clearDefinition(const NamedDecl *D, Context Ctx) { 1115 Context NewCtx = Ctx; 1116 if (NewCtx.contains(D)) { 1117 NewCtx = ContextFactory.remove(NewCtx, D); 1118 NewCtx = ContextFactory.add(NewCtx, D, 0); 1119 } 1120 return NewCtx; 1121 } 1122 1123 // Remove a definition entirely frmo the context. 1124 Context removeDefinition(const NamedDecl *D, Context Ctx) { 1125 Context NewCtx = Ctx; 1126 if (NewCtx.contains(D)) { 1127 NewCtx = ContextFactory.remove(NewCtx, D); 1128 } 1129 return NewCtx; 1130 } 1131 1132 Context intersectContexts(Context C1, Context C2); 1133 Context createReferenceContext(Context C); 1134 void intersectBackEdge(Context C1, Context C2); 1135 1136 friend class VarMapBuilder; 1137 }; 1138 1139 1140 // This has to be defined after LocalVariableMap. 1141 CFGBlockInfo CFGBlockInfo::getEmptyBlockInfo(LocalVariableMap &M) { 1142 return CFGBlockInfo(M.getEmptyContext()); 1143 } 1144 1145 1146 /// Visitor which builds a LocalVariableMap 1147 class VarMapBuilder : public StmtVisitor<VarMapBuilder> { 1148 public: 1149 LocalVariableMap* VMap; 1150 LocalVariableMap::Context Ctx; 1151 1152 VarMapBuilder(LocalVariableMap *VM, LocalVariableMap::Context C) 1153 : VMap(VM), Ctx(C) {} 1154 1155 void VisitDeclStmt(DeclStmt *S); 1156 void VisitBinaryOperator(BinaryOperator *BO); 1157 }; 1158 1159 1160 // Add new local variables to the variable map 1161 void VarMapBuilder::VisitDeclStmt(DeclStmt *S) { 1162 bool modifiedCtx = false; 1163 DeclGroupRef DGrp = S->getDeclGroup(); 1164 for (DeclGroupRef::iterator I = DGrp.begin(), E = DGrp.end(); I != E; ++I) { 1165 if (VarDecl *VD = dyn_cast_or_null<VarDecl>(*I)) { 1166 Expr *E = VD->getInit(); 1167 1168 // Add local variables with trivial type to the variable map 1169 QualType T = VD->getType(); 1170 if (T.isTrivialType(VD->getASTContext())) { 1171 Ctx = VMap->addDefinition(VD, E, Ctx); 1172 modifiedCtx = true; 1173 } 1174 } 1175 } 1176 if (modifiedCtx) 1177 VMap->saveContext(S, Ctx); 1178 } 1179 1180 // Update local variable definitions in variable map 1181 void VarMapBuilder::VisitBinaryOperator(BinaryOperator *BO) { 1182 if (!BO->isAssignmentOp()) 1183 return; 1184 1185 Expr *LHSExp = BO->getLHS()->IgnoreParenCasts(); 1186 1187 // Update the variable map and current context. 1188 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(LHSExp)) { 1189 ValueDecl *VDec = DRE->getDecl(); 1190 if (Ctx.lookup(VDec)) { 1191 if (BO->getOpcode() == BO_Assign) 1192 Ctx = VMap->updateDefinition(VDec, BO->getRHS(), Ctx); 1193 else 1194 // FIXME -- handle compound assignment operators 1195 Ctx = VMap->clearDefinition(VDec, Ctx); 1196 VMap->saveContext(BO, Ctx); 1197 } 1198 } 1199 } 1200 1201 1202 // Computes the intersection of two contexts. The intersection is the 1203 // set of variables which have the same definition in both contexts; 1204 // variables with different definitions are discarded. 1205 LocalVariableMap::Context 1206 LocalVariableMap::intersectContexts(Context C1, Context C2) { 1207 Context Result = C1; 1208 for (Context::iterator I = C1.begin(), E = C1.end(); I != E; ++I) { 1209 const NamedDecl *Dec = I.getKey(); 1210 unsigned i1 = I.getData(); 1211 const unsigned *i2 = C2.lookup(Dec); 1212 if (!i2) // variable doesn't exist on second path 1213 Result = removeDefinition(Dec, Result); 1214 else if (*i2 != i1) // variable exists, but has different definition 1215 Result = clearDefinition(Dec, Result); 1216 } 1217 return Result; 1218 } 1219 1220 // For every variable in C, create a new variable that refers to the 1221 // definition in C. Return a new context that contains these new variables. 1222 // (We use this for a naive implementation of SSA on loop back-edges.) 1223 LocalVariableMap::Context LocalVariableMap::createReferenceContext(Context C) { 1224 Context Result = getEmptyContext(); 1225 for (Context::iterator I = C.begin(), E = C.end(); I != E; ++I) { 1226 const NamedDecl *Dec = I.getKey(); 1227 unsigned i = I.getData(); 1228 Result = addReference(Dec, i, Result); 1229 } 1230 return Result; 1231 } 1232 1233 // This routine also takes the intersection of C1 and C2, but it does so by 1234 // altering the VarDefinitions. C1 must be the result of an earlier call to 1235 // createReferenceContext. 1236 void LocalVariableMap::intersectBackEdge(Context C1, Context C2) { 1237 for (Context::iterator I = C1.begin(), E = C1.end(); I != E; ++I) { 1238 const NamedDecl *Dec = I.getKey(); 1239 unsigned i1 = I.getData(); 1240 VarDefinition *VDef = &VarDefinitions[i1]; 1241 assert(VDef->isReference()); 1242 1243 const unsigned *i2 = C2.lookup(Dec); 1244 if (!i2 || (*i2 != i1)) 1245 VDef->Ref = 0; // Mark this variable as undefined 1246 } 1247 } 1248 1249 1250 // Traverse the CFG in topological order, so all predecessors of a block 1251 // (excluding back-edges) are visited before the block itself. At 1252 // each point in the code, we calculate a Context, which holds the set of 1253 // variable definitions which are visible at that point in execution. 1254 // Visible variables are mapped to their definitions using an array that 1255 // contains all definitions. 1256 // 1257 // At join points in the CFG, the set is computed as the intersection of 1258 // the incoming sets along each edge, E.g. 1259 // 1260 // { Context | VarDefinitions } 1261 // int x = 0; { x -> x1 | x1 = 0 } 1262 // int y = 0; { x -> x1, y -> y1 | y1 = 0, x1 = 0 } 1263 // if (b) x = 1; { x -> x2, y -> y1 | x2 = 1, y1 = 0, ... } 1264 // else x = 2; { x -> x3, y -> y1 | x3 = 2, x2 = 1, ... } 1265 // ... { y -> y1 (x is unknown) | x3 = 2, x2 = 1, ... } 1266 // 1267 // This is essentially a simpler and more naive version of the standard SSA 1268 // algorithm. Those definitions that remain in the intersection are from blocks 1269 // that strictly dominate the current block. We do not bother to insert proper 1270 // phi nodes, because they are not used in our analysis; instead, wherever 1271 // a phi node would be required, we simply remove that definition from the 1272 // context (E.g. x above). 1273 // 1274 // The initial traversal does not capture back-edges, so those need to be 1275 // handled on a separate pass. Whenever the first pass encounters an 1276 // incoming back edge, it duplicates the context, creating new definitions 1277 // that refer back to the originals. (These correspond to places where SSA 1278 // might have to insert a phi node.) On the second pass, these definitions are 1279 // set to NULL if the variable has changed on the back-edge (i.e. a phi 1280 // node was actually required.) E.g. 1281 // 1282 // { Context | VarDefinitions } 1283 // int x = 0, y = 0; { x -> x1, y -> y1 | y1 = 0, x1 = 0 } 1284 // while (b) { x -> x2, y -> y1 | [1st:] x2=x1; [2nd:] x2=NULL; } 1285 // x = x+1; { x -> x3, y -> y1 | x3 = x2 + 1, ... } 1286 // ... { y -> y1 | x3 = 2, x2 = 1, ... } 1287 // 1288 void LocalVariableMap::traverseCFG(CFG *CFGraph, 1289 PostOrderCFGView *SortedGraph, 1290 std::vector<CFGBlockInfo> &BlockInfo) { 1291 PostOrderCFGView::CFGBlockSet VisitedBlocks(CFGraph); 1292 1293 CtxIndices.resize(CFGraph->getNumBlockIDs()); 1294 1295 for (PostOrderCFGView::iterator I = SortedGraph->begin(), 1296 E = SortedGraph->end(); I!= E; ++I) { 1297 const CFGBlock *CurrBlock = *I; 1298 int CurrBlockID = CurrBlock->getBlockID(); 1299 CFGBlockInfo *CurrBlockInfo = &BlockInfo[CurrBlockID]; 1300 1301 VisitedBlocks.insert(CurrBlock); 1302 1303 // Calculate the entry context for the current block 1304 bool HasBackEdges = false; 1305 bool CtxInit = true; 1306 for (CFGBlock::const_pred_iterator PI = CurrBlock->pred_begin(), 1307 PE = CurrBlock->pred_end(); PI != PE; ++PI) { 1308 // if *PI -> CurrBlock is a back edge, so skip it 1309 if (*PI == 0 || !VisitedBlocks.alreadySet(*PI)) { 1310 HasBackEdges = true; 1311 continue; 1312 } 1313 1314 int PrevBlockID = (*PI)->getBlockID(); 1315 CFGBlockInfo *PrevBlockInfo = &BlockInfo[PrevBlockID]; 1316 1317 if (CtxInit) { 1318 CurrBlockInfo->EntryContext = PrevBlockInfo->ExitContext; 1319 CtxInit = false; 1320 } 1321 else { 1322 CurrBlockInfo->EntryContext = 1323 intersectContexts(CurrBlockInfo->EntryContext, 1324 PrevBlockInfo->ExitContext); 1325 } 1326 } 1327 1328 // Duplicate the context if we have back-edges, so we can call 1329 // intersectBackEdges later. 1330 if (HasBackEdges) 1331 CurrBlockInfo->EntryContext = 1332 createReferenceContext(CurrBlockInfo->EntryContext); 1333 1334 // Create a starting context index for the current block 1335 saveContext(0, CurrBlockInfo->EntryContext); 1336 CurrBlockInfo->EntryIndex = getContextIndex(); 1337 1338 // Visit all the statements in the basic block. 1339 VarMapBuilder VMapBuilder(this, CurrBlockInfo->EntryContext); 1340 for (CFGBlock::const_iterator BI = CurrBlock->begin(), 1341 BE = CurrBlock->end(); BI != BE; ++BI) { 1342 switch (BI->getKind()) { 1343 case CFGElement::Statement: { 1344 CFGStmt CS = BI->castAs<CFGStmt>(); 1345 VMapBuilder.Visit(const_cast<Stmt*>(CS.getStmt())); 1346 break; 1347 } 1348 default: 1349 break; 1350 } 1351 } 1352 CurrBlockInfo->ExitContext = VMapBuilder.Ctx; 1353 1354 // Mark variables on back edges as "unknown" if they've been changed. 1355 for (CFGBlock::const_succ_iterator SI = CurrBlock->succ_begin(), 1356 SE = CurrBlock->succ_end(); SI != SE; ++SI) { 1357 // if CurrBlock -> *SI is *not* a back edge 1358 if (*SI == 0 || !VisitedBlocks.alreadySet(*SI)) 1359 continue; 1360 1361 CFGBlock *FirstLoopBlock = *SI; 1362 Context LoopBegin = BlockInfo[FirstLoopBlock->getBlockID()].EntryContext; 1363 Context LoopEnd = CurrBlockInfo->ExitContext; 1364 intersectBackEdge(LoopBegin, LoopEnd); 1365 } 1366 } 1367 1368 // Put an extra entry at the end of the indexed context array 1369 unsigned exitID = CFGraph->getExit().getBlockID(); 1370 saveContext(0, BlockInfo[exitID].ExitContext); 1371 } 1372 1373 /// Find the appropriate source locations to use when producing diagnostics for 1374 /// each block in the CFG. 1375 static void findBlockLocations(CFG *CFGraph, 1376 PostOrderCFGView *SortedGraph, 1377 std::vector<CFGBlockInfo> &BlockInfo) { 1378 for (PostOrderCFGView::iterator I = SortedGraph->begin(), 1379 E = SortedGraph->end(); I!= E; ++I) { 1380 const CFGBlock *CurrBlock = *I; 1381 CFGBlockInfo *CurrBlockInfo = &BlockInfo[CurrBlock->getBlockID()]; 1382 1383 // Find the source location of the last statement in the block, if the 1384 // block is not empty. 1385 if (const Stmt *S = CurrBlock->getTerminator()) { 1386 CurrBlockInfo->EntryLoc = CurrBlockInfo->ExitLoc = S->getLocStart(); 1387 } else { 1388 for (CFGBlock::const_reverse_iterator BI = CurrBlock->rbegin(), 1389 BE = CurrBlock->rend(); BI != BE; ++BI) { 1390 // FIXME: Handle other CFGElement kinds. 1391 if (Optional<CFGStmt> CS = BI->getAs<CFGStmt>()) { 1392 CurrBlockInfo->ExitLoc = CS->getStmt()->getLocStart(); 1393 break; 1394 } 1395 } 1396 } 1397 1398 if (!CurrBlockInfo->ExitLoc.isInvalid()) { 1399 // This block contains at least one statement. Find the source location 1400 // of the first statement in the block. 1401 for (CFGBlock::const_iterator BI = CurrBlock->begin(), 1402 BE = CurrBlock->end(); BI != BE; ++BI) { 1403 // FIXME: Handle other CFGElement kinds. 1404 if (Optional<CFGStmt> CS = BI->getAs<CFGStmt>()) { 1405 CurrBlockInfo->EntryLoc = CS->getStmt()->getLocStart(); 1406 break; 1407 } 1408 } 1409 } else if (CurrBlock->pred_size() == 1 && *CurrBlock->pred_begin() && 1410 CurrBlock != &CFGraph->getExit()) { 1411 // The block is empty, and has a single predecessor. Use its exit 1412 // location. 1413 CurrBlockInfo->EntryLoc = CurrBlockInfo->ExitLoc = 1414 BlockInfo[(*CurrBlock->pred_begin())->getBlockID()].ExitLoc; 1415 } 1416 } 1417 } 1418 1419 /// \brief Class which implements the core thread safety analysis routines. 1420 class ThreadSafetyAnalyzer { 1421 friend class BuildLockset; 1422 1423 ThreadSafetyHandler &Handler; 1424 LocalVariableMap LocalVarMap; 1425 FactManager FactMan; 1426 std::vector<CFGBlockInfo> BlockInfo; 1427 1428 public: 1429 ThreadSafetyAnalyzer(ThreadSafetyHandler &H) : Handler(H) {} 1430 1431 void addLock(FactSet &FSet, const SExpr &Mutex, const LockData &LDat); 1432 void removeLock(FactSet &FSet, const SExpr &Mutex, 1433 SourceLocation UnlockLoc, bool FullyRemove, LockKind Kind); 1434 1435 template <typename AttrType> 1436 void getMutexIDs(MutexIDList &Mtxs, AttrType *Attr, Expr *Exp, 1437 const NamedDecl *D, VarDecl *SelfDecl=0); 1438 1439 template <class AttrType> 1440 void getMutexIDs(MutexIDList &Mtxs, AttrType *Attr, Expr *Exp, 1441 const NamedDecl *D, 1442 const CFGBlock *PredBlock, const CFGBlock *CurrBlock, 1443 Expr *BrE, bool Neg); 1444 1445 const CallExpr* getTrylockCallExpr(const Stmt *Cond, LocalVarContext C, 1446 bool &Negate); 1447 1448 void getEdgeLockset(FactSet &Result, const FactSet &ExitSet, 1449 const CFGBlock* PredBlock, 1450 const CFGBlock *CurrBlock); 1451 1452 void intersectAndWarn(FactSet &FSet1, const FactSet &FSet2, 1453 SourceLocation JoinLoc, 1454 LockErrorKind LEK1, LockErrorKind LEK2, 1455 bool Modify=true); 1456 1457 void intersectAndWarn(FactSet &FSet1, const FactSet &FSet2, 1458 SourceLocation JoinLoc, LockErrorKind LEK1, 1459 bool Modify=true) { 1460 intersectAndWarn(FSet1, FSet2, JoinLoc, LEK1, LEK1, Modify); 1461 } 1462 1463 void runAnalysis(AnalysisDeclContext &AC); 1464 }; 1465 1466 1467 /// \brief Add a new lock to the lockset, warning if the lock is already there. 1468 /// \param Mutex -- the Mutex expression for the lock 1469 /// \param LDat -- the LockData for the lock 1470 void ThreadSafetyAnalyzer::addLock(FactSet &FSet, const SExpr &Mutex, 1471 const LockData &LDat) { 1472 // FIXME: deal with acquired before/after annotations. 1473 // FIXME: Don't always warn when we have support for reentrant locks. 1474 if (Mutex.shouldIgnore()) 1475 return; 1476 1477 if (FSet.findLock(FactMan, Mutex)) { 1478 if (!LDat.Asserted) 1479 Handler.handleDoubleLock(Mutex.toString(), LDat.AcquireLoc); 1480 } else { 1481 FSet.addLock(FactMan, Mutex, LDat); 1482 } 1483 } 1484 1485 1486 /// \brief Remove a lock from the lockset, warning if the lock is not there. 1487 /// \param Mutex The lock expression corresponding to the lock to be removed 1488 /// \param UnlockLoc The source location of the unlock (only used in error msg) 1489 void ThreadSafetyAnalyzer::removeLock(FactSet &FSet, const SExpr &Mutex, 1490 SourceLocation UnlockLoc, 1491 bool FullyRemove, LockKind ReceivedKind) { 1492 if (Mutex.shouldIgnore()) 1493 return; 1494 1495 const LockData *LDat = FSet.findLock(FactMan, Mutex); 1496 if (!LDat) { 1497 Handler.handleUnmatchedUnlock(Mutex.toString(), UnlockLoc); 1498 return; 1499 } 1500 1501 // Generic lock removal doesn't care about lock kind mismatches, but 1502 // otherwise diagnose when the lock kinds are mismatched. 1503 if (ReceivedKind != LK_Generic && LDat->LKind != ReceivedKind) { 1504 Handler.handleIncorrectUnlockKind(Mutex.toString(), LDat->LKind, 1505 ReceivedKind, UnlockLoc); 1506 return; 1507 } 1508 1509 if (LDat->UnderlyingMutex.isValid()) { 1510 // This is scoped lockable object, which manages the real mutex. 1511 if (FullyRemove) { 1512 // We're destroying the managing object. 1513 // Remove the underlying mutex if it exists; but don't warn. 1514 if (FSet.findLock(FactMan, LDat->UnderlyingMutex)) 1515 FSet.removeLock(FactMan, LDat->UnderlyingMutex); 1516 } else { 1517 // We're releasing the underlying mutex, but not destroying the 1518 // managing object. Warn on dual release. 1519 if (!FSet.findLock(FactMan, LDat->UnderlyingMutex)) { 1520 Handler.handleUnmatchedUnlock(LDat->UnderlyingMutex.toString(), 1521 UnlockLoc); 1522 } 1523 FSet.removeLock(FactMan, LDat->UnderlyingMutex); 1524 return; 1525 } 1526 } 1527 FSet.removeLock(FactMan, Mutex); 1528 } 1529 1530 1531 /// \brief Extract the list of mutexIDs from the attribute on an expression, 1532 /// and push them onto Mtxs, discarding any duplicates. 1533 template <typename AttrType> 1534 void ThreadSafetyAnalyzer::getMutexIDs(MutexIDList &Mtxs, AttrType *Attr, 1535 Expr *Exp, const NamedDecl *D, 1536 VarDecl *SelfDecl) { 1537 typedef typename AttrType::args_iterator iterator_type; 1538 1539 if (Attr->args_size() == 0) { 1540 // The mutex held is the "this" object. 1541 SExpr Mu(0, Exp, D, SelfDecl); 1542 if (!Mu.isValid()) 1543 SExpr::warnInvalidLock(Handler, 0, Exp, D); 1544 else 1545 Mtxs.push_back_nodup(Mu); 1546 return; 1547 } 1548 1549 for (iterator_type I=Attr->args_begin(), E=Attr->args_end(); I != E; ++I) { 1550 SExpr Mu(*I, Exp, D, SelfDecl); 1551 if (!Mu.isValid()) 1552 SExpr::warnInvalidLock(Handler, *I, Exp, D); 1553 else 1554 Mtxs.push_back_nodup(Mu); 1555 } 1556 } 1557 1558 1559 /// \brief Extract the list of mutexIDs from a trylock attribute. If the 1560 /// trylock applies to the given edge, then push them onto Mtxs, discarding 1561 /// any duplicates. 1562 template <class AttrType> 1563 void ThreadSafetyAnalyzer::getMutexIDs(MutexIDList &Mtxs, AttrType *Attr, 1564 Expr *Exp, const NamedDecl *D, 1565 const CFGBlock *PredBlock, 1566 const CFGBlock *CurrBlock, 1567 Expr *BrE, bool Neg) { 1568 // Find out which branch has the lock 1569 bool branch = 0; 1570 if (CXXBoolLiteralExpr *BLE = dyn_cast_or_null<CXXBoolLiteralExpr>(BrE)) { 1571 branch = BLE->getValue(); 1572 } 1573 else if (IntegerLiteral *ILE = dyn_cast_or_null<IntegerLiteral>(BrE)) { 1574 branch = ILE->getValue().getBoolValue(); 1575 } 1576 int branchnum = branch ? 0 : 1; 1577 if (Neg) branchnum = !branchnum; 1578 1579 // If we've taken the trylock branch, then add the lock 1580 int i = 0; 1581 for (CFGBlock::const_succ_iterator SI = PredBlock->succ_begin(), 1582 SE = PredBlock->succ_end(); SI != SE && i < 2; ++SI, ++i) { 1583 if (*SI == CurrBlock && i == branchnum) { 1584 getMutexIDs(Mtxs, Attr, Exp, D); 1585 } 1586 } 1587 } 1588 1589 1590 bool getStaticBooleanValue(Expr* E, bool& TCond) { 1591 if (isa<CXXNullPtrLiteralExpr>(E) || isa<GNUNullExpr>(E)) { 1592 TCond = false; 1593 return true; 1594 } else if (CXXBoolLiteralExpr *BLE = dyn_cast<CXXBoolLiteralExpr>(E)) { 1595 TCond = BLE->getValue(); 1596 return true; 1597 } else if (IntegerLiteral *ILE = dyn_cast<IntegerLiteral>(E)) { 1598 TCond = ILE->getValue().getBoolValue(); 1599 return true; 1600 } else if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) { 1601 return getStaticBooleanValue(CE->getSubExpr(), TCond); 1602 } 1603 return false; 1604 } 1605 1606 1607 // If Cond can be traced back to a function call, return the call expression. 1608 // The negate variable should be called with false, and will be set to true 1609 // if the function call is negated, e.g. if (!mu.tryLock(...)) 1610 const CallExpr* ThreadSafetyAnalyzer::getTrylockCallExpr(const Stmt *Cond, 1611 LocalVarContext C, 1612 bool &Negate) { 1613 if (!Cond) 1614 return 0; 1615 1616 if (const CallExpr *CallExp = dyn_cast<CallExpr>(Cond)) { 1617 return CallExp; 1618 } 1619 else if (const ParenExpr *PE = dyn_cast<ParenExpr>(Cond)) { 1620 return getTrylockCallExpr(PE->getSubExpr(), C, Negate); 1621 } 1622 else if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(Cond)) { 1623 return getTrylockCallExpr(CE->getSubExpr(), C, Negate); 1624 } 1625 else if (const ExprWithCleanups* EWC = dyn_cast<ExprWithCleanups>(Cond)) { 1626 return getTrylockCallExpr(EWC->getSubExpr(), C, Negate); 1627 } 1628 else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Cond)) { 1629 const Expr *E = LocalVarMap.lookupExpr(DRE->getDecl(), C); 1630 return getTrylockCallExpr(E, C, Negate); 1631 } 1632 else if (const UnaryOperator *UOP = dyn_cast<UnaryOperator>(Cond)) { 1633 if (UOP->getOpcode() == UO_LNot) { 1634 Negate = !Negate; 1635 return getTrylockCallExpr(UOP->getSubExpr(), C, Negate); 1636 } 1637 return 0; 1638 } 1639 else if (const BinaryOperator *BOP = dyn_cast<BinaryOperator>(Cond)) { 1640 if (BOP->getOpcode() == BO_EQ || BOP->getOpcode() == BO_NE) { 1641 if (BOP->getOpcode() == BO_NE) 1642 Negate = !Negate; 1643 1644 bool TCond = false; 1645 if (getStaticBooleanValue(BOP->getRHS(), TCond)) { 1646 if (!TCond) Negate = !Negate; 1647 return getTrylockCallExpr(BOP->getLHS(), C, Negate); 1648 } 1649 TCond = false; 1650 if (getStaticBooleanValue(BOP->getLHS(), TCond)) { 1651 if (!TCond) Negate = !Negate; 1652 return getTrylockCallExpr(BOP->getRHS(), C, Negate); 1653 } 1654 return 0; 1655 } 1656 if (BOP->getOpcode() == BO_LAnd) { 1657 // LHS must have been evaluated in a different block. 1658 return getTrylockCallExpr(BOP->getRHS(), C, Negate); 1659 } 1660 if (BOP->getOpcode() == BO_LOr) { 1661 return getTrylockCallExpr(BOP->getRHS(), C, Negate); 1662 } 1663 return 0; 1664 } 1665 return 0; 1666 } 1667 1668 1669 /// \brief Find the lockset that holds on the edge between PredBlock 1670 /// and CurrBlock. The edge set is the exit set of PredBlock (passed 1671 /// as the ExitSet parameter) plus any trylocks, which are conditionally held. 1672 void ThreadSafetyAnalyzer::getEdgeLockset(FactSet& Result, 1673 const FactSet &ExitSet, 1674 const CFGBlock *PredBlock, 1675 const CFGBlock *CurrBlock) { 1676 Result = ExitSet; 1677 1678 const Stmt *Cond = PredBlock->getTerminatorCondition(); 1679 if (!Cond) 1680 return; 1681 1682 bool Negate = false; 1683 const CFGBlockInfo *PredBlockInfo = &BlockInfo[PredBlock->getBlockID()]; 1684 const LocalVarContext &LVarCtx = PredBlockInfo->ExitContext; 1685 1686 CallExpr *Exp = 1687 const_cast<CallExpr*>(getTrylockCallExpr(Cond, LVarCtx, Negate)); 1688 if (!Exp) 1689 return; 1690 1691 NamedDecl *FunDecl = dyn_cast_or_null<NamedDecl>(Exp->getCalleeDecl()); 1692 if(!FunDecl || !FunDecl->hasAttrs()) 1693 return; 1694 1695 MutexIDList ExclusiveLocksToAdd; 1696 MutexIDList SharedLocksToAdd; 1697 1698 // If the condition is a call to a Trylock function, then grab the attributes 1699 AttrVec &ArgAttrs = FunDecl->getAttrs(); 1700 for (unsigned i = 0; i < ArgAttrs.size(); ++i) { 1701 Attr *Attr = ArgAttrs[i]; 1702 switch (Attr->getKind()) { 1703 case attr::ExclusiveTrylockFunction: { 1704 ExclusiveTrylockFunctionAttr *A = 1705 cast<ExclusiveTrylockFunctionAttr>(Attr); 1706 getMutexIDs(ExclusiveLocksToAdd, A, Exp, FunDecl, 1707 PredBlock, CurrBlock, A->getSuccessValue(), Negate); 1708 break; 1709 } 1710 case attr::SharedTrylockFunction: { 1711 SharedTrylockFunctionAttr *A = 1712 cast<SharedTrylockFunctionAttr>(Attr); 1713 getMutexIDs(SharedLocksToAdd, A, Exp, FunDecl, 1714 PredBlock, CurrBlock, A->getSuccessValue(), Negate); 1715 break; 1716 } 1717 default: 1718 break; 1719 } 1720 } 1721 1722 // Add and remove locks. 1723 SourceLocation Loc = Exp->getExprLoc(); 1724 for (unsigned i=0,n=ExclusiveLocksToAdd.size(); i<n; ++i) { 1725 addLock(Result, ExclusiveLocksToAdd[i], 1726 LockData(Loc, LK_Exclusive)); 1727 } 1728 for (unsigned i=0,n=SharedLocksToAdd.size(); i<n; ++i) { 1729 addLock(Result, SharedLocksToAdd[i], 1730 LockData(Loc, LK_Shared)); 1731 } 1732 } 1733 1734 1735 /// \brief We use this class to visit different types of expressions in 1736 /// CFGBlocks, and build up the lockset. 1737 /// An expression may cause us to add or remove locks from the lockset, or else 1738 /// output error messages related to missing locks. 1739 /// FIXME: In future, we may be able to not inherit from a visitor. 1740 class BuildLockset : public StmtVisitor<BuildLockset> { 1741 friend class ThreadSafetyAnalyzer; 1742 1743 ThreadSafetyAnalyzer *Analyzer; 1744 FactSet FSet; 1745 LocalVariableMap::Context LVarCtx; 1746 unsigned CtxIndex; 1747 1748 // Helper functions 1749 const ValueDecl *getValueDecl(const Expr *Exp); 1750 1751 void warnIfMutexNotHeld(const NamedDecl *D, const Expr *Exp, AccessKind AK, 1752 Expr *MutexExp, ProtectedOperationKind POK); 1753 void warnIfMutexHeld(const NamedDecl *D, const Expr *Exp, Expr *MutexExp); 1754 1755 void checkAccess(const Expr *Exp, AccessKind AK); 1756 void checkPtAccess(const Expr *Exp, AccessKind AK); 1757 1758 void handleCall(Expr *Exp, const NamedDecl *D, VarDecl *VD = 0); 1759 1760 public: 1761 BuildLockset(ThreadSafetyAnalyzer *Anlzr, CFGBlockInfo &Info) 1762 : StmtVisitor<BuildLockset>(), 1763 Analyzer(Anlzr), 1764 FSet(Info.EntrySet), 1765 LVarCtx(Info.EntryContext), 1766 CtxIndex(Info.EntryIndex) 1767 {} 1768 1769 void VisitUnaryOperator(UnaryOperator *UO); 1770 void VisitBinaryOperator(BinaryOperator *BO); 1771 void VisitCastExpr(CastExpr *CE); 1772 void VisitCallExpr(CallExpr *Exp); 1773 void VisitCXXConstructExpr(CXXConstructExpr *Exp); 1774 void VisitDeclStmt(DeclStmt *S); 1775 }; 1776 1777 1778 /// \brief Gets the value decl pointer from DeclRefExprs or MemberExprs 1779 const ValueDecl *BuildLockset::getValueDecl(const Expr *Exp) { 1780 if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(Exp)) 1781 return getValueDecl(CE->getSubExpr()); 1782 1783 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Exp)) 1784 return DR->getDecl(); 1785 1786 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Exp)) 1787 return ME->getMemberDecl(); 1788 1789 return 0; 1790 } 1791 1792 /// \brief Warn if the LSet does not contain a lock sufficient to protect access 1793 /// of at least the passed in AccessKind. 1794 void BuildLockset::warnIfMutexNotHeld(const NamedDecl *D, const Expr *Exp, 1795 AccessKind AK, Expr *MutexExp, 1796 ProtectedOperationKind POK) { 1797 LockKind LK = getLockKindFromAccessKind(AK); 1798 1799 SExpr Mutex(MutexExp, Exp, D); 1800 if (!Mutex.isValid()) { 1801 SExpr::warnInvalidLock(Analyzer->Handler, MutexExp, Exp, D); 1802 return; 1803 } else if (Mutex.shouldIgnore()) { 1804 return; 1805 } 1806 1807 LockData* LDat = FSet.findLockUniv(Analyzer->FactMan, Mutex); 1808 bool NoError = true; 1809 if (!LDat) { 1810 // No exact match found. Look for a partial match. 1811 FactEntry* FEntry = FSet.findPartialMatch(Analyzer->FactMan, Mutex); 1812 if (FEntry) { 1813 // Warn that there's no precise match. 1814 LDat = &FEntry->LDat; 1815 std::string PartMatchStr = FEntry->MutID.toString(); 1816 StringRef PartMatchName(PartMatchStr); 1817 Analyzer->Handler.handleMutexNotHeld(D, POK, Mutex.toString(), LK, 1818 Exp->getExprLoc(), &PartMatchName); 1819 } else { 1820 // Warn that there's no match at all. 1821 Analyzer->Handler.handleMutexNotHeld(D, POK, Mutex.toString(), LK, 1822 Exp->getExprLoc()); 1823 } 1824 NoError = false; 1825 } 1826 // Make sure the mutex we found is the right kind. 1827 if (NoError && LDat && !LDat->isAtLeast(LK)) 1828 Analyzer->Handler.handleMutexNotHeld(D, POK, Mutex.toString(), LK, 1829 Exp->getExprLoc()); 1830 } 1831 1832 /// \brief Warn if the LSet contains the given lock. 1833 void BuildLockset::warnIfMutexHeld(const NamedDecl *D, const Expr* Exp, 1834 Expr *MutexExp) { 1835 SExpr Mutex(MutexExp, Exp, D); 1836 if (!Mutex.isValid()) { 1837 SExpr::warnInvalidLock(Analyzer->Handler, MutexExp, Exp, D); 1838 return; 1839 } 1840 1841 LockData* LDat = FSet.findLock(Analyzer->FactMan, Mutex); 1842 if (LDat) { 1843 std::string DeclName = D->getNameAsString(); 1844 StringRef DeclNameSR (DeclName); 1845 Analyzer->Handler.handleFunExcludesLock(DeclNameSR, Mutex.toString(), 1846 Exp->getExprLoc()); 1847 } 1848 } 1849 1850 1851 /// \brief Checks guarded_by and pt_guarded_by attributes. 1852 /// Whenever we identify an access (read or write) to a DeclRefExpr that is 1853 /// marked with guarded_by, we must ensure the appropriate mutexes are held. 1854 /// Similarly, we check if the access is to an expression that dereferences 1855 /// a pointer marked with pt_guarded_by. 1856 void BuildLockset::checkAccess(const Expr *Exp, AccessKind AK) { 1857 Exp = Exp->IgnoreParenCasts(); 1858 1859 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(Exp)) { 1860 // For dereferences 1861 if (UO->getOpcode() == clang::UO_Deref) 1862 checkPtAccess(UO->getSubExpr(), AK); 1863 return; 1864 } 1865 1866 if (const ArraySubscriptExpr *AE = dyn_cast<ArraySubscriptExpr>(Exp)) { 1867 checkPtAccess(AE->getLHS(), AK); 1868 return; 1869 } 1870 1871 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Exp)) { 1872 if (ME->isArrow()) 1873 checkPtAccess(ME->getBase(), AK); 1874 else 1875 checkAccess(ME->getBase(), AK); 1876 } 1877 1878 const ValueDecl *D = getValueDecl(Exp); 1879 if (!D || !D->hasAttrs()) 1880 return; 1881 1882 if (D->hasAttr<GuardedVarAttr>() && FSet.isEmpty()) 1883 Analyzer->Handler.handleNoMutexHeld(D, POK_VarAccess, AK, 1884 Exp->getExprLoc()); 1885 1886 for (const auto *I : D->specific_attrs<GuardedByAttr>()) 1887 warnIfMutexNotHeld(D, Exp, AK, I->getArg(), POK_VarAccess); 1888 } 1889 1890 /// \brief Checks pt_guarded_by and pt_guarded_var attributes. 1891 void BuildLockset::checkPtAccess(const Expr *Exp, AccessKind AK) { 1892 while (true) { 1893 if (const ParenExpr *PE = dyn_cast<ParenExpr>(Exp)) { 1894 Exp = PE->getSubExpr(); 1895 continue; 1896 } 1897 if (const CastExpr *CE = dyn_cast<CastExpr>(Exp)) { 1898 if (CE->getCastKind() == CK_ArrayToPointerDecay) { 1899 // If it's an actual array, and not a pointer, then it's elements 1900 // are protected by GUARDED_BY, not PT_GUARDED_BY; 1901 checkAccess(CE->getSubExpr(), AK); 1902 return; 1903 } 1904 Exp = CE->getSubExpr(); 1905 continue; 1906 } 1907 break; 1908 } 1909 1910 const ValueDecl *D = getValueDecl(Exp); 1911 if (!D || !D->hasAttrs()) 1912 return; 1913 1914 if (D->hasAttr<PtGuardedVarAttr>() && FSet.isEmpty()) 1915 Analyzer->Handler.handleNoMutexHeld(D, POK_VarDereference, AK, 1916 Exp->getExprLoc()); 1917 1918 for (auto const *I : D->specific_attrs<PtGuardedByAttr>()) 1919 warnIfMutexNotHeld(D, Exp, AK, I->getArg(), POK_VarDereference); 1920 } 1921 1922 1923 /// \brief Process a function call, method call, constructor call, 1924 /// or destructor call. This involves looking at the attributes on the 1925 /// corresponding function/method/constructor/destructor, issuing warnings, 1926 /// and updating the locksets accordingly. 1927 /// 1928 /// FIXME: For classes annotated with one of the guarded annotations, we need 1929 /// to treat const method calls as reads and non-const method calls as writes, 1930 /// and check that the appropriate locks are held. Non-const method calls with 1931 /// the same signature as const method calls can be also treated as reads. 1932 /// 1933 void BuildLockset::handleCall(Expr *Exp, const NamedDecl *D, VarDecl *VD) { 1934 SourceLocation Loc = Exp->getExprLoc(); 1935 const AttrVec &ArgAttrs = D->getAttrs(); 1936 MutexIDList ExclusiveLocksToAdd, SharedLocksToAdd; 1937 MutexIDList ExclusiveLocksToRemove, SharedLocksToRemove, GenericLocksToRemove; 1938 1939 for(unsigned i = 0; i < ArgAttrs.size(); ++i) { 1940 Attr *At = const_cast<Attr*>(ArgAttrs[i]); 1941 switch (At->getKind()) { 1942 // When we encounter a lock function, we need to add the lock to our 1943 // lockset. 1944 case attr::AcquireCapability: { 1945 auto *A = cast<AcquireCapabilityAttr>(At); 1946 Analyzer->getMutexIDs(A->isShared() ? SharedLocksToAdd 1947 : ExclusiveLocksToAdd, 1948 A, Exp, D, VD); 1949 break; 1950 } 1951 1952 // An assert will add a lock to the lockset, but will not generate 1953 // a warning if it is already there, and will not generate a warning 1954 // if it is not removed. 1955 case attr::AssertExclusiveLock: { 1956 AssertExclusiveLockAttr *A = cast<AssertExclusiveLockAttr>(At); 1957 1958 MutexIDList AssertLocks; 1959 Analyzer->getMutexIDs(AssertLocks, A, Exp, D, VD); 1960 for (unsigned i=0,n=AssertLocks.size(); i<n; ++i) { 1961 Analyzer->addLock(FSet, AssertLocks[i], 1962 LockData(Loc, LK_Exclusive, false, true)); 1963 } 1964 break; 1965 } 1966 case attr::AssertSharedLock: { 1967 AssertSharedLockAttr *A = cast<AssertSharedLockAttr>(At); 1968 1969 MutexIDList AssertLocks; 1970 Analyzer->getMutexIDs(AssertLocks, A, Exp, D, VD); 1971 for (unsigned i=0,n=AssertLocks.size(); i<n; ++i) { 1972 Analyzer->addLock(FSet, AssertLocks[i], 1973 LockData(Loc, LK_Shared, false, true)); 1974 } 1975 break; 1976 } 1977 1978 // When we encounter an unlock function, we need to remove unlocked 1979 // mutexes from the lockset, and flag a warning if they are not there. 1980 case attr::ReleaseCapability: { 1981 auto *A = cast<ReleaseCapabilityAttr>(At); 1982 if (A->isGeneric()) 1983 Analyzer->getMutexIDs(GenericLocksToRemove, A, Exp, D, VD); 1984 else if (A->isShared()) 1985 Analyzer->getMutexIDs(SharedLocksToRemove, A, Exp, D, VD); 1986 else 1987 Analyzer->getMutexIDs(ExclusiveLocksToRemove, A, Exp, D, VD); 1988 break; 1989 } 1990 1991 case attr::RequiresCapability: { 1992 RequiresCapabilityAttr *A = cast<RequiresCapabilityAttr>(At); 1993 1994 for (RequiresCapabilityAttr::args_iterator I = A->args_begin(), 1995 E = A->args_end(); I != E; ++I) 1996 warnIfMutexNotHeld(D, Exp, A->isShared() ? AK_Read : AK_Written, *I, 1997 POK_FunctionCall); 1998 break; 1999 } 2000 2001 case attr::LocksExcluded: { 2002 LocksExcludedAttr *A = cast<LocksExcludedAttr>(At); 2003 2004 for (LocksExcludedAttr::args_iterator I = A->args_begin(), 2005 E = A->args_end(); I != E; ++I) { 2006 warnIfMutexHeld(D, Exp, *I); 2007 } 2008 break; 2009 } 2010 2011 // Ignore attributes unrelated to thread-safety 2012 default: 2013 break; 2014 } 2015 } 2016 2017 // Figure out if we're calling the constructor of scoped lockable class 2018 bool isScopedVar = false; 2019 if (VD) { 2020 if (const CXXConstructorDecl *CD = dyn_cast<const CXXConstructorDecl>(D)) { 2021 const CXXRecordDecl* PD = CD->getParent(); 2022 if (PD && PD->hasAttr<ScopedLockableAttr>()) 2023 isScopedVar = true; 2024 } 2025 } 2026 2027 // Add locks. 2028 for (const auto &M : ExclusiveLocksToAdd) 2029 Analyzer->addLock(FSet, M, LockData(Loc, LK_Exclusive, isScopedVar)); 2030 for (const auto &M : SharedLocksToAdd) 2031 Analyzer->addLock(FSet, M, LockData(Loc, LK_Shared, isScopedVar)); 2032 2033 // Add the managing object as a dummy mutex, mapped to the underlying mutex. 2034 // FIXME -- this doesn't work if we acquire multiple locks. 2035 if (isScopedVar) { 2036 SourceLocation MLoc = VD->getLocation(); 2037 DeclRefExpr DRE(VD, false, VD->getType(), VK_LValue, VD->getLocation()); 2038 SExpr SMutex(&DRE, 0, 0); 2039 2040 for (const auto &M : ExclusiveLocksToAdd) 2041 Analyzer->addLock(FSet, SMutex, LockData(MLoc, LK_Exclusive, M)); 2042 for (const auto &M : SharedLocksToAdd) 2043 Analyzer->addLock(FSet, SMutex, LockData(MLoc, LK_Shared, M)); 2044 } 2045 2046 // Remove locks. 2047 // FIXME -- should only fully remove if the attribute refers to 'this'. 2048 bool Dtor = isa<CXXDestructorDecl>(D); 2049 for (const auto &M : ExclusiveLocksToRemove) 2050 Analyzer->removeLock(FSet, M, Loc, Dtor, LK_Exclusive); 2051 for (const auto &M : SharedLocksToRemove) 2052 Analyzer->removeLock(FSet, M, Loc, Dtor, LK_Shared); 2053 for (const auto &M : GenericLocksToRemove) 2054 Analyzer->removeLock(FSet, M, Loc, Dtor, LK_Generic); 2055 } 2056 2057 2058 /// \brief For unary operations which read and write a variable, we need to 2059 /// check whether we hold any required mutexes. Reads are checked in 2060 /// VisitCastExpr. 2061 void BuildLockset::VisitUnaryOperator(UnaryOperator *UO) { 2062 switch (UO->getOpcode()) { 2063 case clang::UO_PostDec: 2064 case clang::UO_PostInc: 2065 case clang::UO_PreDec: 2066 case clang::UO_PreInc: { 2067 checkAccess(UO->getSubExpr(), AK_Written); 2068 break; 2069 } 2070 default: 2071 break; 2072 } 2073 } 2074 2075 /// For binary operations which assign to a variable (writes), we need to check 2076 /// whether we hold any required mutexes. 2077 /// FIXME: Deal with non-primitive types. 2078 void BuildLockset::VisitBinaryOperator(BinaryOperator *BO) { 2079 if (!BO->isAssignmentOp()) 2080 return; 2081 2082 // adjust the context 2083 LVarCtx = Analyzer->LocalVarMap.getNextContext(CtxIndex, BO, LVarCtx); 2084 2085 checkAccess(BO->getLHS(), AK_Written); 2086 } 2087 2088 2089 /// Whenever we do an LValue to Rvalue cast, we are reading a variable and 2090 /// need to ensure we hold any required mutexes. 2091 /// FIXME: Deal with non-primitive types. 2092 void BuildLockset::VisitCastExpr(CastExpr *CE) { 2093 if (CE->getCastKind() != CK_LValueToRValue) 2094 return; 2095 checkAccess(CE->getSubExpr(), AK_Read); 2096 } 2097 2098 2099 void BuildLockset::VisitCallExpr(CallExpr *Exp) { 2100 if (CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Exp)) { 2101 MemberExpr *ME = dyn_cast<MemberExpr>(CE->getCallee()); 2102 // ME can be null when calling a method pointer 2103 CXXMethodDecl *MD = CE->getMethodDecl(); 2104 2105 if (ME && MD) { 2106 if (ME->isArrow()) { 2107 if (MD->isConst()) { 2108 checkPtAccess(CE->getImplicitObjectArgument(), AK_Read); 2109 } else { // FIXME -- should be AK_Written 2110 checkPtAccess(CE->getImplicitObjectArgument(), AK_Read); 2111 } 2112 } else { 2113 if (MD->isConst()) 2114 checkAccess(CE->getImplicitObjectArgument(), AK_Read); 2115 else // FIXME -- should be AK_Written 2116 checkAccess(CE->getImplicitObjectArgument(), AK_Read); 2117 } 2118 } 2119 } else if (CXXOperatorCallExpr *OE = dyn_cast<CXXOperatorCallExpr>(Exp)) { 2120 switch (OE->getOperator()) { 2121 case OO_Equal: { 2122 const Expr *Target = OE->getArg(0); 2123 const Expr *Source = OE->getArg(1); 2124 checkAccess(Target, AK_Written); 2125 checkAccess(Source, AK_Read); 2126 break; 2127 } 2128 case OO_Star: 2129 case OO_Arrow: 2130 case OO_Subscript: { 2131 const Expr *Obj = OE->getArg(0); 2132 checkAccess(Obj, AK_Read); 2133 checkPtAccess(Obj, AK_Read); 2134 break; 2135 } 2136 default: { 2137 const Expr *Obj = OE->getArg(0); 2138 checkAccess(Obj, AK_Read); 2139 break; 2140 } 2141 } 2142 } 2143 NamedDecl *D = dyn_cast_or_null<NamedDecl>(Exp->getCalleeDecl()); 2144 if(!D || !D->hasAttrs()) 2145 return; 2146 handleCall(Exp, D); 2147 } 2148 2149 void BuildLockset::VisitCXXConstructExpr(CXXConstructExpr *Exp) { 2150 const CXXConstructorDecl *D = Exp->getConstructor(); 2151 if (D && D->isCopyConstructor()) { 2152 const Expr* Source = Exp->getArg(0); 2153 checkAccess(Source, AK_Read); 2154 } 2155 // FIXME -- only handles constructors in DeclStmt below. 2156 } 2157 2158 void BuildLockset::VisitDeclStmt(DeclStmt *S) { 2159 // adjust the context 2160 LVarCtx = Analyzer->LocalVarMap.getNextContext(CtxIndex, S, LVarCtx); 2161 2162 DeclGroupRef DGrp = S->getDeclGroup(); 2163 for (DeclGroupRef::iterator I = DGrp.begin(), E = DGrp.end(); I != E; ++I) { 2164 Decl *D = *I; 2165 if (VarDecl *VD = dyn_cast_or_null<VarDecl>(D)) { 2166 Expr *E = VD->getInit(); 2167 // handle constructors that involve temporaries 2168 if (ExprWithCleanups *EWC = dyn_cast_or_null<ExprWithCleanups>(E)) 2169 E = EWC->getSubExpr(); 2170 2171 if (CXXConstructExpr *CE = dyn_cast_or_null<CXXConstructExpr>(E)) { 2172 NamedDecl *CtorD = dyn_cast_or_null<NamedDecl>(CE->getConstructor()); 2173 if (!CtorD || !CtorD->hasAttrs()) 2174 return; 2175 handleCall(CE, CtorD, VD); 2176 } 2177 } 2178 } 2179 } 2180 2181 2182 2183 /// \brief Compute the intersection of two locksets and issue warnings for any 2184 /// locks in the symmetric difference. 2185 /// 2186 /// This function is used at a merge point in the CFG when comparing the lockset 2187 /// of each branch being merged. For example, given the following sequence: 2188 /// A; if () then B; else C; D; we need to check that the lockset after B and C 2189 /// are the same. In the event of a difference, we use the intersection of these 2190 /// two locksets at the start of D. 2191 /// 2192 /// \param FSet1 The first lockset. 2193 /// \param FSet2 The second lockset. 2194 /// \param JoinLoc The location of the join point for error reporting 2195 /// \param LEK1 The error message to report if a mutex is missing from LSet1 2196 /// \param LEK2 The error message to report if a mutex is missing from Lset2 2197 void ThreadSafetyAnalyzer::intersectAndWarn(FactSet &FSet1, 2198 const FactSet &FSet2, 2199 SourceLocation JoinLoc, 2200 LockErrorKind LEK1, 2201 LockErrorKind LEK2, 2202 bool Modify) { 2203 FactSet FSet1Orig = FSet1; 2204 2205 // Find locks in FSet2 that conflict or are not in FSet1, and warn. 2206 for (FactSet::const_iterator I = FSet2.begin(), E = FSet2.end(); 2207 I != E; ++I) { 2208 const SExpr &FSet2Mutex = FactMan[*I].MutID; 2209 const LockData &LDat2 = FactMan[*I].LDat; 2210 FactSet::iterator I1 = FSet1.findLockIter(FactMan, FSet2Mutex); 2211 2212 if (I1 != FSet1.end()) { 2213 const LockData* LDat1 = &FactMan[*I1].LDat; 2214 if (LDat1->LKind != LDat2.LKind) { 2215 Handler.handleExclusiveAndShared(FSet2Mutex.toString(), 2216 LDat2.AcquireLoc, 2217 LDat1->AcquireLoc); 2218 if (Modify && LDat1->LKind != LK_Exclusive) { 2219 // Take the exclusive lock, which is the one in FSet2. 2220 *I1 = *I; 2221 } 2222 } 2223 else if (LDat1->Asserted && !LDat2.Asserted) { 2224 // The non-asserted lock in FSet2 is the one we want to track. 2225 *I1 = *I; 2226 } 2227 } else { 2228 if (LDat2.UnderlyingMutex.isValid()) { 2229 if (FSet2.findLock(FactMan, LDat2.UnderlyingMutex)) { 2230 // If this is a scoped lock that manages another mutex, and if the 2231 // underlying mutex is still held, then warn about the underlying 2232 // mutex. 2233 Handler.handleMutexHeldEndOfScope(LDat2.UnderlyingMutex.toString(), 2234 LDat2.AcquireLoc, 2235 JoinLoc, LEK1); 2236 } 2237 } 2238 else if (!LDat2.Managed && !FSet2Mutex.isUniversal() && !LDat2.Asserted) 2239 Handler.handleMutexHeldEndOfScope(FSet2Mutex.toString(), 2240 LDat2.AcquireLoc, 2241 JoinLoc, LEK1); 2242 } 2243 } 2244 2245 // Find locks in FSet1 that are not in FSet2, and remove them. 2246 for (FactSet::const_iterator I = FSet1Orig.begin(), E = FSet1Orig.end(); 2247 I != E; ++I) { 2248 const SExpr &FSet1Mutex = FactMan[*I].MutID; 2249 const LockData &LDat1 = FactMan[*I].LDat; 2250 2251 if (!FSet2.findLock(FactMan, FSet1Mutex)) { 2252 if (LDat1.UnderlyingMutex.isValid()) { 2253 if (FSet1Orig.findLock(FactMan, LDat1.UnderlyingMutex)) { 2254 // If this is a scoped lock that manages another mutex, and if the 2255 // underlying mutex is still held, then warn about the underlying 2256 // mutex. 2257 Handler.handleMutexHeldEndOfScope(LDat1.UnderlyingMutex.toString(), 2258 LDat1.AcquireLoc, 2259 JoinLoc, LEK1); 2260 } 2261 } 2262 else if (!LDat1.Managed && !FSet1Mutex.isUniversal() && !LDat1.Asserted) 2263 Handler.handleMutexHeldEndOfScope(FSet1Mutex.toString(), 2264 LDat1.AcquireLoc, 2265 JoinLoc, LEK2); 2266 if (Modify) 2267 FSet1.removeLock(FactMan, FSet1Mutex); 2268 } 2269 } 2270 } 2271 2272 2273 // Return true if block B never continues to its successors. 2274 inline bool neverReturns(const CFGBlock* B) { 2275 if (B->hasNoReturnElement()) 2276 return true; 2277 if (B->empty()) 2278 return false; 2279 2280 CFGElement Last = B->back(); 2281 if (Optional<CFGStmt> S = Last.getAs<CFGStmt>()) { 2282 if (isa<CXXThrowExpr>(S->getStmt())) 2283 return true; 2284 } 2285 return false; 2286 } 2287 2288 2289 /// \brief Check a function's CFG for thread-safety violations. 2290 /// 2291 /// We traverse the blocks in the CFG, compute the set of mutexes that are held 2292 /// at the end of each block, and issue warnings for thread safety violations. 2293 /// Each block in the CFG is traversed exactly once. 2294 void ThreadSafetyAnalyzer::runAnalysis(AnalysisDeclContext &AC) { 2295 CFG *CFGraph = AC.getCFG(); 2296 if (!CFGraph) return; 2297 const NamedDecl *D = dyn_cast_or_null<NamedDecl>(AC.getDecl()); 2298 2299 // AC.dumpCFG(true); 2300 2301 if (!D) 2302 return; // Ignore anonymous functions for now. 2303 if (D->hasAttr<NoThreadSafetyAnalysisAttr>()) 2304 return; 2305 // FIXME: Do something a bit more intelligent inside constructor and 2306 // destructor code. Constructors and destructors must assume unique access 2307 // to 'this', so checks on member variable access is disabled, but we should 2308 // still enable checks on other objects. 2309 if (isa<CXXConstructorDecl>(D)) 2310 return; // Don't check inside constructors. 2311 if (isa<CXXDestructorDecl>(D)) 2312 return; // Don't check inside destructors. 2313 2314 BlockInfo.resize(CFGraph->getNumBlockIDs(), 2315 CFGBlockInfo::getEmptyBlockInfo(LocalVarMap)); 2316 2317 // We need to explore the CFG via a "topological" ordering. 2318 // That way, we will be guaranteed to have information about required 2319 // predecessor locksets when exploring a new block. 2320 PostOrderCFGView *SortedGraph = AC.getAnalysis<PostOrderCFGView>(); 2321 PostOrderCFGView::CFGBlockSet VisitedBlocks(CFGraph); 2322 2323 // Mark entry block as reachable 2324 BlockInfo[CFGraph->getEntry().getBlockID()].Reachable = true; 2325 2326 // Compute SSA names for local variables 2327 LocalVarMap.traverseCFG(CFGraph, SortedGraph, BlockInfo); 2328 2329 // Fill in source locations for all CFGBlocks. 2330 findBlockLocations(CFGraph, SortedGraph, BlockInfo); 2331 2332 MutexIDList ExclusiveLocksAcquired; 2333 MutexIDList SharedLocksAcquired; 2334 MutexIDList LocksReleased; 2335 2336 // Add locks from exclusive_locks_required and shared_locks_required 2337 // to initial lockset. Also turn off checking for lock and unlock functions. 2338 // FIXME: is there a more intelligent way to check lock/unlock functions? 2339 if (!SortedGraph->empty() && D->hasAttrs()) { 2340 const CFGBlock *FirstBlock = *SortedGraph->begin(); 2341 FactSet &InitialLockset = BlockInfo[FirstBlock->getBlockID()].EntrySet; 2342 const AttrVec &ArgAttrs = D->getAttrs(); 2343 2344 MutexIDList ExclusiveLocksToAdd; 2345 MutexIDList SharedLocksToAdd; 2346 2347 SourceLocation Loc = D->getLocation(); 2348 for (unsigned i = 0; i < ArgAttrs.size(); ++i) { 2349 Attr *Attr = ArgAttrs[i]; 2350 Loc = Attr->getLocation(); 2351 if (RequiresCapabilityAttr *A = dyn_cast<RequiresCapabilityAttr>(Attr)) { 2352 getMutexIDs(A->isShared() ? SharedLocksToAdd : ExclusiveLocksToAdd, A, 2353 0, D); 2354 } else if (auto *A = dyn_cast<ReleaseCapabilityAttr>(Attr)) { 2355 // UNLOCK_FUNCTION() is used to hide the underlying lock implementation. 2356 // We must ignore such methods. 2357 if (A->args_size() == 0) 2358 return; 2359 // FIXME -- deal with exclusive vs. shared unlock functions? 2360 getMutexIDs(ExclusiveLocksToAdd, A, (Expr*) 0, D); 2361 getMutexIDs(LocksReleased, A, (Expr*) 0, D); 2362 } else if (auto *A = dyn_cast<AcquireCapabilityAttr>(Attr)) { 2363 if (A->args_size() == 0) 2364 return; 2365 getMutexIDs(A->isShared() ? SharedLocksAcquired 2366 : ExclusiveLocksAcquired, 2367 A, nullptr, D); 2368 } else if (isa<ExclusiveTrylockFunctionAttr>(Attr)) { 2369 // Don't try to check trylock functions for now 2370 return; 2371 } else if (isa<SharedTrylockFunctionAttr>(Attr)) { 2372 // Don't try to check trylock functions for now 2373 return; 2374 } 2375 } 2376 2377 // FIXME -- Loc can be wrong here. 2378 for (unsigned i=0,n=ExclusiveLocksToAdd.size(); i<n; ++i) { 2379 addLock(InitialLockset, ExclusiveLocksToAdd[i], 2380 LockData(Loc, LK_Exclusive)); 2381 } 2382 for (unsigned i=0,n=SharedLocksToAdd.size(); i<n; ++i) { 2383 addLock(InitialLockset, SharedLocksToAdd[i], 2384 LockData(Loc, LK_Shared)); 2385 } 2386 } 2387 2388 for (PostOrderCFGView::iterator I = SortedGraph->begin(), 2389 E = SortedGraph->end(); I!= E; ++I) { 2390 const CFGBlock *CurrBlock = *I; 2391 int CurrBlockID = CurrBlock->getBlockID(); 2392 CFGBlockInfo *CurrBlockInfo = &BlockInfo[CurrBlockID]; 2393 2394 // Use the default initial lockset in case there are no predecessors. 2395 VisitedBlocks.insert(CurrBlock); 2396 2397 // Iterate through the predecessor blocks and warn if the lockset for all 2398 // predecessors is not the same. We take the entry lockset of the current 2399 // block to be the intersection of all previous locksets. 2400 // FIXME: By keeping the intersection, we may output more errors in future 2401 // for a lock which is not in the intersection, but was in the union. We 2402 // may want to also keep the union in future. As an example, let's say 2403 // the intersection contains Mutex L, and the union contains L and M. 2404 // Later we unlock M. At this point, we would output an error because we 2405 // never locked M; although the real error is probably that we forgot to 2406 // lock M on all code paths. Conversely, let's say that later we lock M. 2407 // In this case, we should compare against the intersection instead of the 2408 // union because the real error is probably that we forgot to unlock M on 2409 // all code paths. 2410 bool LocksetInitialized = false; 2411 SmallVector<CFGBlock *, 8> SpecialBlocks; 2412 for (CFGBlock::const_pred_iterator PI = CurrBlock->pred_begin(), 2413 PE = CurrBlock->pred_end(); PI != PE; ++PI) { 2414 2415 // if *PI -> CurrBlock is a back edge 2416 if (*PI == 0 || !VisitedBlocks.alreadySet(*PI)) 2417 continue; 2418 2419 int PrevBlockID = (*PI)->getBlockID(); 2420 CFGBlockInfo *PrevBlockInfo = &BlockInfo[PrevBlockID]; 2421 2422 // Ignore edges from blocks that can't return. 2423 if (neverReturns(*PI) || !PrevBlockInfo->Reachable) 2424 continue; 2425 2426 // Okay, we can reach this block from the entry. 2427 CurrBlockInfo->Reachable = true; 2428 2429 // If the previous block ended in a 'continue' or 'break' statement, then 2430 // a difference in locksets is probably due to a bug in that block, rather 2431 // than in some other predecessor. In that case, keep the other 2432 // predecessor's lockset. 2433 if (const Stmt *Terminator = (*PI)->getTerminator()) { 2434 if (isa<ContinueStmt>(Terminator) || isa<BreakStmt>(Terminator)) { 2435 SpecialBlocks.push_back(*PI); 2436 continue; 2437 } 2438 } 2439 2440 FactSet PrevLockset; 2441 getEdgeLockset(PrevLockset, PrevBlockInfo->ExitSet, *PI, CurrBlock); 2442 2443 if (!LocksetInitialized) { 2444 CurrBlockInfo->EntrySet = PrevLockset; 2445 LocksetInitialized = true; 2446 } else { 2447 intersectAndWarn(CurrBlockInfo->EntrySet, PrevLockset, 2448 CurrBlockInfo->EntryLoc, 2449 LEK_LockedSomePredecessors); 2450 } 2451 } 2452 2453 // Skip rest of block if it's not reachable. 2454 if (!CurrBlockInfo->Reachable) 2455 continue; 2456 2457 // Process continue and break blocks. Assume that the lockset for the 2458 // resulting block is unaffected by any discrepancies in them. 2459 for (unsigned SpecialI = 0, SpecialN = SpecialBlocks.size(); 2460 SpecialI < SpecialN; ++SpecialI) { 2461 CFGBlock *PrevBlock = SpecialBlocks[SpecialI]; 2462 int PrevBlockID = PrevBlock->getBlockID(); 2463 CFGBlockInfo *PrevBlockInfo = &BlockInfo[PrevBlockID]; 2464 2465 if (!LocksetInitialized) { 2466 CurrBlockInfo->EntrySet = PrevBlockInfo->ExitSet; 2467 LocksetInitialized = true; 2468 } else { 2469 // Determine whether this edge is a loop terminator for diagnostic 2470 // purposes. FIXME: A 'break' statement might be a loop terminator, but 2471 // it might also be part of a switch. Also, a subsequent destructor 2472 // might add to the lockset, in which case the real issue might be a 2473 // double lock on the other path. 2474 const Stmt *Terminator = PrevBlock->getTerminator(); 2475 bool IsLoop = Terminator && isa<ContinueStmt>(Terminator); 2476 2477 FactSet PrevLockset; 2478 getEdgeLockset(PrevLockset, PrevBlockInfo->ExitSet, 2479 PrevBlock, CurrBlock); 2480 2481 // Do not update EntrySet. 2482 intersectAndWarn(CurrBlockInfo->EntrySet, PrevLockset, 2483 PrevBlockInfo->ExitLoc, 2484 IsLoop ? LEK_LockedSomeLoopIterations 2485 : LEK_LockedSomePredecessors, 2486 false); 2487 } 2488 } 2489 2490 BuildLockset LocksetBuilder(this, *CurrBlockInfo); 2491 2492 // Visit all the statements in the basic block. 2493 for (CFGBlock::const_iterator BI = CurrBlock->begin(), 2494 BE = CurrBlock->end(); BI != BE; ++BI) { 2495 switch (BI->getKind()) { 2496 case CFGElement::Statement: { 2497 CFGStmt CS = BI->castAs<CFGStmt>(); 2498 LocksetBuilder.Visit(const_cast<Stmt*>(CS.getStmt())); 2499 break; 2500 } 2501 // Ignore BaseDtor, MemberDtor, and TemporaryDtor for now. 2502 case CFGElement::AutomaticObjectDtor: { 2503 CFGAutomaticObjDtor AD = BI->castAs<CFGAutomaticObjDtor>(); 2504 CXXDestructorDecl *DD = const_cast<CXXDestructorDecl *>( 2505 AD.getDestructorDecl(AC.getASTContext())); 2506 if (!DD->hasAttrs()) 2507 break; 2508 2509 // Create a dummy expression, 2510 VarDecl *VD = const_cast<VarDecl*>(AD.getVarDecl()); 2511 DeclRefExpr DRE(VD, false, VD->getType(), VK_LValue, 2512 AD.getTriggerStmt()->getLocEnd()); 2513 LocksetBuilder.handleCall(&DRE, DD); 2514 break; 2515 } 2516 default: 2517 break; 2518 } 2519 } 2520 CurrBlockInfo->ExitSet = LocksetBuilder.FSet; 2521 2522 // For every back edge from CurrBlock (the end of the loop) to another block 2523 // (FirstLoopBlock) we need to check that the Lockset of Block is equal to 2524 // the one held at the beginning of FirstLoopBlock. We can look up the 2525 // Lockset held at the beginning of FirstLoopBlock in the EntryLockSets map. 2526 for (CFGBlock::const_succ_iterator SI = CurrBlock->succ_begin(), 2527 SE = CurrBlock->succ_end(); SI != SE; ++SI) { 2528 2529 // if CurrBlock -> *SI is *not* a back edge 2530 if (*SI == 0 || !VisitedBlocks.alreadySet(*SI)) 2531 continue; 2532 2533 CFGBlock *FirstLoopBlock = *SI; 2534 CFGBlockInfo *PreLoop = &BlockInfo[FirstLoopBlock->getBlockID()]; 2535 CFGBlockInfo *LoopEnd = &BlockInfo[CurrBlockID]; 2536 intersectAndWarn(LoopEnd->ExitSet, PreLoop->EntrySet, 2537 PreLoop->EntryLoc, 2538 LEK_LockedSomeLoopIterations, 2539 false); 2540 } 2541 } 2542 2543 CFGBlockInfo *Initial = &BlockInfo[CFGraph->getEntry().getBlockID()]; 2544 CFGBlockInfo *Final = &BlockInfo[CFGraph->getExit().getBlockID()]; 2545 2546 // Skip the final check if the exit block is unreachable. 2547 if (!Final->Reachable) 2548 return; 2549 2550 // By default, we expect all locks held on entry to be held on exit. 2551 FactSet ExpectedExitSet = Initial->EntrySet; 2552 2553 // Adjust the expected exit set by adding or removing locks, as declared 2554 // by *-LOCK_FUNCTION and UNLOCK_FUNCTION. The intersect below will then 2555 // issue the appropriate warning. 2556 // FIXME: the location here is not quite right. 2557 for (unsigned i=0,n=ExclusiveLocksAcquired.size(); i<n; ++i) { 2558 ExpectedExitSet.addLock(FactMan, ExclusiveLocksAcquired[i], 2559 LockData(D->getLocation(), LK_Exclusive)); 2560 } 2561 for (unsigned i=0,n=SharedLocksAcquired.size(); i<n; ++i) { 2562 ExpectedExitSet.addLock(FactMan, SharedLocksAcquired[i], 2563 LockData(D->getLocation(), LK_Shared)); 2564 } 2565 for (unsigned i=0,n=LocksReleased.size(); i<n; ++i) { 2566 ExpectedExitSet.removeLock(FactMan, LocksReleased[i]); 2567 } 2568 2569 // FIXME: Should we call this function for all blocks which exit the function? 2570 intersectAndWarn(ExpectedExitSet, Final->ExitSet, 2571 Final->ExitLoc, 2572 LEK_LockedAtEndOfFunction, 2573 LEK_NotLockedAtEndOfFunction, 2574 false); 2575 } 2576 2577 } // end anonymous namespace 2578 2579 2580 namespace clang { 2581 namespace thread_safety { 2582 2583 /// \brief Check a function's CFG for thread-safety violations. 2584 /// 2585 /// We traverse the blocks in the CFG, compute the set of mutexes that are held 2586 /// at the end of each block, and issue warnings for thread safety violations. 2587 /// Each block in the CFG is traversed exactly once. 2588 void runThreadSafetyAnalysis(AnalysisDeclContext &AC, 2589 ThreadSafetyHandler &Handler) { 2590 ThreadSafetyAnalyzer Analyzer(Handler); 2591 Analyzer.runAnalysis(AC); 2592 } 2593 2594 /// \brief Helper function that returns a LockKind required for the given level 2595 /// of access. 2596 LockKind getLockKindFromAccessKind(AccessKind AK) { 2597 switch (AK) { 2598 case AK_Read : 2599 return LK_Shared; 2600 case AK_Written : 2601 return LK_Exclusive; 2602 } 2603 llvm_unreachable("Unknown AccessKind"); 2604 } 2605 2606 }} // end namespace clang::thread_safety 2607