1 //===- ThreadSafetyCommon.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 // Implementation of the interfaces declared in ThreadSafetyCommon.h 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "clang/Analysis/Analyses/ThreadSafetyCommon.h" 15 #include "clang/AST/Attr.h" 16 #include "clang/AST/DeclCXX.h" 17 #include "clang/AST/DeclObjC.h" 18 #include "clang/AST/ExprCXX.h" 19 #include "clang/AST/StmtCXX.h" 20 #include "clang/Analysis/Analyses/PostOrderCFGView.h" 21 #include "clang/Analysis/Analyses/ThreadSafetyTIL.h" 22 #include "clang/Analysis/Analyses/ThreadSafetyTraverse.h" 23 #include "clang/Analysis/AnalysisContext.h" 24 #include "clang/Analysis/CFG.h" 25 #include "clang/Basic/OperatorKinds.h" 26 #include "clang/Basic/SourceLocation.h" 27 #include "clang/Basic/SourceManager.h" 28 #include "llvm/ADT/DenseMap.h" 29 #include "llvm/ADT/SmallVector.h" 30 #include "llvm/ADT/StringRef.h" 31 #include <algorithm> 32 #include <climits> 33 #include <vector> 34 35 36 namespace clang { 37 namespace threadSafety { 38 39 // From ThreadSafetyUtil.h 40 std::string getSourceLiteralString(const clang::Expr *CE) { 41 switch (CE->getStmtClass()) { 42 case Stmt::IntegerLiteralClass: 43 return cast<IntegerLiteral>(CE)->getValue().toString(10, true); 44 case Stmt::StringLiteralClass: { 45 std::string ret("\""); 46 ret += cast<StringLiteral>(CE)->getString(); 47 ret += "\""; 48 return ret; 49 } 50 case Stmt::CharacterLiteralClass: 51 case Stmt::CXXNullPtrLiteralExprClass: 52 case Stmt::GNUNullExprClass: 53 case Stmt::CXXBoolLiteralExprClass: 54 case Stmt::FloatingLiteralClass: 55 case Stmt::ImaginaryLiteralClass: 56 case Stmt::ObjCStringLiteralClass: 57 default: 58 return "#lit"; 59 } 60 } 61 62 namespace til { 63 64 // Return true if E is a variable that points to an incomplete Phi node. 65 static bool isIncompletePhi(const SExpr *E) { 66 if (const auto *Ph = dyn_cast<Phi>(E)) 67 return Ph->status() == Phi::PH_Incomplete; 68 return false; 69 } 70 71 } // end namespace til 72 73 74 typedef SExprBuilder::CallingContext CallingContext; 75 76 77 til::SExpr *SExprBuilder::lookupStmt(const Stmt *S) { 78 auto It = SMap.find(S); 79 if (It != SMap.end()) 80 return It->second; 81 return nullptr; 82 } 83 84 85 til::SCFG *SExprBuilder::buildCFG(CFGWalker &Walker) { 86 Walker.walk(*this); 87 return Scfg; 88 } 89 90 91 92 inline bool isCalleeArrow(const Expr *E) { 93 const MemberExpr *ME = dyn_cast<MemberExpr>(E->IgnoreParenCasts()); 94 return ME ? ME->isArrow() : false; 95 } 96 97 98 /// \brief Translate a clang expression in an attribute to a til::SExpr. 99 /// Constructs the context from D, DeclExp, and SelfDecl. 100 /// 101 /// \param AttrExp The expression to translate. 102 /// \param D The declaration to which the attribute is attached. 103 /// \param DeclExp An expression involving the Decl to which the attribute 104 /// is attached. E.g. the call to a function. 105 CapabilityExpr SExprBuilder::translateAttrExpr(const Expr *AttrExp, 106 const NamedDecl *D, 107 const Expr *DeclExp, 108 VarDecl *SelfDecl) { 109 // If we are processing a raw attribute expression, with no substitutions. 110 if (!DeclExp) 111 return translateAttrExpr(AttrExp, nullptr); 112 113 CallingContext Ctx(nullptr, D); 114 115 // Examine DeclExp to find SelfArg and FunArgs, which are used to substitute 116 // for formal parameters when we call buildMutexID later. 117 if (const MemberExpr *ME = dyn_cast<MemberExpr>(DeclExp)) { 118 Ctx.SelfArg = ME->getBase(); 119 Ctx.SelfArrow = ME->isArrow(); 120 } else if (const CXXMemberCallExpr *CE = 121 dyn_cast<CXXMemberCallExpr>(DeclExp)) { 122 Ctx.SelfArg = CE->getImplicitObjectArgument(); 123 Ctx.SelfArrow = isCalleeArrow(CE->getCallee()); 124 Ctx.NumArgs = CE->getNumArgs(); 125 Ctx.FunArgs = CE->getArgs(); 126 } else if (const CallExpr *CE = dyn_cast<CallExpr>(DeclExp)) { 127 Ctx.NumArgs = CE->getNumArgs(); 128 Ctx.FunArgs = CE->getArgs(); 129 } else if (const CXXConstructExpr *CE = 130 dyn_cast<CXXConstructExpr>(DeclExp)) { 131 Ctx.SelfArg = nullptr; // Will be set below 132 Ctx.NumArgs = CE->getNumArgs(); 133 Ctx.FunArgs = CE->getArgs(); 134 } else if (D && isa<CXXDestructorDecl>(D)) { 135 // There's no such thing as a "destructor call" in the AST. 136 Ctx.SelfArg = DeclExp; 137 } 138 139 // Hack to handle constructors, where self cannot be recovered from 140 // the expression. 141 if (SelfDecl && !Ctx.SelfArg) { 142 DeclRefExpr SelfDRE(SelfDecl, false, SelfDecl->getType(), VK_LValue, 143 SelfDecl->getLocation()); 144 Ctx.SelfArg = &SelfDRE; 145 146 // If the attribute has no arguments, then assume the argument is "this". 147 if (!AttrExp) 148 return translateAttrExpr(Ctx.SelfArg, nullptr); 149 else // For most attributes. 150 return translateAttrExpr(AttrExp, &Ctx); 151 } 152 153 // If the attribute has no arguments, then assume the argument is "this". 154 if (!AttrExp) 155 return translateAttrExpr(Ctx.SelfArg, nullptr); 156 else // For most attributes. 157 return translateAttrExpr(AttrExp, &Ctx); 158 } 159 160 161 /// \brief Translate a clang expression in an attribute to a til::SExpr. 162 // This assumes a CallingContext has already been created. 163 CapabilityExpr SExprBuilder::translateAttrExpr(const Expr *AttrExp, 164 CallingContext *Ctx) { 165 if (!AttrExp) 166 return CapabilityExpr(nullptr, false); 167 168 if (auto* SLit = dyn_cast<StringLiteral>(AttrExp)) { 169 if (SLit->getString() == StringRef("*")) 170 // The "*" expr is a universal lock, which essentially turns off 171 // checks until it is removed from the lockset. 172 return CapabilityExpr(new (Arena) til::Wildcard(), false); 173 else 174 // Ignore other string literals for now. 175 return CapabilityExpr(nullptr, false); 176 } 177 178 bool Neg = false; 179 if (auto *OE = dyn_cast<CXXOperatorCallExpr>(AttrExp)) { 180 if (OE->getOperator() == OO_Exclaim) { 181 Neg = true; 182 AttrExp = OE->getArg(0); 183 } 184 } 185 else if (auto *UO = dyn_cast<UnaryOperator>(AttrExp)) { 186 if (UO->getOpcode() == UO_LNot) { 187 Neg = true; 188 AttrExp = UO->getSubExpr(); 189 } 190 } 191 192 til::SExpr *E = translate(AttrExp, Ctx); 193 194 // Trap mutex expressions like nullptr, or 0. 195 // Any literal value is nonsense. 196 if (!E || isa<til::Literal>(E)) 197 return CapabilityExpr(nullptr, false); 198 199 // Hack to deal with smart pointers -- strip off top-level pointer casts. 200 if (auto *CE = dyn_cast_or_null<til::Cast>(E)) { 201 if (CE->castOpcode() == til::CAST_objToPtr) 202 return CapabilityExpr(CE->expr(), Neg); 203 } 204 return CapabilityExpr(E, Neg); 205 } 206 207 208 209 // Translate a clang statement or expression to a TIL expression. 210 // Also performs substitution of variables; Ctx provides the context. 211 // Dispatches on the type of S. 212 til::SExpr *SExprBuilder::translate(const Stmt *S, CallingContext *Ctx) { 213 if (!S) 214 return nullptr; 215 216 // Check if S has already been translated and cached. 217 // This handles the lookup of SSA names for DeclRefExprs here. 218 if (til::SExpr *E = lookupStmt(S)) 219 return E; 220 221 switch (S->getStmtClass()) { 222 case Stmt::DeclRefExprClass: 223 return translateDeclRefExpr(cast<DeclRefExpr>(S), Ctx); 224 case Stmt::CXXThisExprClass: 225 return translateCXXThisExpr(cast<CXXThisExpr>(S), Ctx); 226 case Stmt::MemberExprClass: 227 return translateMemberExpr(cast<MemberExpr>(S), Ctx); 228 case Stmt::CallExprClass: 229 return translateCallExpr(cast<CallExpr>(S), Ctx); 230 case Stmt::CXXMemberCallExprClass: 231 return translateCXXMemberCallExpr(cast<CXXMemberCallExpr>(S), Ctx); 232 case Stmt::CXXOperatorCallExprClass: 233 return translateCXXOperatorCallExpr(cast<CXXOperatorCallExpr>(S), Ctx); 234 case Stmt::UnaryOperatorClass: 235 return translateUnaryOperator(cast<UnaryOperator>(S), Ctx); 236 case Stmt::BinaryOperatorClass: 237 case Stmt::CompoundAssignOperatorClass: 238 return translateBinaryOperator(cast<BinaryOperator>(S), Ctx); 239 240 case Stmt::ArraySubscriptExprClass: 241 return translateArraySubscriptExpr(cast<ArraySubscriptExpr>(S), Ctx); 242 case Stmt::ConditionalOperatorClass: 243 return translateAbstractConditionalOperator( 244 cast<ConditionalOperator>(S), Ctx); 245 case Stmt::BinaryConditionalOperatorClass: 246 return translateAbstractConditionalOperator( 247 cast<BinaryConditionalOperator>(S), Ctx); 248 249 // We treat these as no-ops 250 case Stmt::ParenExprClass: 251 return translate(cast<ParenExpr>(S)->getSubExpr(), Ctx); 252 case Stmt::ExprWithCleanupsClass: 253 return translate(cast<ExprWithCleanups>(S)->getSubExpr(), Ctx); 254 case Stmt::CXXBindTemporaryExprClass: 255 return translate(cast<CXXBindTemporaryExpr>(S)->getSubExpr(), Ctx); 256 257 // Collect all literals 258 case Stmt::CharacterLiteralClass: 259 case Stmt::CXXNullPtrLiteralExprClass: 260 case Stmt::GNUNullExprClass: 261 case Stmt::CXXBoolLiteralExprClass: 262 case Stmt::FloatingLiteralClass: 263 case Stmt::ImaginaryLiteralClass: 264 case Stmt::IntegerLiteralClass: 265 case Stmt::StringLiteralClass: 266 case Stmt::ObjCStringLiteralClass: 267 return new (Arena) til::Literal(cast<Expr>(S)); 268 269 case Stmt::DeclStmtClass: 270 return translateDeclStmt(cast<DeclStmt>(S), Ctx); 271 default: 272 break; 273 } 274 if (const CastExpr *CE = dyn_cast<CastExpr>(S)) 275 return translateCastExpr(CE, Ctx); 276 277 return new (Arena) til::Undefined(S); 278 } 279 280 281 282 til::SExpr *SExprBuilder::translateDeclRefExpr(const DeclRefExpr *DRE, 283 CallingContext *Ctx) { 284 const ValueDecl *VD = cast<ValueDecl>(DRE->getDecl()->getCanonicalDecl()); 285 286 // Function parameters require substitution and/or renaming. 287 if (const ParmVarDecl *PV = dyn_cast_or_null<ParmVarDecl>(VD)) { 288 const FunctionDecl *FD = 289 cast<FunctionDecl>(PV->getDeclContext())->getCanonicalDecl(); 290 unsigned I = PV->getFunctionScopeIndex(); 291 292 if (Ctx && Ctx->FunArgs && FD == Ctx->AttrDecl->getCanonicalDecl()) { 293 // Substitute call arguments for references to function parameters 294 assert(I < Ctx->NumArgs); 295 return translate(Ctx->FunArgs[I], Ctx->Prev); 296 } 297 // Map the param back to the param of the original function declaration 298 // for consistent comparisons. 299 VD = FD->getParamDecl(I); 300 } 301 302 // For non-local variables, treat it as a referenced to a named object. 303 return new (Arena) til::LiteralPtr(VD); 304 } 305 306 307 til::SExpr *SExprBuilder::translateCXXThisExpr(const CXXThisExpr *TE, 308 CallingContext *Ctx) { 309 // Substitute for 'this' 310 if (Ctx && Ctx->SelfArg) 311 return translate(Ctx->SelfArg, Ctx->Prev); 312 assert(SelfVar && "We have no variable for 'this'!"); 313 return SelfVar; 314 } 315 316 317 const ValueDecl *getValueDeclFromSExpr(const til::SExpr *E) { 318 if (auto *V = dyn_cast<til::Variable>(E)) 319 return V->clangDecl(); 320 if (auto *Ph = dyn_cast<til::Phi>(E)) 321 return Ph->clangDecl(); 322 if (auto *P = dyn_cast<til::Project>(E)) 323 return P->clangDecl(); 324 if (auto *L = dyn_cast<til::LiteralPtr>(E)) 325 return L->clangDecl(); 326 return 0; 327 } 328 329 bool hasCppPointerType(const til::SExpr *E) { 330 auto *VD = getValueDeclFromSExpr(E); 331 if (VD && VD->getType()->isPointerType()) 332 return true; 333 if (auto *C = dyn_cast<til::Cast>(E)) 334 return C->castOpcode() == til::CAST_objToPtr; 335 336 return false; 337 } 338 339 340 // Grab the very first declaration of virtual method D 341 const CXXMethodDecl* getFirstVirtualDecl(const CXXMethodDecl *D) { 342 while (true) { 343 D = D->getCanonicalDecl(); 344 CXXMethodDecl::method_iterator I = D->begin_overridden_methods(), 345 E = D->end_overridden_methods(); 346 if (I == E) 347 return D; // Method does not override anything 348 D = *I; // FIXME: this does not work with multiple inheritance. 349 } 350 return nullptr; 351 } 352 353 til::SExpr *SExprBuilder::translateMemberExpr(const MemberExpr *ME, 354 CallingContext *Ctx) { 355 til::SExpr *BE = translate(ME->getBase(), Ctx); 356 til::SExpr *E = new (Arena) til::SApply(BE); 357 358 const ValueDecl *D = ME->getMemberDecl(); 359 if (auto *VD = dyn_cast<CXXMethodDecl>(D)) 360 D = getFirstVirtualDecl(VD); 361 362 til::Project *P = new (Arena) til::Project(E, D); 363 if (hasCppPointerType(BE)) 364 P->setArrow(true); 365 return P; 366 } 367 368 369 til::SExpr *SExprBuilder::translateCallExpr(const CallExpr *CE, 370 CallingContext *Ctx, 371 const Expr *SelfE) { 372 if (CapabilityExprMode) { 373 // Handle LOCK_RETURNED 374 const FunctionDecl *FD = CE->getDirectCallee()->getMostRecentDecl(); 375 if (LockReturnedAttr* At = FD->getAttr<LockReturnedAttr>()) { 376 CallingContext LRCallCtx(Ctx); 377 LRCallCtx.AttrDecl = CE->getDirectCallee(); 378 LRCallCtx.SelfArg = SelfE; 379 LRCallCtx.NumArgs = CE->getNumArgs(); 380 LRCallCtx.FunArgs = CE->getArgs(); 381 return const_cast<til::SExpr*>( 382 translateAttrExpr(At->getArg(), &LRCallCtx).sexpr()); 383 } 384 } 385 386 til::SExpr *E = translate(CE->getCallee(), Ctx); 387 for (const auto *Arg : CE->arguments()) { 388 til::SExpr *A = translate(Arg, Ctx); 389 E = new (Arena) til::Apply(E, A); 390 } 391 return new (Arena) til::Call(E, CE); 392 } 393 394 395 til::SExpr *SExprBuilder::translateCXXMemberCallExpr( 396 const CXXMemberCallExpr *ME, CallingContext *Ctx) { 397 if (CapabilityExprMode) { 398 // Ignore calls to get() on smart pointers. 399 if (ME->getMethodDecl()->getNameAsString() == "get" && 400 ME->getNumArgs() == 0) { 401 auto *E = translate(ME->getImplicitObjectArgument(), Ctx); 402 return new (Arena) til::Cast(til::CAST_objToPtr, E); 403 // return E; 404 } 405 } 406 return translateCallExpr(cast<CallExpr>(ME), Ctx, 407 ME->getImplicitObjectArgument()); 408 } 409 410 411 til::SExpr *SExprBuilder::translateCXXOperatorCallExpr( 412 const CXXOperatorCallExpr *OCE, CallingContext *Ctx) { 413 if (CapabilityExprMode) { 414 // Ignore operator * and operator -> on smart pointers. 415 OverloadedOperatorKind k = OCE->getOperator(); 416 if (k == OO_Star || k == OO_Arrow) { 417 auto *E = translate(OCE->getArg(0), Ctx); 418 return new (Arena) til::Cast(til::CAST_objToPtr, E); 419 // return E; 420 } 421 } 422 return translateCallExpr(cast<CallExpr>(OCE), Ctx); 423 } 424 425 426 til::SExpr *SExprBuilder::translateUnaryOperator(const UnaryOperator *UO, 427 CallingContext *Ctx) { 428 switch (UO->getOpcode()) { 429 case UO_PostInc: 430 case UO_PostDec: 431 case UO_PreInc: 432 case UO_PreDec: 433 return new (Arena) til::Undefined(UO); 434 435 case UO_AddrOf: { 436 if (CapabilityExprMode) { 437 // interpret &Graph::mu_ as an existential. 438 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(UO->getSubExpr())) { 439 if (DRE->getDecl()->isCXXInstanceMember()) { 440 // This is a pointer-to-member expression, e.g. &MyClass::mu_. 441 // We interpret this syntax specially, as a wildcard. 442 auto *W = new (Arena) til::Wildcard(); 443 return new (Arena) til::Project(W, DRE->getDecl()); 444 } 445 } 446 } 447 // otherwise, & is a no-op 448 return translate(UO->getSubExpr(), Ctx); 449 } 450 451 // We treat these as no-ops 452 case UO_Deref: 453 case UO_Plus: 454 return translate(UO->getSubExpr(), Ctx); 455 456 case UO_Minus: 457 return new (Arena) 458 til::UnaryOp(til::UOP_Minus, translate(UO->getSubExpr(), Ctx)); 459 case UO_Not: 460 return new (Arena) 461 til::UnaryOp(til::UOP_BitNot, translate(UO->getSubExpr(), Ctx)); 462 case UO_LNot: 463 return new (Arena) 464 til::UnaryOp(til::UOP_LogicNot, translate(UO->getSubExpr(), Ctx)); 465 466 // Currently unsupported 467 case UO_Real: 468 case UO_Imag: 469 case UO_Extension: 470 return new (Arena) til::Undefined(UO); 471 } 472 return new (Arena) til::Undefined(UO); 473 } 474 475 476 til::SExpr *SExprBuilder::translateBinOp(til::TIL_BinaryOpcode Op, 477 const BinaryOperator *BO, 478 CallingContext *Ctx, bool Reverse) { 479 til::SExpr *E0 = translate(BO->getLHS(), Ctx); 480 til::SExpr *E1 = translate(BO->getRHS(), Ctx); 481 if (Reverse) 482 return new (Arena) til::BinaryOp(Op, E1, E0); 483 else 484 return new (Arena) til::BinaryOp(Op, E0, E1); 485 } 486 487 488 til::SExpr *SExprBuilder::translateBinAssign(til::TIL_BinaryOpcode Op, 489 const BinaryOperator *BO, 490 CallingContext *Ctx, 491 bool Assign) { 492 const Expr *LHS = BO->getLHS(); 493 const Expr *RHS = BO->getRHS(); 494 til::SExpr *E0 = translate(LHS, Ctx); 495 til::SExpr *E1 = translate(RHS, Ctx); 496 497 const ValueDecl *VD = nullptr; 498 til::SExpr *CV = nullptr; 499 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(LHS)) { 500 VD = DRE->getDecl(); 501 CV = lookupVarDecl(VD); 502 } 503 504 if (!Assign) { 505 til::SExpr *Arg = CV ? CV : new (Arena) til::Load(E0); 506 E1 = new (Arena) til::BinaryOp(Op, Arg, E1); 507 E1 = addStatement(E1, nullptr, VD); 508 } 509 if (VD && CV) 510 return updateVarDecl(VD, E1); 511 return new (Arena) til::Store(E0, E1); 512 } 513 514 515 til::SExpr *SExprBuilder::translateBinaryOperator(const BinaryOperator *BO, 516 CallingContext *Ctx) { 517 switch (BO->getOpcode()) { 518 case BO_PtrMemD: 519 case BO_PtrMemI: 520 return new (Arena) til::Undefined(BO); 521 522 case BO_Mul: return translateBinOp(til::BOP_Mul, BO, Ctx); 523 case BO_Div: return translateBinOp(til::BOP_Div, BO, Ctx); 524 case BO_Rem: return translateBinOp(til::BOP_Rem, BO, Ctx); 525 case BO_Add: return translateBinOp(til::BOP_Add, BO, Ctx); 526 case BO_Sub: return translateBinOp(til::BOP_Sub, BO, Ctx); 527 case BO_Shl: return translateBinOp(til::BOP_Shl, BO, Ctx); 528 case BO_Shr: return translateBinOp(til::BOP_Shr, BO, Ctx); 529 case BO_LT: return translateBinOp(til::BOP_Lt, BO, Ctx); 530 case BO_GT: return translateBinOp(til::BOP_Lt, BO, Ctx, true); 531 case BO_LE: return translateBinOp(til::BOP_Leq, BO, Ctx); 532 case BO_GE: return translateBinOp(til::BOP_Leq, BO, Ctx, true); 533 case BO_EQ: return translateBinOp(til::BOP_Eq, BO, Ctx); 534 case BO_NE: return translateBinOp(til::BOP_Neq, BO, Ctx); 535 case BO_And: return translateBinOp(til::BOP_BitAnd, BO, Ctx); 536 case BO_Xor: return translateBinOp(til::BOP_BitXor, BO, Ctx); 537 case BO_Or: return translateBinOp(til::BOP_BitOr, BO, Ctx); 538 case BO_LAnd: return translateBinOp(til::BOP_LogicAnd, BO, Ctx); 539 case BO_LOr: return translateBinOp(til::BOP_LogicOr, BO, Ctx); 540 541 case BO_Assign: return translateBinAssign(til::BOP_Eq, BO, Ctx, true); 542 case BO_MulAssign: return translateBinAssign(til::BOP_Mul, BO, Ctx); 543 case BO_DivAssign: return translateBinAssign(til::BOP_Div, BO, Ctx); 544 case BO_RemAssign: return translateBinAssign(til::BOP_Rem, BO, Ctx); 545 case BO_AddAssign: return translateBinAssign(til::BOP_Add, BO, Ctx); 546 case BO_SubAssign: return translateBinAssign(til::BOP_Sub, BO, Ctx); 547 case BO_ShlAssign: return translateBinAssign(til::BOP_Shl, BO, Ctx); 548 case BO_ShrAssign: return translateBinAssign(til::BOP_Shr, BO, Ctx); 549 case BO_AndAssign: return translateBinAssign(til::BOP_BitAnd, BO, Ctx); 550 case BO_XorAssign: return translateBinAssign(til::BOP_BitXor, BO, Ctx); 551 case BO_OrAssign: return translateBinAssign(til::BOP_BitOr, BO, Ctx); 552 553 case BO_Comma: 554 // The clang CFG should have already processed both sides. 555 return translate(BO->getRHS(), Ctx); 556 } 557 return new (Arena) til::Undefined(BO); 558 } 559 560 561 til::SExpr *SExprBuilder::translateCastExpr(const CastExpr *CE, 562 CallingContext *Ctx) { 563 clang::CastKind K = CE->getCastKind(); 564 switch (K) { 565 case CK_LValueToRValue: { 566 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CE->getSubExpr())) { 567 til::SExpr *E0 = lookupVarDecl(DRE->getDecl()); 568 if (E0) 569 return E0; 570 } 571 til::SExpr *E0 = translate(CE->getSubExpr(), Ctx); 572 return E0; 573 // FIXME!! -- get Load working properly 574 // return new (Arena) til::Load(E0); 575 } 576 case CK_NoOp: 577 case CK_DerivedToBase: 578 case CK_UncheckedDerivedToBase: 579 case CK_ArrayToPointerDecay: 580 case CK_FunctionToPointerDecay: { 581 til::SExpr *E0 = translate(CE->getSubExpr(), Ctx); 582 return E0; 583 } 584 default: { 585 // FIXME: handle different kinds of casts. 586 til::SExpr *E0 = translate(CE->getSubExpr(), Ctx); 587 if (CapabilityExprMode) 588 return E0; 589 return new (Arena) til::Cast(til::CAST_none, E0); 590 } 591 } 592 } 593 594 595 til::SExpr * 596 SExprBuilder::translateArraySubscriptExpr(const ArraySubscriptExpr *E, 597 CallingContext *Ctx) { 598 til::SExpr *E0 = translate(E->getBase(), Ctx); 599 til::SExpr *E1 = translate(E->getIdx(), Ctx); 600 return new (Arena) til::ArrayIndex(E0, E1); 601 } 602 603 604 til::SExpr * 605 SExprBuilder::translateAbstractConditionalOperator( 606 const AbstractConditionalOperator *CO, CallingContext *Ctx) { 607 auto *C = translate(CO->getCond(), Ctx); 608 auto *T = translate(CO->getTrueExpr(), Ctx); 609 auto *E = translate(CO->getFalseExpr(), Ctx); 610 return new (Arena) til::IfThenElse(C, T, E); 611 } 612 613 614 til::SExpr * 615 SExprBuilder::translateDeclStmt(const DeclStmt *S, CallingContext *Ctx) { 616 DeclGroupRef DGrp = S->getDeclGroup(); 617 for (DeclGroupRef::iterator I = DGrp.begin(), E = DGrp.end(); I != E; ++I) { 618 if (VarDecl *VD = dyn_cast_or_null<VarDecl>(*I)) { 619 Expr *E = VD->getInit(); 620 til::SExpr* SE = translate(E, Ctx); 621 622 // Add local variables with trivial type to the variable map 623 QualType T = VD->getType(); 624 if (T.isTrivialType(VD->getASTContext())) { 625 return addVarDecl(VD, SE); 626 } 627 else { 628 // TODO: add alloca 629 } 630 } 631 } 632 return nullptr; 633 } 634 635 636 637 // If (E) is non-trivial, then add it to the current basic block, and 638 // update the statement map so that S refers to E. Returns a new variable 639 // that refers to E. 640 // If E is trivial returns E. 641 til::SExpr *SExprBuilder::addStatement(til::SExpr* E, const Stmt *S, 642 const ValueDecl *VD) { 643 if (!E || !CurrentBB || E->block() || til::ThreadSafetyTIL::isTrivial(E)) 644 return E; 645 if (VD) 646 E = new (Arena) til::Variable(E, VD); 647 CurrentInstructions.push_back(E); 648 if (S) 649 insertStmt(S, E); 650 return E; 651 } 652 653 654 // Returns the current value of VD, if known, and nullptr otherwise. 655 til::SExpr *SExprBuilder::lookupVarDecl(const ValueDecl *VD) { 656 auto It = LVarIdxMap.find(VD); 657 if (It != LVarIdxMap.end()) { 658 assert(CurrentLVarMap[It->second].first == VD); 659 return CurrentLVarMap[It->second].second; 660 } 661 return nullptr; 662 } 663 664 665 // if E is a til::Variable, update its clangDecl. 666 inline void maybeUpdateVD(til::SExpr *E, const ValueDecl *VD) { 667 if (!E) 668 return; 669 if (til::Variable *V = dyn_cast<til::Variable>(E)) { 670 if (!V->clangDecl()) 671 V->setClangDecl(VD); 672 } 673 } 674 675 // Adds a new variable declaration. 676 til::SExpr *SExprBuilder::addVarDecl(const ValueDecl *VD, til::SExpr *E) { 677 maybeUpdateVD(E, VD); 678 LVarIdxMap.insert(std::make_pair(VD, CurrentLVarMap.size())); 679 CurrentLVarMap.makeWritable(); 680 CurrentLVarMap.push_back(std::make_pair(VD, E)); 681 return E; 682 } 683 684 685 // Updates a current variable declaration. (E.g. by assignment) 686 til::SExpr *SExprBuilder::updateVarDecl(const ValueDecl *VD, til::SExpr *E) { 687 maybeUpdateVD(E, VD); 688 auto It = LVarIdxMap.find(VD); 689 if (It == LVarIdxMap.end()) { 690 til::SExpr *Ptr = new (Arena) til::LiteralPtr(VD); 691 til::SExpr *St = new (Arena) til::Store(Ptr, E); 692 return St; 693 } 694 CurrentLVarMap.makeWritable(); 695 CurrentLVarMap.elem(It->second).second = E; 696 return E; 697 } 698 699 700 // Make a Phi node in the current block for the i^th variable in CurrentVarMap. 701 // If E != null, sets Phi[CurrentBlockInfo->ArgIndex] = E. 702 // If E == null, this is a backedge and will be set later. 703 void SExprBuilder::makePhiNodeVar(unsigned i, unsigned NPreds, til::SExpr *E) { 704 unsigned ArgIndex = CurrentBlockInfo->ProcessedPredecessors; 705 assert(ArgIndex > 0 && ArgIndex < NPreds); 706 707 til::SExpr *CurrE = CurrentLVarMap[i].second; 708 if (CurrE->block() == CurrentBB) { 709 // We already have a Phi node in the current block, 710 // so just add the new variable to the Phi node. 711 til::Phi *Ph = dyn_cast<til::Phi>(CurrE); 712 assert(Ph && "Expecting Phi node."); 713 if (E) 714 Ph->values()[ArgIndex] = E; 715 return; 716 } 717 718 // Make a new phi node: phi(..., E) 719 // All phi args up to the current index are set to the current value. 720 til::Phi *Ph = new (Arena) til::Phi(Arena, NPreds); 721 Ph->values().setValues(NPreds, nullptr); 722 for (unsigned PIdx = 0; PIdx < ArgIndex; ++PIdx) 723 Ph->values()[PIdx] = CurrE; 724 if (E) 725 Ph->values()[ArgIndex] = E; 726 Ph->setClangDecl(CurrentLVarMap[i].first); 727 // If E is from a back-edge, or either E or CurrE are incomplete, then 728 // mark this node as incomplete; we may need to remove it later. 729 if (!E || isIncompletePhi(E) || isIncompletePhi(CurrE)) { 730 Ph->setStatus(til::Phi::PH_Incomplete); 731 } 732 733 // Add Phi node to current block, and update CurrentLVarMap[i] 734 CurrentArguments.push_back(Ph); 735 if (Ph->status() == til::Phi::PH_Incomplete) 736 IncompleteArgs.push_back(Ph); 737 738 CurrentLVarMap.makeWritable(); 739 CurrentLVarMap.elem(i).second = Ph; 740 } 741 742 743 // Merge values from Map into the current variable map. 744 // This will construct Phi nodes in the current basic block as necessary. 745 void SExprBuilder::mergeEntryMap(LVarDefinitionMap Map) { 746 assert(CurrentBlockInfo && "Not processing a block!"); 747 748 if (!CurrentLVarMap.valid()) { 749 // Steal Map, using copy-on-write. 750 CurrentLVarMap = std::move(Map); 751 return; 752 } 753 if (CurrentLVarMap.sameAs(Map)) 754 return; // Easy merge: maps from different predecessors are unchanged. 755 756 unsigned NPreds = CurrentBB->numPredecessors(); 757 unsigned ESz = CurrentLVarMap.size(); 758 unsigned MSz = Map.size(); 759 unsigned Sz = std::min(ESz, MSz); 760 761 for (unsigned i=0; i<Sz; ++i) { 762 if (CurrentLVarMap[i].first != Map[i].first) { 763 // We've reached the end of variables in common. 764 CurrentLVarMap.makeWritable(); 765 CurrentLVarMap.downsize(i); 766 break; 767 } 768 if (CurrentLVarMap[i].second != Map[i].second) 769 makePhiNodeVar(i, NPreds, Map[i].second); 770 } 771 if (ESz > MSz) { 772 CurrentLVarMap.makeWritable(); 773 CurrentLVarMap.downsize(Map.size()); 774 } 775 } 776 777 778 // Merge a back edge into the current variable map. 779 // This will create phi nodes for all variables in the variable map. 780 void SExprBuilder::mergeEntryMapBackEdge() { 781 // We don't have definitions for variables on the backedge, because we 782 // haven't gotten that far in the CFG. Thus, when encountering a back edge, 783 // we conservatively create Phi nodes for all variables. Unnecessary Phi 784 // nodes will be marked as incomplete, and stripped out at the end. 785 // 786 // An Phi node is unnecessary if it only refers to itself and one other 787 // variable, e.g. x = Phi(y, y, x) can be reduced to x = y. 788 789 assert(CurrentBlockInfo && "Not processing a block!"); 790 791 if (CurrentBlockInfo->HasBackEdges) 792 return; 793 CurrentBlockInfo->HasBackEdges = true; 794 795 CurrentLVarMap.makeWritable(); 796 unsigned Sz = CurrentLVarMap.size(); 797 unsigned NPreds = CurrentBB->numPredecessors(); 798 799 for (unsigned i=0; i < Sz; ++i) { 800 makePhiNodeVar(i, NPreds, nullptr); 801 } 802 } 803 804 805 // Update the phi nodes that were initially created for a back edge 806 // once the variable definitions have been computed. 807 // I.e., merge the current variable map into the phi nodes for Blk. 808 void SExprBuilder::mergePhiNodesBackEdge(const CFGBlock *Blk) { 809 til::BasicBlock *BB = lookupBlock(Blk); 810 unsigned ArgIndex = BBInfo[Blk->getBlockID()].ProcessedPredecessors; 811 assert(ArgIndex > 0 && ArgIndex < BB->numPredecessors()); 812 813 for (til::SExpr *PE : BB->arguments()) { 814 til::Phi *Ph = dyn_cast_or_null<til::Phi>(PE); 815 assert(Ph && "Expecting Phi Node."); 816 assert(Ph->values()[ArgIndex] == nullptr && "Wrong index for back edge."); 817 818 til::SExpr *E = lookupVarDecl(Ph->clangDecl()); 819 assert(E && "Couldn't find local variable for Phi node."); 820 Ph->values()[ArgIndex] = E; 821 } 822 } 823 824 void SExprBuilder::enterCFG(CFG *Cfg, const NamedDecl *D, 825 const CFGBlock *First) { 826 // Perform initial setup operations. 827 unsigned NBlocks = Cfg->getNumBlockIDs(); 828 Scfg = new (Arena) til::SCFG(Arena, NBlocks); 829 830 // allocate all basic blocks immediately, to handle forward references. 831 BBInfo.resize(NBlocks); 832 BlockMap.resize(NBlocks, nullptr); 833 // create map from clang blockID to til::BasicBlocks 834 for (auto *B : *Cfg) { 835 auto *BB = new (Arena) til::BasicBlock(Arena); 836 BB->reserveInstructions(B->size()); 837 BlockMap[B->getBlockID()] = BB; 838 } 839 840 CurrentBB = lookupBlock(&Cfg->getEntry()); 841 auto Parms = isa<ObjCMethodDecl>(D) ? cast<ObjCMethodDecl>(D)->parameters() 842 : cast<FunctionDecl>(D)->parameters(); 843 for (auto *Pm : Parms) { 844 QualType T = Pm->getType(); 845 if (!T.isTrivialType(Pm->getASTContext())) 846 continue; 847 848 // Add parameters to local variable map. 849 // FIXME: right now we emulate params with loads; that should be fixed. 850 til::SExpr *Lp = new (Arena) til::LiteralPtr(Pm); 851 til::SExpr *Ld = new (Arena) til::Load(Lp); 852 til::SExpr *V = addStatement(Ld, nullptr, Pm); 853 addVarDecl(Pm, V); 854 } 855 } 856 857 858 void SExprBuilder::enterCFGBlock(const CFGBlock *B) { 859 // Intialize TIL basic block and add it to the CFG. 860 CurrentBB = lookupBlock(B); 861 CurrentBB->reservePredecessors(B->pred_size()); 862 Scfg->add(CurrentBB); 863 864 CurrentBlockInfo = &BBInfo[B->getBlockID()]; 865 866 // CurrentLVarMap is moved to ExitMap on block exit. 867 // FIXME: the entry block will hold function parameters. 868 // assert(!CurrentLVarMap.valid() && "CurrentLVarMap already initialized."); 869 } 870 871 872 void SExprBuilder::handlePredecessor(const CFGBlock *Pred) { 873 // Compute CurrentLVarMap on entry from ExitMaps of predecessors 874 875 CurrentBB->addPredecessor(BlockMap[Pred->getBlockID()]); 876 BlockInfo *PredInfo = &BBInfo[Pred->getBlockID()]; 877 assert(PredInfo->UnprocessedSuccessors > 0); 878 879 if (--PredInfo->UnprocessedSuccessors == 0) 880 mergeEntryMap(std::move(PredInfo->ExitMap)); 881 else 882 mergeEntryMap(PredInfo->ExitMap.clone()); 883 884 ++CurrentBlockInfo->ProcessedPredecessors; 885 } 886 887 888 void SExprBuilder::handlePredecessorBackEdge(const CFGBlock *Pred) { 889 mergeEntryMapBackEdge(); 890 } 891 892 893 void SExprBuilder::enterCFGBlockBody(const CFGBlock *B) { 894 // The merge*() methods have created arguments. 895 // Push those arguments onto the basic block. 896 CurrentBB->arguments().reserve( 897 static_cast<unsigned>(CurrentArguments.size()), Arena); 898 for (auto *A : CurrentArguments) 899 CurrentBB->addArgument(A); 900 } 901 902 903 void SExprBuilder::handleStatement(const Stmt *S) { 904 til::SExpr *E = translate(S, nullptr); 905 addStatement(E, S); 906 } 907 908 909 void SExprBuilder::handleDestructorCall(const VarDecl *VD, 910 const CXXDestructorDecl *DD) { 911 til::SExpr *Sf = new (Arena) til::LiteralPtr(VD); 912 til::SExpr *Dr = new (Arena) til::LiteralPtr(DD); 913 til::SExpr *Ap = new (Arena) til::Apply(Dr, Sf); 914 til::SExpr *E = new (Arena) til::Call(Ap); 915 addStatement(E, nullptr); 916 } 917 918 919 920 void SExprBuilder::exitCFGBlockBody(const CFGBlock *B) { 921 CurrentBB->instructions().reserve( 922 static_cast<unsigned>(CurrentInstructions.size()), Arena); 923 for (auto *V : CurrentInstructions) 924 CurrentBB->addInstruction(V); 925 926 // Create an appropriate terminator 927 unsigned N = B->succ_size(); 928 auto It = B->succ_begin(); 929 if (N == 1) { 930 til::BasicBlock *BB = *It ? lookupBlock(*It) : nullptr; 931 // TODO: set index 932 unsigned Idx = BB ? BB->findPredecessorIndex(CurrentBB) : 0; 933 auto *Tm = new (Arena) til::Goto(BB, Idx); 934 CurrentBB->setTerminator(Tm); 935 } 936 else if (N == 2) { 937 til::SExpr *C = translate(B->getTerminatorCondition(true), nullptr); 938 til::BasicBlock *BB1 = *It ? lookupBlock(*It) : nullptr; 939 ++It; 940 til::BasicBlock *BB2 = *It ? lookupBlock(*It) : nullptr; 941 // FIXME: make sure these arent' critical edges. 942 auto *Tm = new (Arena) til::Branch(C, BB1, BB2); 943 CurrentBB->setTerminator(Tm); 944 } 945 } 946 947 948 void SExprBuilder::handleSuccessor(const CFGBlock *Succ) { 949 ++CurrentBlockInfo->UnprocessedSuccessors; 950 } 951 952 953 void SExprBuilder::handleSuccessorBackEdge(const CFGBlock *Succ) { 954 mergePhiNodesBackEdge(Succ); 955 ++BBInfo[Succ->getBlockID()].ProcessedPredecessors; 956 } 957 958 959 void SExprBuilder::exitCFGBlock(const CFGBlock *B) { 960 CurrentArguments.clear(); 961 CurrentInstructions.clear(); 962 CurrentBlockInfo->ExitMap = std::move(CurrentLVarMap); 963 CurrentBB = nullptr; 964 CurrentBlockInfo = nullptr; 965 } 966 967 968 void SExprBuilder::exitCFG(const CFGBlock *Last) { 969 for (auto *Ph : IncompleteArgs) { 970 if (Ph->status() == til::Phi::PH_Incomplete) 971 simplifyIncompleteArg(Ph); 972 } 973 974 CurrentArguments.clear(); 975 CurrentInstructions.clear(); 976 IncompleteArgs.clear(); 977 } 978 979 980 /* 981 void printSCFG(CFGWalker &Walker) { 982 llvm::BumpPtrAllocator Bpa; 983 til::MemRegionRef Arena(&Bpa); 984 SExprBuilder SxBuilder(Arena); 985 til::SCFG *Scfg = SxBuilder.buildCFG(Walker); 986 TILPrinter::print(Scfg, llvm::errs()); 987 } 988 */ 989 990 991 } // end namespace threadSafety 992 993 } // end namespace clang 994