1 //===- ThreadSafetyCommon.cpp ---------------------------------------------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // Implementation of the interfaces declared in ThreadSafetyCommon.h
11 //===----------------------------------------------------------------------===//
13 #include "clang/Analysis/Analyses/ThreadSafetyCommon.h"
14 #include "clang/AST/Attr.h"
15 #include "clang/AST/Decl.h"
16 #include "clang/AST/DeclCXX.h"
17 #include "clang/AST/DeclGroup.h"
18 #include "clang/AST/DeclObjC.h"
19 #include "clang/AST/Expr.h"
20 #include "clang/AST/ExprCXX.h"
21 #include "clang/AST/OperationKinds.h"
22 #include "clang/AST/Stmt.h"
23 #include "clang/AST/Type.h"
24 #include "clang/Analysis/Analyses/ThreadSafetyTIL.h"
25 #include "clang/Analysis/CFG.h"
26 #include "clang/Basic/LLVM.h"
27 #include "clang/Basic/OperatorKinds.h"
28 #include "clang/Basic/Specifiers.h"
29 #include "llvm/ADT/StringExtras.h"
30 #include "llvm/ADT/StringRef.h"
31 #include "llvm/Support/Casting.h"
37 using namespace clang
;
38 using namespace threadSafety
;
40 // From ThreadSafetyUtil.h
41 std::string
threadSafety::getSourceLiteralString(const Expr
*CE
) {
42 switch (CE
->getStmtClass()) {
43 case Stmt::IntegerLiteralClass
:
44 return toString(cast
<IntegerLiteral
>(CE
)->getValue(), 10, true);
45 case Stmt::StringLiteralClass
: {
46 std::string
ret("\"");
47 ret
+= cast
<StringLiteral
>(CE
)->getString();
51 case Stmt::CharacterLiteralClass
:
52 case Stmt::CXXNullPtrLiteralExprClass
:
53 case Stmt::GNUNullExprClass
:
54 case Stmt::CXXBoolLiteralExprClass
:
55 case Stmt::FloatingLiteralClass
:
56 case Stmt::ImaginaryLiteralClass
:
57 case Stmt::ObjCStringLiteralClass
:
63 // Return true if E is a variable that points to an incomplete Phi node.
64 static bool isIncompletePhi(const til::SExpr
*E
) {
65 if (const auto *Ph
= dyn_cast
<til::Phi
>(E
))
66 return Ph
->status() == til::Phi::PH_Incomplete
;
70 using CallingContext
= SExprBuilder::CallingContext
;
72 til::SExpr
*SExprBuilder::lookupStmt(const Stmt
*S
) { return SMap
.lookup(S
); }
74 til::SCFG
*SExprBuilder::buildCFG(CFGWalker
&Walker
) {
79 static bool isCalleeArrow(const Expr
*E
) {
80 const auto *ME
= dyn_cast
<MemberExpr
>(E
->IgnoreParenCasts());
81 return ME
? ME
->isArrow() : false;
84 static StringRef
ClassifyDiagnostic(const CapabilityAttr
*A
) {
88 static StringRef
ClassifyDiagnostic(QualType VDT
) {
89 // We need to look at the declaration of the type of the value to determine
90 // which it is. The type should either be a record or a typedef, or a pointer
91 // or reference thereof.
92 if (const auto *RT
= VDT
->getAs
<RecordType
>()) {
93 if (const auto *RD
= RT
->getDecl())
94 if (const auto *CA
= RD
->getAttr
<CapabilityAttr
>())
95 return ClassifyDiagnostic(CA
);
96 } else if (const auto *TT
= VDT
->getAs
<TypedefType
>()) {
97 if (const auto *TD
= TT
->getDecl())
98 if (const auto *CA
= TD
->getAttr
<CapabilityAttr
>())
99 return ClassifyDiagnostic(CA
);
100 } else if (VDT
->isPointerOrReferenceType())
101 return ClassifyDiagnostic(VDT
->getPointeeType());
106 /// Translate a clang expression in an attribute to a til::SExpr.
107 /// Constructs the context from D, DeclExp, and SelfDecl.
109 /// \param AttrExp The expression to translate.
110 /// \param D The declaration to which the attribute is attached.
111 /// \param DeclExp An expression involving the Decl to which the attribute
112 /// is attached. E.g. the call to a function.
113 /// \param Self S-expression to substitute for a \ref CXXThisExpr in a call,
114 /// or argument to a cleanup function.
115 CapabilityExpr
SExprBuilder::translateAttrExpr(const Expr
*AttrExp
,
119 // If we are processing a raw attribute expression, with no substitutions.
120 if (!DeclExp
&& !Self
)
121 return translateAttrExpr(AttrExp
, nullptr);
123 CallingContext
Ctx(nullptr, D
);
125 // Examine DeclExp to find SelfArg and FunArgs, which are used to substitute
126 // for formal parameters when we call buildMutexID later.
128 /* We'll use Self. */;
129 else if (const auto *ME
= dyn_cast
<MemberExpr
>(DeclExp
)) {
130 Ctx
.SelfArg
= ME
->getBase();
131 Ctx
.SelfArrow
= ME
->isArrow();
132 } else if (const auto *CE
= dyn_cast
<CXXMemberCallExpr
>(DeclExp
)) {
133 Ctx
.SelfArg
= CE
->getImplicitObjectArgument();
134 Ctx
.SelfArrow
= isCalleeArrow(CE
->getCallee());
135 Ctx
.NumArgs
= CE
->getNumArgs();
136 Ctx
.FunArgs
= CE
->getArgs();
137 } else if (const auto *CE
= dyn_cast
<CallExpr
>(DeclExp
)) {
138 Ctx
.NumArgs
= CE
->getNumArgs();
139 Ctx
.FunArgs
= CE
->getArgs();
140 } else if (const auto *CE
= dyn_cast
<CXXConstructExpr
>(DeclExp
)) {
141 Ctx
.SelfArg
= nullptr; // Will be set below
142 Ctx
.NumArgs
= CE
->getNumArgs();
143 Ctx
.FunArgs
= CE
->getArgs();
147 assert(!Ctx
.SelfArg
&& "Ambiguous self argument");
148 assert(isa
<FunctionDecl
>(D
) && "Self argument requires function");
149 if (isa
<CXXMethodDecl
>(D
))
154 // If the attribute has no arguments, then assume the argument is "this".
156 return CapabilityExpr(
159 cast
<CXXMethodDecl
>(D
)->getFunctionObjectParameterType()),
161 else // For most attributes.
162 return translateAttrExpr(AttrExp
, &Ctx
);
165 // If the attribute has no arguments, then assume the argument is "this".
167 return translateAttrExpr(cast
<const Expr
*>(Ctx
.SelfArg
), nullptr);
168 else // For most attributes.
169 return translateAttrExpr(AttrExp
, &Ctx
);
172 /// Translate a clang expression in an attribute to a til::SExpr.
173 // This assumes a CallingContext has already been created.
174 CapabilityExpr
SExprBuilder::translateAttrExpr(const Expr
*AttrExp
,
175 CallingContext
*Ctx
) {
177 return CapabilityExpr();
179 if (const auto* SLit
= dyn_cast
<StringLiteral
>(AttrExp
)) {
180 if (SLit
->getString() == "*")
181 // The "*" expr is a universal lock, which essentially turns off
182 // checks until it is removed from the lockset.
183 return CapabilityExpr(new (Arena
) til::Wildcard(), StringRef("wildcard"),
186 // Ignore other string literals for now.
187 return CapabilityExpr();
191 if (const auto *OE
= dyn_cast
<CXXOperatorCallExpr
>(AttrExp
)) {
192 if (OE
->getOperator() == OO_Exclaim
) {
194 AttrExp
= OE
->getArg(0);
197 else if (const auto *UO
= dyn_cast
<UnaryOperator
>(AttrExp
)) {
198 if (UO
->getOpcode() == UO_LNot
) {
200 AttrExp
= UO
->getSubExpr()->IgnoreImplicit();
204 til::SExpr
*E
= translate(AttrExp
, Ctx
);
206 // Trap mutex expressions like nullptr, or 0.
207 // Any literal value is nonsense.
208 if (!E
|| isa
<til::Literal
>(E
))
209 return CapabilityExpr();
211 StringRef Kind
= ClassifyDiagnostic(AttrExp
->getType());
213 // Hack to deal with smart pointers -- strip off top-level pointer casts.
214 if (const auto *CE
= dyn_cast
<til::Cast
>(E
)) {
215 if (CE
->castOpcode() == til::CAST_objToPtr
)
216 return CapabilityExpr(CE
->expr(), Kind
, Neg
);
218 return CapabilityExpr(E
, Kind
, Neg
);
221 til::LiteralPtr
*SExprBuilder::createVariable(const VarDecl
*VD
) {
222 return new (Arena
) til::LiteralPtr(VD
);
225 std::pair
<til::LiteralPtr
*, StringRef
>
226 SExprBuilder::createThisPlaceholder(const Expr
*Exp
) {
227 return {new (Arena
) til::LiteralPtr(nullptr),
228 ClassifyDiagnostic(Exp
->getType())};
231 // Translate a clang statement or expression to a TIL expression.
232 // Also performs substitution of variables; Ctx provides the context.
233 // Dispatches on the type of S.
234 til::SExpr
*SExprBuilder::translate(const Stmt
*S
, CallingContext
*Ctx
) {
238 // Check if S has already been translated and cached.
239 // This handles the lookup of SSA names for DeclRefExprs here.
240 if (til::SExpr
*E
= lookupStmt(S
))
243 switch (S
->getStmtClass()) {
244 case Stmt::DeclRefExprClass
:
245 return translateDeclRefExpr(cast
<DeclRefExpr
>(S
), Ctx
);
246 case Stmt::CXXThisExprClass
:
247 return translateCXXThisExpr(cast
<CXXThisExpr
>(S
), Ctx
);
248 case Stmt::MemberExprClass
:
249 return translateMemberExpr(cast
<MemberExpr
>(S
), Ctx
);
250 case Stmt::ObjCIvarRefExprClass
:
251 return translateObjCIVarRefExpr(cast
<ObjCIvarRefExpr
>(S
), Ctx
);
252 case Stmt::CallExprClass
:
253 return translateCallExpr(cast
<CallExpr
>(S
), Ctx
);
254 case Stmt::CXXMemberCallExprClass
:
255 return translateCXXMemberCallExpr(cast
<CXXMemberCallExpr
>(S
), Ctx
);
256 case Stmt::CXXOperatorCallExprClass
:
257 return translateCXXOperatorCallExpr(cast
<CXXOperatorCallExpr
>(S
), Ctx
);
258 case Stmt::UnaryOperatorClass
:
259 return translateUnaryOperator(cast
<UnaryOperator
>(S
), Ctx
);
260 case Stmt::BinaryOperatorClass
:
261 case Stmt::CompoundAssignOperatorClass
:
262 return translateBinaryOperator(cast
<BinaryOperator
>(S
), Ctx
);
264 case Stmt::ArraySubscriptExprClass
:
265 return translateArraySubscriptExpr(cast
<ArraySubscriptExpr
>(S
), Ctx
);
266 case Stmt::ConditionalOperatorClass
:
267 return translateAbstractConditionalOperator(
268 cast
<ConditionalOperator
>(S
), Ctx
);
269 case Stmt::BinaryConditionalOperatorClass
:
270 return translateAbstractConditionalOperator(
271 cast
<BinaryConditionalOperator
>(S
), Ctx
);
273 // We treat these as no-ops
274 case Stmt::ConstantExprClass
:
275 return translate(cast
<ConstantExpr
>(S
)->getSubExpr(), Ctx
);
276 case Stmt::ParenExprClass
:
277 return translate(cast
<ParenExpr
>(S
)->getSubExpr(), Ctx
);
278 case Stmt::ExprWithCleanupsClass
:
279 return translate(cast
<ExprWithCleanups
>(S
)->getSubExpr(), Ctx
);
280 case Stmt::CXXBindTemporaryExprClass
:
281 return translate(cast
<CXXBindTemporaryExpr
>(S
)->getSubExpr(), Ctx
);
282 case Stmt::MaterializeTemporaryExprClass
:
283 return translate(cast
<MaterializeTemporaryExpr
>(S
)->getSubExpr(), Ctx
);
285 // Collect all literals
286 case Stmt::CharacterLiteralClass
:
287 case Stmt::CXXNullPtrLiteralExprClass
:
288 case Stmt::GNUNullExprClass
:
289 case Stmt::CXXBoolLiteralExprClass
:
290 case Stmt::FloatingLiteralClass
:
291 case Stmt::ImaginaryLiteralClass
:
292 case Stmt::IntegerLiteralClass
:
293 case Stmt::StringLiteralClass
:
294 case Stmt::ObjCStringLiteralClass
:
295 return new (Arena
) til::Literal(cast
<Expr
>(S
));
297 case Stmt::DeclStmtClass
:
298 return translateDeclStmt(cast
<DeclStmt
>(S
), Ctx
);
302 if (const auto *CE
= dyn_cast
<CastExpr
>(S
))
303 return translateCastExpr(CE
, Ctx
);
305 return new (Arena
) til::Undefined(S
);
308 til::SExpr
*SExprBuilder::translateDeclRefExpr(const DeclRefExpr
*DRE
,
309 CallingContext
*Ctx
) {
310 const auto *VD
= cast
<ValueDecl
>(DRE
->getDecl()->getCanonicalDecl());
312 // Function parameters require substitution and/or renaming.
313 if (const auto *PV
= dyn_cast
<ParmVarDecl
>(VD
)) {
314 unsigned I
= PV
->getFunctionScopeIndex();
315 const DeclContext
*D
= PV
->getDeclContext();
316 if (Ctx
&& Ctx
->FunArgs
) {
317 const Decl
*Canonical
= Ctx
->AttrDecl
->getCanonicalDecl();
318 if (isa
<FunctionDecl
>(D
)
319 ? (cast
<FunctionDecl
>(D
)->getCanonicalDecl() == Canonical
)
320 : (cast
<ObjCMethodDecl
>(D
)->getCanonicalDecl() == Canonical
)) {
321 // Substitute call arguments for references to function parameters
322 if (const Expr
*const *FunArgs
=
323 Ctx
->FunArgs
.dyn_cast
<const Expr
*const *>()) {
324 assert(I
< Ctx
->NumArgs
);
325 return translate(FunArgs
[I
], Ctx
->Prev
);
329 return Ctx
->FunArgs
.get
<til::SExpr
*>();
332 // Map the param back to the param of the original function declaration
333 // for consistent comparisons.
334 VD
= isa
<FunctionDecl
>(D
)
335 ? cast
<FunctionDecl
>(D
)->getCanonicalDecl()->getParamDecl(I
)
336 : cast
<ObjCMethodDecl
>(D
)->getCanonicalDecl()->getParamDecl(I
);
339 // For non-local variables, treat it as a reference to a named object.
340 return new (Arena
) til::LiteralPtr(VD
);
343 til::SExpr
*SExprBuilder::translateCXXThisExpr(const CXXThisExpr
*TE
,
344 CallingContext
*Ctx
) {
345 // Substitute for 'this'
346 if (Ctx
&& Ctx
->SelfArg
) {
347 if (const auto *SelfArg
= dyn_cast
<const Expr
*>(Ctx
->SelfArg
))
348 return translate(SelfArg
, Ctx
->Prev
);
350 return cast
<til::SExpr
*>(Ctx
->SelfArg
);
352 assert(SelfVar
&& "We have no variable for 'this'!");
356 static const ValueDecl
*getValueDeclFromSExpr(const til::SExpr
*E
) {
357 if (const auto *V
= dyn_cast
<til::Variable
>(E
))
358 return V
->clangDecl();
359 if (const auto *Ph
= dyn_cast
<til::Phi
>(E
))
360 return Ph
->clangDecl();
361 if (const auto *P
= dyn_cast
<til::Project
>(E
))
362 return P
->clangDecl();
363 if (const auto *L
= dyn_cast
<til::LiteralPtr
>(E
))
364 return L
->clangDecl();
368 static bool hasAnyPointerType(const til::SExpr
*E
) {
369 auto *VD
= getValueDeclFromSExpr(E
);
370 if (VD
&& VD
->getType()->isAnyPointerType())
372 if (const auto *C
= dyn_cast
<til::Cast
>(E
))
373 return C
->castOpcode() == til::CAST_objToPtr
;
378 // Grab the very first declaration of virtual method D
379 static const CXXMethodDecl
*getFirstVirtualDecl(const CXXMethodDecl
*D
) {
381 D
= D
->getCanonicalDecl();
382 auto OverriddenMethods
= D
->overridden_methods();
383 if (OverriddenMethods
.begin() == OverriddenMethods
.end())
384 return D
; // Method does not override anything
385 // FIXME: this does not work with multiple inheritance.
386 D
= *OverriddenMethods
.begin();
391 til::SExpr
*SExprBuilder::translateMemberExpr(const MemberExpr
*ME
,
392 CallingContext
*Ctx
) {
393 til::SExpr
*BE
= translate(ME
->getBase(), Ctx
);
394 til::SExpr
*E
= new (Arena
) til::SApply(BE
);
396 const auto *D
= cast
<ValueDecl
>(ME
->getMemberDecl()->getCanonicalDecl());
397 if (const auto *VD
= dyn_cast
<CXXMethodDecl
>(D
))
398 D
= getFirstVirtualDecl(VD
);
400 til::Project
*P
= new (Arena
) til::Project(E
, D
);
401 if (hasAnyPointerType(BE
))
406 til::SExpr
*SExprBuilder::translateObjCIVarRefExpr(const ObjCIvarRefExpr
*IVRE
,
407 CallingContext
*Ctx
) {
408 til::SExpr
*BE
= translate(IVRE
->getBase(), Ctx
);
409 til::SExpr
*E
= new (Arena
) til::SApply(BE
);
411 const auto *D
= cast
<ObjCIvarDecl
>(IVRE
->getDecl()->getCanonicalDecl());
413 til::Project
*P
= new (Arena
) til::Project(E
, D
);
414 if (hasAnyPointerType(BE
))
419 til::SExpr
*SExprBuilder::translateCallExpr(const CallExpr
*CE
,
422 if (CapabilityExprMode
) {
423 // Handle LOCK_RETURNED
424 if (const FunctionDecl
*FD
= CE
->getDirectCallee()) {
425 FD
= FD
->getMostRecentDecl();
426 if (LockReturnedAttr
*At
= FD
->getAttr
<LockReturnedAttr
>()) {
427 CallingContext
LRCallCtx(Ctx
);
428 LRCallCtx
.AttrDecl
= CE
->getDirectCallee();
429 LRCallCtx
.SelfArg
= SelfE
;
430 LRCallCtx
.NumArgs
= CE
->getNumArgs();
431 LRCallCtx
.FunArgs
= CE
->getArgs();
432 return const_cast<til::SExpr
*>(
433 translateAttrExpr(At
->getArg(), &LRCallCtx
).sexpr());
438 til::SExpr
*E
= translate(CE
->getCallee(), Ctx
);
439 for (const auto *Arg
: CE
->arguments()) {
440 til::SExpr
*A
= translate(Arg
, Ctx
);
441 E
= new (Arena
) til::Apply(E
, A
);
443 return new (Arena
) til::Call(E
, CE
);
446 til::SExpr
*SExprBuilder::translateCXXMemberCallExpr(
447 const CXXMemberCallExpr
*ME
, CallingContext
*Ctx
) {
448 if (CapabilityExprMode
) {
449 // Ignore calls to get() on smart pointers.
450 if (ME
->getMethodDecl()->getNameAsString() == "get" &&
451 ME
->getNumArgs() == 0) {
452 auto *E
= translate(ME
->getImplicitObjectArgument(), Ctx
);
453 return new (Arena
) til::Cast(til::CAST_objToPtr
, E
);
457 return translateCallExpr(cast
<CallExpr
>(ME
), Ctx
,
458 ME
->getImplicitObjectArgument());
461 til::SExpr
*SExprBuilder::translateCXXOperatorCallExpr(
462 const CXXOperatorCallExpr
*OCE
, CallingContext
*Ctx
) {
463 if (CapabilityExprMode
) {
464 // Ignore operator * and operator -> on smart pointers.
465 OverloadedOperatorKind k
= OCE
->getOperator();
466 if (k
== OO_Star
|| k
== OO_Arrow
) {
467 auto *E
= translate(OCE
->getArg(0), Ctx
);
468 return new (Arena
) til::Cast(til::CAST_objToPtr
, E
);
472 return translateCallExpr(cast
<CallExpr
>(OCE
), Ctx
);
475 til::SExpr
*SExprBuilder::translateUnaryOperator(const UnaryOperator
*UO
,
476 CallingContext
*Ctx
) {
477 switch (UO
->getOpcode()) {
482 return new (Arena
) til::Undefined(UO
);
485 if (CapabilityExprMode
) {
486 // interpret &Graph::mu_ as an existential.
487 if (const auto *DRE
= dyn_cast
<DeclRefExpr
>(UO
->getSubExpr())) {
488 if (DRE
->getDecl()->isCXXInstanceMember()) {
489 // This is a pointer-to-member expression, e.g. &MyClass::mu_.
490 // We interpret this syntax specially, as a wildcard.
491 auto *W
= new (Arena
) til::Wildcard();
492 return new (Arena
) til::Project(W
, DRE
->getDecl());
496 // otherwise, & is a no-op
497 return translate(UO
->getSubExpr(), Ctx
);
499 // We treat these as no-ops
502 return translate(UO
->getSubExpr(), Ctx
);
506 til::UnaryOp(til::UOP_Minus
, translate(UO
->getSubExpr(), Ctx
));
509 til::UnaryOp(til::UOP_BitNot
, translate(UO
->getSubExpr(), Ctx
));
512 til::UnaryOp(til::UOP_LogicNot
, translate(UO
->getSubExpr(), Ctx
));
514 // Currently unsupported
519 return new (Arena
) til::Undefined(UO
);
521 return new (Arena
) til::Undefined(UO
);
524 til::SExpr
*SExprBuilder::translateBinOp(til::TIL_BinaryOpcode Op
,
525 const BinaryOperator
*BO
,
526 CallingContext
*Ctx
, bool Reverse
) {
527 til::SExpr
*E0
= translate(BO
->getLHS(), Ctx
);
528 til::SExpr
*E1
= translate(BO
->getRHS(), Ctx
);
530 return new (Arena
) til::BinaryOp(Op
, E1
, E0
);
532 return new (Arena
) til::BinaryOp(Op
, E0
, E1
);
535 til::SExpr
*SExprBuilder::translateBinAssign(til::TIL_BinaryOpcode Op
,
536 const BinaryOperator
*BO
,
539 const Expr
*LHS
= BO
->getLHS();
540 const Expr
*RHS
= BO
->getRHS();
541 til::SExpr
*E0
= translate(LHS
, Ctx
);
542 til::SExpr
*E1
= translate(RHS
, Ctx
);
544 const ValueDecl
*VD
= nullptr;
545 til::SExpr
*CV
= nullptr;
546 if (const auto *DRE
= dyn_cast
<DeclRefExpr
>(LHS
)) {
548 CV
= lookupVarDecl(VD
);
552 til::SExpr
*Arg
= CV
? CV
: new (Arena
) til::Load(E0
);
553 E1
= new (Arena
) til::BinaryOp(Op
, Arg
, E1
);
554 E1
= addStatement(E1
, nullptr, VD
);
557 return updateVarDecl(VD
, E1
);
558 return new (Arena
) til::Store(E0
, E1
);
561 til::SExpr
*SExprBuilder::translateBinaryOperator(const BinaryOperator
*BO
,
562 CallingContext
*Ctx
) {
563 switch (BO
->getOpcode()) {
566 return new (Arena
) til::Undefined(BO
);
568 case BO_Mul
: return translateBinOp(til::BOP_Mul
, BO
, Ctx
);
569 case BO_Div
: return translateBinOp(til::BOP_Div
, BO
, Ctx
);
570 case BO_Rem
: return translateBinOp(til::BOP_Rem
, BO
, Ctx
);
571 case BO_Add
: return translateBinOp(til::BOP_Add
, BO
, Ctx
);
572 case BO_Sub
: return translateBinOp(til::BOP_Sub
, BO
, Ctx
);
573 case BO_Shl
: return translateBinOp(til::BOP_Shl
, BO
, Ctx
);
574 case BO_Shr
: return translateBinOp(til::BOP_Shr
, BO
, Ctx
);
575 case BO_LT
: return translateBinOp(til::BOP_Lt
, BO
, Ctx
);
576 case BO_GT
: return translateBinOp(til::BOP_Lt
, BO
, Ctx
, true);
577 case BO_LE
: return translateBinOp(til::BOP_Leq
, BO
, Ctx
);
578 case BO_GE
: return translateBinOp(til::BOP_Leq
, BO
, Ctx
, true);
579 case BO_EQ
: return translateBinOp(til::BOP_Eq
, BO
, Ctx
);
580 case BO_NE
: return translateBinOp(til::BOP_Neq
, BO
, Ctx
);
581 case BO_Cmp
: return translateBinOp(til::BOP_Cmp
, BO
, Ctx
);
582 case BO_And
: return translateBinOp(til::BOP_BitAnd
, BO
, Ctx
);
583 case BO_Xor
: return translateBinOp(til::BOP_BitXor
, BO
, Ctx
);
584 case BO_Or
: return translateBinOp(til::BOP_BitOr
, BO
, Ctx
);
585 case BO_LAnd
: return translateBinOp(til::BOP_LogicAnd
, BO
, Ctx
);
586 case BO_LOr
: return translateBinOp(til::BOP_LogicOr
, BO
, Ctx
);
588 case BO_Assign
: return translateBinAssign(til::BOP_Eq
, BO
, Ctx
, true);
589 case BO_MulAssign
: return translateBinAssign(til::BOP_Mul
, BO
, Ctx
);
590 case BO_DivAssign
: return translateBinAssign(til::BOP_Div
, BO
, Ctx
);
591 case BO_RemAssign
: return translateBinAssign(til::BOP_Rem
, BO
, Ctx
);
592 case BO_AddAssign
: return translateBinAssign(til::BOP_Add
, BO
, Ctx
);
593 case BO_SubAssign
: return translateBinAssign(til::BOP_Sub
, BO
, Ctx
);
594 case BO_ShlAssign
: return translateBinAssign(til::BOP_Shl
, BO
, Ctx
);
595 case BO_ShrAssign
: return translateBinAssign(til::BOP_Shr
, BO
, Ctx
);
596 case BO_AndAssign
: return translateBinAssign(til::BOP_BitAnd
, BO
, Ctx
);
597 case BO_XorAssign
: return translateBinAssign(til::BOP_BitXor
, BO
, Ctx
);
598 case BO_OrAssign
: return translateBinAssign(til::BOP_BitOr
, BO
, Ctx
);
601 // The clang CFG should have already processed both sides.
602 return translate(BO
->getRHS(), Ctx
);
604 return new (Arena
) til::Undefined(BO
);
607 til::SExpr
*SExprBuilder::translateCastExpr(const CastExpr
*CE
,
608 CallingContext
*Ctx
) {
609 CastKind K
= CE
->getCastKind();
611 case CK_LValueToRValue
: {
612 if (const auto *DRE
= dyn_cast
<DeclRefExpr
>(CE
->getSubExpr())) {
613 til::SExpr
*E0
= lookupVarDecl(DRE
->getDecl());
617 til::SExpr
*E0
= translate(CE
->getSubExpr(), Ctx
);
619 // FIXME!! -- get Load working properly
620 // return new (Arena) til::Load(E0);
623 case CK_DerivedToBase
:
624 case CK_UncheckedDerivedToBase
:
625 case CK_ArrayToPointerDecay
:
626 case CK_FunctionToPointerDecay
: {
627 til::SExpr
*E0
= translate(CE
->getSubExpr(), Ctx
);
631 // FIXME: handle different kinds of casts.
632 til::SExpr
*E0
= translate(CE
->getSubExpr(), Ctx
);
633 if (CapabilityExprMode
)
635 return new (Arena
) til::Cast(til::CAST_none
, E0
);
641 SExprBuilder::translateArraySubscriptExpr(const ArraySubscriptExpr
*E
,
642 CallingContext
*Ctx
) {
643 til::SExpr
*E0
= translate(E
->getBase(), Ctx
);
644 til::SExpr
*E1
= translate(E
->getIdx(), Ctx
);
645 return new (Arena
) til::ArrayIndex(E0
, E1
);
649 SExprBuilder::translateAbstractConditionalOperator(
650 const AbstractConditionalOperator
*CO
, CallingContext
*Ctx
) {
651 auto *C
= translate(CO
->getCond(), Ctx
);
652 auto *T
= translate(CO
->getTrueExpr(), Ctx
);
653 auto *E
= translate(CO
->getFalseExpr(), Ctx
);
654 return new (Arena
) til::IfThenElse(C
, T
, E
);
658 SExprBuilder::translateDeclStmt(const DeclStmt
*S
, CallingContext
*Ctx
) {
659 DeclGroupRef DGrp
= S
->getDeclGroup();
660 for (auto *I
: DGrp
) {
661 if (auto *VD
= dyn_cast_or_null
<VarDecl
>(I
)) {
662 Expr
*E
= VD
->getInit();
663 til::SExpr
* SE
= translate(E
, Ctx
);
665 // Add local variables with trivial type to the variable map
666 QualType T
= VD
->getType();
667 if (T
.isTrivialType(VD
->getASTContext()))
668 return addVarDecl(VD
, SE
);
677 // If (E) is non-trivial, then add it to the current basic block, and
678 // update the statement map so that S refers to E. Returns a new variable
680 // If E is trivial returns E.
681 til::SExpr
*SExprBuilder::addStatement(til::SExpr
* E
, const Stmt
*S
,
682 const ValueDecl
*VD
) {
683 if (!E
|| !CurrentBB
|| E
->block() || til::ThreadSafetyTIL::isTrivial(E
))
686 E
= new (Arena
) til::Variable(E
, VD
);
687 CurrentInstructions
.push_back(E
);
693 // Returns the current value of VD, if known, and nullptr otherwise.
694 til::SExpr
*SExprBuilder::lookupVarDecl(const ValueDecl
*VD
) {
695 auto It
= LVarIdxMap
.find(VD
);
696 if (It
!= LVarIdxMap
.end()) {
697 assert(CurrentLVarMap
[It
->second
].first
== VD
);
698 return CurrentLVarMap
[It
->second
].second
;
703 // if E is a til::Variable, update its clangDecl.
704 static void maybeUpdateVD(til::SExpr
*E
, const ValueDecl
*VD
) {
707 if (auto *V
= dyn_cast
<til::Variable
>(E
)) {
713 // Adds a new variable declaration.
714 til::SExpr
*SExprBuilder::addVarDecl(const ValueDecl
*VD
, til::SExpr
*E
) {
715 maybeUpdateVD(E
, VD
);
716 LVarIdxMap
.insert(std::make_pair(VD
, CurrentLVarMap
.size()));
717 CurrentLVarMap
.makeWritable();
718 CurrentLVarMap
.push_back(std::make_pair(VD
, E
));
722 // Updates a current variable declaration. (E.g. by assignment)
723 til::SExpr
*SExprBuilder::updateVarDecl(const ValueDecl
*VD
, til::SExpr
*E
) {
724 maybeUpdateVD(E
, VD
);
725 auto It
= LVarIdxMap
.find(VD
);
726 if (It
== LVarIdxMap
.end()) {
727 til::SExpr
*Ptr
= new (Arena
) til::LiteralPtr(VD
);
728 til::SExpr
*St
= new (Arena
) til::Store(Ptr
, E
);
731 CurrentLVarMap
.makeWritable();
732 CurrentLVarMap
.elem(It
->second
).second
= E
;
736 // Make a Phi node in the current block for the i^th variable in CurrentVarMap.
737 // If E != null, sets Phi[CurrentBlockInfo->ArgIndex] = E.
738 // If E == null, this is a backedge and will be set later.
739 void SExprBuilder::makePhiNodeVar(unsigned i
, unsigned NPreds
, til::SExpr
*E
) {
740 unsigned ArgIndex
= CurrentBlockInfo
->ProcessedPredecessors
;
741 assert(ArgIndex
> 0 && ArgIndex
< NPreds
);
743 til::SExpr
*CurrE
= CurrentLVarMap
[i
].second
;
744 if (CurrE
->block() == CurrentBB
) {
745 // We already have a Phi node in the current block,
746 // so just add the new variable to the Phi node.
747 auto *Ph
= dyn_cast
<til::Phi
>(CurrE
);
748 assert(Ph
&& "Expecting Phi node.");
750 Ph
->values()[ArgIndex
] = E
;
754 // Make a new phi node: phi(..., E)
755 // All phi args up to the current index are set to the current value.
756 til::Phi
*Ph
= new (Arena
) til::Phi(Arena
, NPreds
);
757 Ph
->values().setValues(NPreds
, nullptr);
758 for (unsigned PIdx
= 0; PIdx
< ArgIndex
; ++PIdx
)
759 Ph
->values()[PIdx
] = CurrE
;
761 Ph
->values()[ArgIndex
] = E
;
762 Ph
->setClangDecl(CurrentLVarMap
[i
].first
);
763 // If E is from a back-edge, or either E or CurrE are incomplete, then
764 // mark this node as incomplete; we may need to remove it later.
765 if (!E
|| isIncompletePhi(E
) || isIncompletePhi(CurrE
))
766 Ph
->setStatus(til::Phi::PH_Incomplete
);
768 // Add Phi node to current block, and update CurrentLVarMap[i]
769 CurrentArguments
.push_back(Ph
);
770 if (Ph
->status() == til::Phi::PH_Incomplete
)
771 IncompleteArgs
.push_back(Ph
);
773 CurrentLVarMap
.makeWritable();
774 CurrentLVarMap
.elem(i
).second
= Ph
;
777 // Merge values from Map into the current variable map.
778 // This will construct Phi nodes in the current basic block as necessary.
779 void SExprBuilder::mergeEntryMap(LVarDefinitionMap Map
) {
780 assert(CurrentBlockInfo
&& "Not processing a block!");
782 if (!CurrentLVarMap
.valid()) {
783 // Steal Map, using copy-on-write.
784 CurrentLVarMap
= std::move(Map
);
787 if (CurrentLVarMap
.sameAs(Map
))
788 return; // Easy merge: maps from different predecessors are unchanged.
790 unsigned NPreds
= CurrentBB
->numPredecessors();
791 unsigned ESz
= CurrentLVarMap
.size();
792 unsigned MSz
= Map
.size();
793 unsigned Sz
= std::min(ESz
, MSz
);
795 for (unsigned i
= 0; i
< Sz
; ++i
) {
796 if (CurrentLVarMap
[i
].first
!= Map
[i
].first
) {
797 // We've reached the end of variables in common.
798 CurrentLVarMap
.makeWritable();
799 CurrentLVarMap
.downsize(i
);
802 if (CurrentLVarMap
[i
].second
!= Map
[i
].second
)
803 makePhiNodeVar(i
, NPreds
, Map
[i
].second
);
806 CurrentLVarMap
.makeWritable();
807 CurrentLVarMap
.downsize(Map
.size());
811 // Merge a back edge into the current variable map.
812 // This will create phi nodes for all variables in the variable map.
813 void SExprBuilder::mergeEntryMapBackEdge() {
814 // We don't have definitions for variables on the backedge, because we
815 // haven't gotten that far in the CFG. Thus, when encountering a back edge,
816 // we conservatively create Phi nodes for all variables. Unnecessary Phi
817 // nodes will be marked as incomplete, and stripped out at the end.
819 // An Phi node is unnecessary if it only refers to itself and one other
820 // variable, e.g. x = Phi(y, y, x) can be reduced to x = y.
822 assert(CurrentBlockInfo
&& "Not processing a block!");
824 if (CurrentBlockInfo
->HasBackEdges
)
826 CurrentBlockInfo
->HasBackEdges
= true;
828 CurrentLVarMap
.makeWritable();
829 unsigned Sz
= CurrentLVarMap
.size();
830 unsigned NPreds
= CurrentBB
->numPredecessors();
832 for (unsigned i
= 0; i
< Sz
; ++i
)
833 makePhiNodeVar(i
, NPreds
, nullptr);
836 // Update the phi nodes that were initially created for a back edge
837 // once the variable definitions have been computed.
838 // I.e., merge the current variable map into the phi nodes for Blk.
839 void SExprBuilder::mergePhiNodesBackEdge(const CFGBlock
*Blk
) {
840 til::BasicBlock
*BB
= lookupBlock(Blk
);
841 unsigned ArgIndex
= BBInfo
[Blk
->getBlockID()].ProcessedPredecessors
;
842 assert(ArgIndex
> 0 && ArgIndex
< BB
->numPredecessors());
844 for (til::SExpr
*PE
: BB
->arguments()) {
845 auto *Ph
= dyn_cast_or_null
<til::Phi
>(PE
);
846 assert(Ph
&& "Expecting Phi Node.");
847 assert(Ph
->values()[ArgIndex
] == nullptr && "Wrong index for back edge.");
849 til::SExpr
*E
= lookupVarDecl(Ph
->clangDecl());
850 assert(E
&& "Couldn't find local variable for Phi node.");
851 Ph
->values()[ArgIndex
] = E
;
855 void SExprBuilder::enterCFG(CFG
*Cfg
, const NamedDecl
*D
,
856 const CFGBlock
*First
) {
857 // Perform initial setup operations.
858 unsigned NBlocks
= Cfg
->getNumBlockIDs();
859 Scfg
= new (Arena
) til::SCFG(Arena
, NBlocks
);
861 // allocate all basic blocks immediately, to handle forward references.
862 BBInfo
.resize(NBlocks
);
863 BlockMap
.resize(NBlocks
, nullptr);
864 // create map from clang blockID to til::BasicBlocks
865 for (auto *B
: *Cfg
) {
866 auto *BB
= new (Arena
) til::BasicBlock(Arena
);
867 BB
->reserveInstructions(B
->size());
868 BlockMap
[B
->getBlockID()] = BB
;
871 CurrentBB
= lookupBlock(&Cfg
->getEntry());
872 auto Parms
= isa
<ObjCMethodDecl
>(D
) ? cast
<ObjCMethodDecl
>(D
)->parameters()
873 : cast
<FunctionDecl
>(D
)->parameters();
874 for (auto *Pm
: Parms
) {
875 QualType T
= Pm
->getType();
876 if (!T
.isTrivialType(Pm
->getASTContext()))
879 // Add parameters to local variable map.
880 // FIXME: right now we emulate params with loads; that should be fixed.
881 til::SExpr
*Lp
= new (Arena
) til::LiteralPtr(Pm
);
882 til::SExpr
*Ld
= new (Arena
) til::Load(Lp
);
883 til::SExpr
*V
= addStatement(Ld
, nullptr, Pm
);
888 void SExprBuilder::enterCFGBlock(const CFGBlock
*B
) {
889 // Initialize TIL basic block and add it to the CFG.
890 CurrentBB
= lookupBlock(B
);
891 CurrentBB
->reservePredecessors(B
->pred_size());
892 Scfg
->add(CurrentBB
);
894 CurrentBlockInfo
= &BBInfo
[B
->getBlockID()];
896 // CurrentLVarMap is moved to ExitMap on block exit.
897 // FIXME: the entry block will hold function parameters.
898 // assert(!CurrentLVarMap.valid() && "CurrentLVarMap already initialized.");
901 void SExprBuilder::handlePredecessor(const CFGBlock
*Pred
) {
902 // Compute CurrentLVarMap on entry from ExitMaps of predecessors
904 CurrentBB
->addPredecessor(BlockMap
[Pred
->getBlockID()]);
905 BlockInfo
*PredInfo
= &BBInfo
[Pred
->getBlockID()];
906 assert(PredInfo
->UnprocessedSuccessors
> 0);
908 if (--PredInfo
->UnprocessedSuccessors
== 0)
909 mergeEntryMap(std::move(PredInfo
->ExitMap
));
911 mergeEntryMap(PredInfo
->ExitMap
.clone());
913 ++CurrentBlockInfo
->ProcessedPredecessors
;
916 void SExprBuilder::handlePredecessorBackEdge(const CFGBlock
*Pred
) {
917 mergeEntryMapBackEdge();
920 void SExprBuilder::enterCFGBlockBody(const CFGBlock
*B
) {
921 // The merge*() methods have created arguments.
922 // Push those arguments onto the basic block.
923 CurrentBB
->arguments().reserve(
924 static_cast<unsigned>(CurrentArguments
.size()), Arena
);
925 for (auto *A
: CurrentArguments
)
926 CurrentBB
->addArgument(A
);
929 void SExprBuilder::handleStatement(const Stmt
*S
) {
930 til::SExpr
*E
= translate(S
, nullptr);
934 void SExprBuilder::handleDestructorCall(const VarDecl
*VD
,
935 const CXXDestructorDecl
*DD
) {
936 til::SExpr
*Sf
= new (Arena
) til::LiteralPtr(VD
);
937 til::SExpr
*Dr
= new (Arena
) til::LiteralPtr(DD
);
938 til::SExpr
*Ap
= new (Arena
) til::Apply(Dr
, Sf
);
939 til::SExpr
*E
= new (Arena
) til::Call(Ap
);
940 addStatement(E
, nullptr);
943 void SExprBuilder::exitCFGBlockBody(const CFGBlock
*B
) {
944 CurrentBB
->instructions().reserve(
945 static_cast<unsigned>(CurrentInstructions
.size()), Arena
);
946 for (auto *V
: CurrentInstructions
)
947 CurrentBB
->addInstruction(V
);
949 // Create an appropriate terminator
950 unsigned N
= B
->succ_size();
951 auto It
= B
->succ_begin();
953 til::BasicBlock
*BB
= *It
? lookupBlock(*It
) : nullptr;
955 unsigned Idx
= BB
? BB
->findPredecessorIndex(CurrentBB
) : 0;
956 auto *Tm
= new (Arena
) til::Goto(BB
, Idx
);
957 CurrentBB
->setTerminator(Tm
);
960 til::SExpr
*C
= translate(B
->getTerminatorCondition(true), nullptr);
961 til::BasicBlock
*BB1
= *It
? lookupBlock(*It
) : nullptr;
963 til::BasicBlock
*BB2
= *It
? lookupBlock(*It
) : nullptr;
964 // FIXME: make sure these aren't critical edges.
965 auto *Tm
= new (Arena
) til::Branch(C
, BB1
, BB2
);
966 CurrentBB
->setTerminator(Tm
);
970 void SExprBuilder::handleSuccessor(const CFGBlock
*Succ
) {
971 ++CurrentBlockInfo
->UnprocessedSuccessors
;
974 void SExprBuilder::handleSuccessorBackEdge(const CFGBlock
*Succ
) {
975 mergePhiNodesBackEdge(Succ
);
976 ++BBInfo
[Succ
->getBlockID()].ProcessedPredecessors
;
979 void SExprBuilder::exitCFGBlock(const CFGBlock
*B
) {
980 CurrentArguments
.clear();
981 CurrentInstructions
.clear();
982 CurrentBlockInfo
->ExitMap
= std::move(CurrentLVarMap
);
984 CurrentBlockInfo
= nullptr;
987 void SExprBuilder::exitCFG(const CFGBlock
*Last
) {
988 for (auto *Ph
: IncompleteArgs
) {
989 if (Ph
->status() == til::Phi::PH_Incomplete
)
990 simplifyIncompleteArg(Ph
);
993 CurrentArguments
.clear();
994 CurrentInstructions
.clear();
995 IncompleteArgs
.clear();
1002 public til::PrettyPrinter
<TILPrinter
, llvm::raw_ostream
> {};
1007 namespace threadSafety
{
1009 void printSCFG(CFGWalker
&Walker
) {
1010 llvm::BumpPtrAllocator Bpa
;
1011 til::MemRegionRef
Arena(&Bpa
);
1012 SExprBuilder
SxBuilder(Arena
);
1013 til::SCFG
*Scfg
= SxBuilder
.buildCFG(Walker
);
1014 TILPrinter::print(Scfg
, llvm::errs());
1017 } // namespace threadSafety
1018 } // namespace clang