1//===- ThreadSafetyCommon.cpp ---------------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// Implementation of the interfaces declared in ThreadSafetyCommon.h
10//
11//===----------------------------------------------------------------------===//
12
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/ScopeExit.h"
30#include "llvm/ADT/StringExtras.h"
31#include "llvm/ADT/StringRef.h"
32#include <algorithm>
33#include <cassert>
34#include <string>
35#include <utility>
36
37using namespace clang;
38using namespace threadSafety;
39
40// From ThreadSafetyUtil.h
41std::string threadSafety::getSourceLiteralString(const Expr *CE) {
42 switch (CE->getStmtClass()) {
43 case Stmt::IntegerLiteralClass:
44 return toString(I: cast<IntegerLiteral>(Val: CE)->getValue(), Radix: 10, Signed: true);
45 case Stmt::StringLiteralClass: {
46 std::string ret("\"");
47 ret += cast<StringLiteral>(Val: CE)->getString();
48 ret += "\"";
49 return ret;
50 }
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:
58 default:
59 return "#lit";
60 }
61}
62
63// Return true if E is a variable that points to an incomplete Phi node.
64static bool isIncompletePhi(const til::SExpr *E) {
65 if (const auto *Ph = dyn_cast<til::Phi>(Val: E))
66 return Ph->status() == til::Phi::PH_Incomplete;
67 return false;
68}
69
70static constexpr std::pair<StringRef, bool> ClassifyCapabilityFallback{
71 /*Kind=*/StringRef("mutex"),
72 /*Reentrant=*/false};
73
74// Returns pair (Kind, Reentrant).
75static std::pair<StringRef, bool> classifyCapability(const TypeDecl &TD) {
76 if (const auto *CA = TD.getAttr<CapabilityAttr>())
77 return {CA->getName(), TD.hasAttr<ReentrantCapabilityAttr>()};
78
79 return ClassifyCapabilityFallback;
80}
81
82// Returns pair (Kind, Reentrant).
83static std::pair<StringRef, bool> classifyCapability(QualType QT) {
84 // We need to look at the declaration of the type of the value to determine
85 // which it is. The type should either be a record or a typedef, or a pointer
86 // or reference thereof.
87 if (const auto *RD = QT->getAsRecordDecl())
88 return classifyCapability(TD: *RD);
89 if (const auto *TT = QT->getAs<TypedefType>())
90 return classifyCapability(TD: *TT->getDecl());
91 if (QT->isPointerOrReferenceType())
92 return classifyCapability(QT: QT->getPointeeType());
93
94 return ClassifyCapabilityFallback;
95}
96
97CapabilityExpr::CapabilityExpr(const til::SExpr *E, QualType QT, bool Neg) {
98 const auto &[Kind, Reentrant] = classifyCapability(QT);
99 *this = CapabilityExpr(E, Kind, Neg, Reentrant);
100}
101
102using CallingContext = SExprBuilder::CallingContext;
103
104til::SExpr *SExprBuilder::lookupStmt(const Stmt *S) { return SMap.lookup(Val: S); }
105
106til::SCFG *SExprBuilder::buildCFG(CFGWalker &Walker) {
107 Walker.walk(V&: *this);
108 return Scfg;
109}
110
111static bool isCalleeArrow(const Expr *E) {
112 const auto *ME = dyn_cast<MemberExpr>(Val: E->IgnoreParenCasts());
113 return ME ? ME->isArrow() : false;
114}
115
116/// Translate a clang expression in an attribute to a til::SExpr.
117/// Constructs the context from D, DeclExp, and SelfDecl.
118///
119/// \param AttrExp The expression to translate.
120/// \param D The declaration to which the attribute is attached.
121/// \param DeclExp An expression involving the Decl to which the attribute
122/// is attached. E.g. the call to a function.
123/// \param Self S-expression to substitute for a \ref CXXThisExpr in a call,
124/// or argument to a cleanup function.
125CapabilityExpr SExprBuilder::translateAttrExpr(const Expr *AttrExp,
126 const NamedDecl *D,
127 const Expr *DeclExp,
128 til::SExpr *Self) {
129 // If we are processing a raw attribute expression, with no substitutions.
130 if (!DeclExp && !Self)
131 return translateAttrExpr(AttrExp, Ctx: nullptr);
132
133 CallingContext Ctx(nullptr, D);
134
135 // Examine DeclExp to find SelfArg and FunArgs, which are used to substitute
136 // for formal parameters when we call buildMutexID later.
137 if (!DeclExp)
138 /* We'll use Self. */;
139 else if (const auto *ME = dyn_cast<MemberExpr>(Val: DeclExp)) {
140 Ctx.SelfArg = ME->getBase();
141 Ctx.SelfArrow = ME->isArrow();
142 } else if (const auto *CE = dyn_cast<CXXMemberCallExpr>(Val: DeclExp)) {
143 Ctx.SelfArg = CE->getImplicitObjectArgument();
144 Ctx.SelfArrow = isCalleeArrow(E: CE->getCallee());
145 Ctx.NumArgs = CE->getNumArgs();
146 Ctx.FunArgs = CE->getArgs();
147 } else if (const auto *CE = dyn_cast<CallExpr>(Val: DeclExp)) {
148 // Calls to operators that are members need to be treated like member calls.
149 if (isa<CXXOperatorCallExpr>(Val: CE) && isa<CXXMethodDecl>(Val: D)) {
150 Ctx.SelfArg = CE->getArg(Arg: 0);
151 Ctx.SelfArrow = false;
152 Ctx.NumArgs = CE->getNumArgs() - 1;
153 Ctx.FunArgs = CE->getArgs() + 1;
154 } else {
155 Ctx.NumArgs = CE->getNumArgs();
156 Ctx.FunArgs = CE->getArgs();
157 }
158 } else if (const auto *CE = dyn_cast<CXXConstructExpr>(Val: DeclExp)) {
159 Ctx.SelfArg = nullptr; // Will be set below
160 Ctx.NumArgs = CE->getNumArgs();
161 Ctx.FunArgs = CE->getArgs();
162 }
163
164 // Usually we want to substitute the self-argument for "this", but lambdas
165 // are an exception: "this" on or in a lambda call operator doesn't refer
166 // to the lambda, but to captured "this" in the context it was created in.
167 // This can happen for operator calls and member calls, so fix it up here.
168 if (const auto *CMD = dyn_cast<CXXMethodDecl>(Val: D))
169 if (CMD->getParent()->isLambda())
170 Ctx.SelfArg = nullptr;
171
172 if (Self) {
173 assert(!Ctx.SelfArg && "Ambiguous self argument");
174 assert(isa<FunctionDecl>(D) && "Self argument requires function");
175 if (isa<CXXMethodDecl>(Val: D))
176 Ctx.SelfArg = Self;
177 else
178 Ctx.FunArgs = Self;
179
180 // If the attribute has no arguments, then assume the argument is "this".
181 if (!AttrExp)
182 return CapabilityExpr(
183 Self, cast<CXXMethodDecl>(Val: D)->getFunctionObjectParameterType(),
184 false);
185 else // For most attributes.
186 return translateAttrExpr(AttrExp, Ctx: &Ctx);
187 }
188
189 // If the attribute has no arguments, then assume the argument is "this".
190 // SelfArg may be null for non-method callees (e.g. function pointers).
191 if (!AttrExp) {
192 if (!Ctx.SelfArg)
193 return CapabilityExpr();
194 return translateAttrExpr(AttrExp: cast<const Expr *>(Val&: Ctx.SelfArg), Ctx: nullptr);
195 }
196
197 // For most attributes.
198 return translateAttrExpr(AttrExp, Ctx: &Ctx);
199}
200
201/// Translate a clang expression in an attribute to a til::SExpr.
202// This assumes a CallingContext has already been created.
203CapabilityExpr SExprBuilder::translateAttrExpr(const Expr *AttrExp,
204 CallingContext *Ctx) {
205 if (!AttrExp)
206 return CapabilityExpr();
207
208 if (const auto* SLit = dyn_cast<StringLiteral>(Val: AttrExp)) {
209 if (SLit->getString() == "*")
210 // The "*" expr is a universal lock, which essentially turns off
211 // checks until it is removed from the lockset.
212 return CapabilityExpr(new (Arena) til::Wildcard(), StringRef("wildcard"),
213 /*Neg=*/false, /*Reentrant=*/false);
214 else
215 // Ignore other string literals for now.
216 return CapabilityExpr();
217 }
218
219 bool Neg = false;
220 if (const auto *OE = dyn_cast<CXXOperatorCallExpr>(Val: AttrExp)) {
221 if (OE->getOperator() == OO_Exclaim) {
222 Neg = true;
223 AttrExp = OE->getArg(Arg: 0);
224 }
225 }
226 else if (const auto *UO = dyn_cast<UnaryOperator>(Val: AttrExp)) {
227 if (UO->getOpcode() == UO_LNot) {
228 Neg = true;
229 AttrExp = UO->getSubExpr()->IgnoreImplicit();
230 }
231 }
232
233 const til::SExpr *E = translate(S: AttrExp, Ctx);
234
235 // Trap mutex expressions like nullptr, or 0.
236 // Any literal value is nonsense.
237 if (!E || isa<til::Literal>(Val: E))
238 return CapabilityExpr();
239
240 // Hack to deal with smart pointers -- strip off top-level pointer casts.
241 if (const auto *CE = dyn_cast<til::Cast>(Val: E)) {
242 if (CE->castOpcode() == til::CAST_objToPtr)
243 E = CE->expr();
244 }
245 return CapabilityExpr(E, AttrExp->getType(), Neg);
246}
247
248til::SExpr *SExprBuilder::translateVariable(const VarDecl *VD,
249 CallingContext *Ctx) {
250 assert(VD);
251
252 // General recursion guard for x = f(x). If we are already in the process of
253 // defining VD, use its pre-assignment value to break the cycle.
254 if (VarsBeingTranslated.contains(V: VD->getCanonicalDecl()))
255 return new (Arena) til::LiteralPtr(VD);
256
257 // The closure captures state that is updated to correctly translate chains of
258 // aliases. Restore it when we are done with recursive translation.
259 llvm::scope_exit Cleanup([&, RestoreClosure = VarsBeingTranslated.empty()
260 ? LookupLocalVarExpr
261 : nullptr] {
262 VarsBeingTranslated.erase(V: VD->getCanonicalDecl());
263 if (VarsBeingTranslated.empty())
264 LookupLocalVarExpr = RestoreClosure;
265 });
266 VarsBeingTranslated.insert(V: VD->getCanonicalDecl());
267
268 QualType Ty = VD->getType();
269 if (!VD->isStaticLocal() && Ty->isPointerType()) {
270 // Substitute local variable aliases with a canonical definition.
271 if (LookupLocalVarExpr) {
272 // Attempt to resolve an alias through the more complex local variable map
273 // lookup. This will fail with complex control-flow graphs (where we
274 // revert to no alias resolution to retain stable variable names).
275 if (const Expr *E = LookupLocalVarExpr(VD)) {
276 til::SExpr *Result = translate(S: E, Ctx);
277 // Unsupported expression (such as heap allocations) will be undefined;
278 // rather than failing here, we simply revert to the pointer being the
279 // canonical variable.
280 if (Result && !isa<til::Undefined>(Val: Result))
281 return Result;
282 }
283 }
284 }
285
286 return new (Arena) til::LiteralPtr(VD);
287}
288
289// Translate a clang statement or expression to a TIL expression.
290// Also performs substitution of variables; Ctx provides the context.
291// Dispatches on the type of S.
292til::SExpr *SExprBuilder::translate(const Stmt *S, CallingContext *Ctx) {
293 if (!S)
294 return nullptr;
295
296 // Check if S has already been translated and cached.
297 // This handles the lookup of SSA names for DeclRefExprs here.
298 if (til::SExpr *E = lookupStmt(S))
299 return E;
300
301 switch (S->getStmtClass()) {
302 case Stmt::DeclRefExprClass:
303 return translateDeclRefExpr(DRE: cast<DeclRefExpr>(Val: S), Ctx);
304 case Stmt::CXXThisExprClass:
305 return translateCXXThisExpr(TE: cast<CXXThisExpr>(Val: S), Ctx);
306 case Stmt::MemberExprClass:
307 return translateMemberExpr(ME: cast<MemberExpr>(Val: S), Ctx);
308 case Stmt::ObjCIvarRefExprClass:
309 return translateObjCIVarRefExpr(IVRE: cast<ObjCIvarRefExpr>(Val: S), Ctx);
310 case Stmt::CallExprClass:
311 return translateCallExpr(CE: cast<CallExpr>(Val: S), Ctx);
312 case Stmt::CXXMemberCallExprClass:
313 return translateCXXMemberCallExpr(ME: cast<CXXMemberCallExpr>(Val: S), Ctx);
314 case Stmt::CXXOperatorCallExprClass:
315 return translateCXXOperatorCallExpr(OCE: cast<CXXOperatorCallExpr>(Val: S), Ctx);
316 case Stmt::UnaryOperatorClass:
317 return translateUnaryOperator(UO: cast<UnaryOperator>(Val: S), Ctx);
318 case Stmt::BinaryOperatorClass:
319 case Stmt::CompoundAssignOperatorClass:
320 return translateBinaryOperator(BO: cast<BinaryOperator>(Val: S), Ctx);
321
322 case Stmt::ArraySubscriptExprClass:
323 return translateArraySubscriptExpr(E: cast<ArraySubscriptExpr>(Val: S), Ctx);
324 case Stmt::ConditionalOperatorClass:
325 return translateAbstractConditionalOperator(
326 C: cast<ConditionalOperator>(Val: S), Ctx);
327 case Stmt::BinaryConditionalOperatorClass:
328 return translateAbstractConditionalOperator(
329 C: cast<BinaryConditionalOperator>(Val: S), Ctx);
330
331 // We treat these as no-ops
332 case Stmt::ConstantExprClass:
333 return translate(S: cast<ConstantExpr>(Val: S)->getSubExpr(), Ctx);
334 case Stmt::ParenExprClass:
335 return translate(S: cast<ParenExpr>(Val: S)->getSubExpr(), Ctx);
336 case Stmt::ExprWithCleanupsClass:
337 return translate(S: cast<ExprWithCleanups>(Val: S)->getSubExpr(), Ctx);
338 case Stmt::CXXBindTemporaryExprClass:
339 return translate(S: cast<CXXBindTemporaryExpr>(Val: S)->getSubExpr(), Ctx);
340 case Stmt::MaterializeTemporaryExprClass:
341 return translate(S: cast<MaterializeTemporaryExpr>(Val: S)->getSubExpr(), Ctx);
342
343 // Collect all literals
344 case Stmt::CharacterLiteralClass:
345 return new (Arena)
346 til::LiteralT<char32_t>(cast<CharacterLiteral>(Val: S)->getValue());
347 case Stmt::CXXNullPtrLiteralExprClass:
348 case Stmt::GNUNullExprClass:
349 return new (Arena) til::LiteralT(nullptr);
350 case Stmt::CXXBoolLiteralExprClass:
351 return new (Arena) til::LiteralT(cast<CXXBoolLiteralExpr>(Val: S)->getValue());
352 case Stmt::IntegerLiteralClass: {
353 const auto *IL = cast<IntegerLiteral>(Val: S);
354 const auto *BT = cast<BuiltinType>(Val: IL->getType());
355 const llvm::APInt &Value = IL->getValue();
356 if (BT->isSignedInteger())
357 return new (Arena) til::LiteralT(Value.getSExtValue());
358 else if (BT->isUnsignedInteger())
359 return new (Arena) til::LiteralT(Value.getZExtValue());
360 else
361 llvm_unreachable("Invalid integer type");
362 }
363 case Stmt::StringLiteralClass:
364 return new (Arena) til::LiteralT(cast<StringLiteral>(Val: S)->getBytes());
365 case Stmt::ObjCStringLiteralClass:
366 return new (Arena)
367 til::LiteralT(cast<ObjCStringLiteral>(Val: S)->getString()->getBytes());
368
369 case Stmt::DeclStmtClass:
370 return translateDeclStmt(S: cast<DeclStmt>(Val: S), Ctx);
371 case Stmt::StmtExprClass:
372 return translateStmtExpr(SE: cast<StmtExpr>(Val: S), Ctx);
373 default:
374 break;
375 }
376 if (const auto *CE = dyn_cast<CastExpr>(Val: S))
377 return translateCastExpr(CE, Ctx);
378
379 return new (Arena) til::Undefined(S);
380}
381
382/// Helper to extract the canonical parameter declaration from a function or
383/// function pointer. This unwraps pointer and reference types to reach the
384/// underlying function prototype.
385static const ParmVarDecl *getCanonicalParamDecl(const Decl *D, unsigned I) {
386 if (const auto *FD = dyn_cast<FunctionDecl>(Val: D))
387 return FD->getCanonicalDecl()->getParamDecl(i: I);
388 if (const auto *MD = dyn_cast<ObjCMethodDecl>(Val: D))
389 return MD->getCanonicalDecl()->getParamDecl(Idx: I);
390 if (const auto *DD = dyn_cast<DeclaratorDecl>(Val: D)) {
391 if (auto *TSI = DD->getTypeSourceInfo()) {
392 TypeLoc TL = TSI->getTypeLoc();
393 if (auto RTL = TL.getAsAdjusted<ReferenceTypeLoc>())
394 TL = RTL.getPointeeLoc();
395 // A function pointer can be multiple levels deep.
396 while (auto PTL = TL.getAsAdjusted<PointerTypeLoc>())
397 TL = PTL.getPointeeLoc();
398 if (auto FPTL = TL.getAsAdjusted<FunctionProtoTypeLoc>())
399 if (I < FPTL.getNumParams())
400 return FPTL.getParam(i: I);
401 }
402 }
403 return nullptr;
404}
405
406static const ValueDecl *getValueDeclFromSExpr(const til::SExpr *E) {
407 if (const auto *V = dyn_cast<til::Variable>(Val: E))
408 return V->clangDecl();
409 if (const auto *Ph = dyn_cast<til::Phi>(Val: E))
410 return Ph->clangDecl();
411 if (const auto *P = dyn_cast<til::Project>(Val: E))
412 return P->clangDecl();
413 if (const auto *L = dyn_cast<til::LiteralPtr>(Val: E))
414 return L->clangDecl();
415 return nullptr;
416}
417
418static bool hasAnyPointerType(const til::SExpr *E) {
419 auto *VD = getValueDeclFromSExpr(E);
420 if (VD && VD->getType()->isAnyPointerType())
421 return true;
422 if (const auto *C = dyn_cast<til::Cast>(Val: E))
423 return C->castOpcode() == til::CAST_objToPtr;
424
425 return false;
426}
427
428til::SExpr *SExprBuilder::translateDeclRefExpr(const DeclRefExpr *DRE,
429 CallingContext *Ctx) {
430 const auto *VD = cast<ValueDecl>(Val: DRE->getDecl()->getCanonicalDecl());
431
432 // Function parameters require substitution and/or renaming.
433 if (const auto *PV = dyn_cast<ParmVarDecl>(Val: VD)) {
434 unsigned I = PV->getFunctionScopeIndex();
435 const DeclContext *D = PV->getDeclContext();
436 if (Ctx && Ctx->FunArgs) {
437 const Decl *Canonical = Ctx->AttrDecl->getCanonicalDecl();
438 bool Match = false;
439 if (const auto *FD = dyn_cast<FunctionDecl>(Val: D))
440 Match = (FD->getCanonicalDecl() == Canonical);
441 else if (const auto *MD = dyn_cast<ObjCMethodDecl>(Val: D))
442 Match = (MD->getCanonicalDecl() == Canonical);
443 else if (getCanonicalParamDecl(D: Canonical, I) == PV->getCanonicalDecl())
444 Match = true;
445 else
446 llvm_unreachable("ParmVarDecl does not belong to current declaration");
447
448 if (Match) {
449 // Substitute call arguments for references to function parameters
450 if (const Expr *const *FunArgs =
451 dyn_cast<const Expr *const *>(Val&: Ctx->FunArgs)) {
452 assert(I < Ctx->NumArgs);
453 return translate(S: FunArgs[I], Ctx: Ctx->Prev);
454 }
455
456 assert(I == 0);
457 return cast<til::SExpr *>(Val&: Ctx->FunArgs);
458 }
459 }
460 // Map the param back to the param of the original function declaration
461 // for consistent comparisons.
462 if (const auto *PVD = getCanonicalParamDecl(D: cast<Decl>(Val: D), I))
463 VD = PVD;
464 }
465
466 if (const auto *VarD = dyn_cast<VarDecl>(Val: VD))
467 return translateVariable(VD: VarD, Ctx);
468
469 // FIXME: A FieldDecl reached via a DeclRefExpr should ideally be modelled as
470 // a MemberExpr with an artificial self in the AST (e.g. ImplicitThisExpr as a
471 // C equivalent of CXXThisExpr). Until such AST support is available, project
472 // the field on the current SelfArg, so implicit member references in C and in
473 // parameter attributes are not lost.
474 if (const auto *FD = dyn_cast<FieldDecl>(Val: VD); FD && Ctx && Ctx->SelfArg) {
475 til::SExpr *BE = translateCXXThisExpr(TE: nullptr, Ctx);
476 til::SExpr *E = new (Arena) til::SApply(BE);
477 til::Project *P = new (Arena) til::Project(E, FD);
478 if (hasAnyPointerType(E: BE))
479 P->setArrow(true);
480 return P;
481 }
482
483 // For non-local variables, treat it as a reference to a named object.
484 return new (Arena) til::LiteralPtr(VD);
485}
486
487til::SExpr *SExprBuilder::translateCXXThisExpr(const CXXThisExpr *TE,
488 CallingContext *Ctx) {
489 // Substitute for 'this'
490 if (Ctx && Ctx->SelfArg) {
491 if (const auto *SelfArg = dyn_cast<const Expr *>(Val&: Ctx->SelfArg))
492 return translate(S: SelfArg, Ctx: Ctx->Prev);
493 else
494 return cast<til::SExpr *>(Val&: Ctx->SelfArg);
495 }
496 assert(SelfVar && "We have no variable for 'this'!");
497 return SelfVar;
498}
499
500// Grab the very first declaration of virtual method D
501static const CXXMethodDecl *getFirstVirtualDecl(const CXXMethodDecl *D) {
502 while (true) {
503 D = D->getCanonicalDecl();
504 auto OverriddenMethods = D->overridden_methods();
505 if (OverriddenMethods.begin() == OverriddenMethods.end())
506 return D; // Method does not override anything
507 // FIXME: this does not work with multiple inheritance.
508 D = *OverriddenMethods.begin();
509 }
510 return nullptr;
511}
512
513til::SExpr *SExprBuilder::translateMemberExpr(const MemberExpr *ME,
514 CallingContext *Ctx) {
515 til::SExpr *BE = translate(S: ME->getBase(), Ctx);
516 til::SExpr *E = new (Arena) til::SApply(BE);
517
518 const auto *D = cast<ValueDecl>(Val: ME->getMemberDecl()->getCanonicalDecl());
519 if (const auto *VD = dyn_cast<CXXMethodDecl>(Val: D))
520 D = getFirstVirtualDecl(D: VD);
521
522 til::Project *P = new (Arena) til::Project(E, D);
523 if (hasAnyPointerType(E: BE))
524 P->setArrow(true);
525 return P;
526}
527
528til::SExpr *SExprBuilder::translateObjCIVarRefExpr(const ObjCIvarRefExpr *IVRE,
529 CallingContext *Ctx) {
530 til::SExpr *BE = translate(S: IVRE->getBase(), Ctx);
531 til::SExpr *E = new (Arena) til::SApply(BE);
532
533 const auto *D = cast<ObjCIvarDecl>(Val: IVRE->getDecl()->getCanonicalDecl());
534
535 til::Project *P = new (Arena) til::Project(E, D);
536 if (hasAnyPointerType(E: BE))
537 P->setArrow(true);
538 return P;
539}
540
541til::SExpr *SExprBuilder::translateCallExpr(const CallExpr *CE,
542 CallingContext *Ctx,
543 const Expr *SelfE) {
544 if (CapabilityExprMode) {
545 // Handle LOCK_RETURNED
546 if (const FunctionDecl *FD = CE->getDirectCallee()) {
547 FD = FD->getMostRecentDecl();
548 if (LockReturnedAttr *At = FD->getAttr<LockReturnedAttr>()) {
549 CallingContext LRCallCtx(Ctx);
550 LRCallCtx.AttrDecl = CE->getDirectCallee();
551 LRCallCtx.SelfArg = SelfE;
552 LRCallCtx.NumArgs = CE->getNumArgs();
553 LRCallCtx.FunArgs = CE->getArgs();
554 return const_cast<til::SExpr *>(
555 translateAttrExpr(AttrExp: At->getArg(), Ctx: &LRCallCtx).sexpr());
556 }
557 }
558 }
559
560 til::SExpr *E = translate(S: CE->getCallee(), Ctx);
561 for (const auto *Arg : CE->arguments()) {
562 til::SExpr *A = translate(S: Arg, Ctx);
563 E = new (Arena) til::Apply(E, A);
564 }
565 return new (Arena) til::Call(E, CE);
566}
567
568til::SExpr *SExprBuilder::translateCXXMemberCallExpr(
569 const CXXMemberCallExpr *ME, CallingContext *Ctx) {
570 if (CapabilityExprMode) {
571 // Ignore calls to get() on smart pointers.
572 if (ME->getMethodDecl()->getNameAsString() == "get" &&
573 ME->getNumArgs() == 0) {
574 auto *E = translate(S: ME->getImplicitObjectArgument(), Ctx);
575 return new (Arena) til::Cast(til::CAST_objToPtr, E);
576 // return E;
577 }
578 }
579 return translateCallExpr(CE: cast<CallExpr>(Val: ME), Ctx,
580 SelfE: ME->getImplicitObjectArgument());
581}
582
583til::SExpr *SExprBuilder::translateCXXOperatorCallExpr(
584 const CXXOperatorCallExpr *OCE, CallingContext *Ctx) {
585 if (CapabilityExprMode) {
586 // Ignore operator * and operator -> on smart pointers.
587 OverloadedOperatorKind k = OCE->getOperator();
588 if (k == OO_Star || k == OO_Arrow) {
589 auto *E = translate(S: OCE->getArg(Arg: 0), Ctx);
590 return new (Arena) til::Cast(til::CAST_objToPtr, E);
591 // return E;
592 }
593 }
594 return translateCallExpr(CE: cast<CallExpr>(Val: OCE), Ctx);
595}
596
597til::SExpr *SExprBuilder::translateUnaryOperator(const UnaryOperator *UO,
598 CallingContext *Ctx) {
599 switch (UO->getOpcode()) {
600 case UO_PostInc:
601 case UO_PostDec:
602 case UO_PreInc:
603 case UO_PreDec:
604 return new (Arena) til::Undefined(UO);
605
606 case UO_AddrOf:
607 if (CapabilityExprMode) {
608 // interpret &Graph::mu_ as an existential.
609 if (const auto *DRE = dyn_cast<DeclRefExpr>(Val: UO->getSubExpr())) {
610 if (DRE->getDecl()->isCXXInstanceMember()) {
611 // This is a pointer-to-member expression, e.g. &MyClass::mu_.
612 // We interpret this syntax specially, as a wildcard.
613 auto *W = new (Arena) til::Wildcard();
614 return new (Arena) til::Project(W, DRE->getDecl());
615 }
616 }
617 }
618 // otherwise, & is a no-op
619 return translate(S: UO->getSubExpr(), Ctx);
620
621 // We treat these as no-ops
622 case UO_Deref:
623 case UO_Plus:
624 return translate(S: UO->getSubExpr(), Ctx);
625
626 case UO_Minus:
627 return new (Arena)
628 til::UnaryOp(til::UOP_Minus, translate(S: UO->getSubExpr(), Ctx));
629 case UO_Not:
630 return new (Arena)
631 til::UnaryOp(til::UOP_BitNot, translate(S: UO->getSubExpr(), Ctx));
632 case UO_LNot:
633 return new (Arena)
634 til::UnaryOp(til::UOP_LogicNot, translate(S: UO->getSubExpr(), Ctx));
635
636 // Currently unsupported
637 case UO_Real:
638 case UO_Imag:
639 case UO_Extension:
640 case UO_Coawait:
641 return new (Arena) til::Undefined(UO);
642 }
643 return new (Arena) til::Undefined(UO);
644}
645
646til::SExpr *SExprBuilder::translateBinOp(til::TIL_BinaryOpcode Op,
647 const BinaryOperator *BO,
648 CallingContext *Ctx, bool Reverse) {
649 til::SExpr *E0 = translate(S: BO->getLHS(), Ctx);
650 til::SExpr *E1 = translate(S: BO->getRHS(), Ctx);
651 if (Reverse)
652 return new (Arena) til::BinaryOp(Op, E1, E0);
653 else
654 return new (Arena) til::BinaryOp(Op, E0, E1);
655}
656
657til::SExpr *SExprBuilder::translateBinAssign(til::TIL_BinaryOpcode Op,
658 const BinaryOperator *BO,
659 CallingContext *Ctx,
660 bool Assign) {
661 const Expr *LHS = BO->getLHS();
662 const Expr *RHS = BO->getRHS();
663 til::SExpr *E0 = translate(S: LHS, Ctx);
664 til::SExpr *E1 = translate(S: RHS, Ctx);
665
666 const ValueDecl *VD = nullptr;
667 til::SExpr *CV = nullptr;
668 if (const auto *DRE = dyn_cast<DeclRefExpr>(Val: LHS)) {
669 VD = DRE->getDecl();
670 CV = lookupVarDecl(VD);
671 }
672
673 if (!Assign) {
674 til::SExpr *Arg = CV ? CV : new (Arena) til::Load(E0);
675 E1 = new (Arena) til::BinaryOp(Op, Arg, E1);
676 E1 = addStatement(E: E1, S: nullptr, VD);
677 }
678 if (VD && CV)
679 return updateVarDecl(VD, E: E1);
680 return new (Arena) til::Store(E0, E1);
681}
682
683til::SExpr *SExprBuilder::translateBinaryOperator(const BinaryOperator *BO,
684 CallingContext *Ctx) {
685 switch (BO->getOpcode()) {
686 case BO_PtrMemD:
687 case BO_PtrMemI:
688 return new (Arena) til::Undefined(BO);
689
690 case BO_Mul: return translateBinOp(Op: til::BOP_Mul, BO, Ctx);
691 case BO_Div: return translateBinOp(Op: til::BOP_Div, BO, Ctx);
692 case BO_Rem: return translateBinOp(Op: til::BOP_Rem, BO, Ctx);
693 case BO_Add: return translateBinOp(Op: til::BOP_Add, BO, Ctx);
694 case BO_Sub: return translateBinOp(Op: til::BOP_Sub, BO, Ctx);
695 case BO_Shl: return translateBinOp(Op: til::BOP_Shl, BO, Ctx);
696 case BO_Shr: return translateBinOp(Op: til::BOP_Shr, BO, Ctx);
697 case BO_LT: return translateBinOp(Op: til::BOP_Lt, BO, Ctx);
698 case BO_GT: return translateBinOp(Op: til::BOP_Lt, BO, Ctx, Reverse: true);
699 case BO_LE: return translateBinOp(Op: til::BOP_Leq, BO, Ctx);
700 case BO_GE: return translateBinOp(Op: til::BOP_Leq, BO, Ctx, Reverse: true);
701 case BO_EQ: return translateBinOp(Op: til::BOP_Eq, BO, Ctx);
702 case BO_NE: return translateBinOp(Op: til::BOP_Neq, BO, Ctx);
703 case BO_Cmp: return translateBinOp(Op: til::BOP_Cmp, BO, Ctx);
704 case BO_And: return translateBinOp(Op: til::BOP_BitAnd, BO, Ctx);
705 case BO_Xor: return translateBinOp(Op: til::BOP_BitXor, BO, Ctx);
706 case BO_Or: return translateBinOp(Op: til::BOP_BitOr, BO, Ctx);
707 case BO_LAnd: return translateBinOp(Op: til::BOP_LogicAnd, BO, Ctx);
708 case BO_LOr: return translateBinOp(Op: til::BOP_LogicOr, BO, Ctx);
709
710 case BO_Assign: return translateBinAssign(Op: til::BOP_Eq, BO, Ctx, Assign: true);
711 case BO_MulAssign: return translateBinAssign(Op: til::BOP_Mul, BO, Ctx);
712 case BO_DivAssign: return translateBinAssign(Op: til::BOP_Div, BO, Ctx);
713 case BO_RemAssign: return translateBinAssign(Op: til::BOP_Rem, BO, Ctx);
714 case BO_AddAssign: return translateBinAssign(Op: til::BOP_Add, BO, Ctx);
715 case BO_SubAssign: return translateBinAssign(Op: til::BOP_Sub, BO, Ctx);
716 case BO_ShlAssign: return translateBinAssign(Op: til::BOP_Shl, BO, Ctx);
717 case BO_ShrAssign: return translateBinAssign(Op: til::BOP_Shr, BO, Ctx);
718 case BO_AndAssign: return translateBinAssign(Op: til::BOP_BitAnd, BO, Ctx);
719 case BO_XorAssign: return translateBinAssign(Op: til::BOP_BitXor, BO, Ctx);
720 case BO_OrAssign: return translateBinAssign(Op: til::BOP_BitOr, BO, Ctx);
721
722 case BO_Comma:
723 // The clang CFG should have already processed both sides.
724 return translate(S: BO->getRHS(), Ctx);
725 }
726 return new (Arena) til::Undefined(BO);
727}
728
729til::SExpr *SExprBuilder::translateCastExpr(const CastExpr *CE,
730 CallingContext *Ctx) {
731 CastKind K = CE->getCastKind();
732 switch (K) {
733 case CK_LValueToRValue: {
734 if (const auto *DRE = dyn_cast<DeclRefExpr>(Val: CE->getSubExpr())) {
735 til::SExpr *E0 = lookupVarDecl(VD: DRE->getDecl());
736 if (E0)
737 return E0;
738 }
739 til::SExpr *E0 = translate(S: CE->getSubExpr(), Ctx);
740 return E0;
741 // FIXME!! -- get Load working properly
742 // return new (Arena) til::Load(E0);
743 }
744 case CK_NoOp:
745 case CK_DerivedToBase:
746 case CK_UncheckedDerivedToBase:
747 case CK_ArrayToPointerDecay:
748 case CK_FunctionToPointerDecay: {
749 til::SExpr *E0 = translate(S: CE->getSubExpr(), Ctx);
750 return E0;
751 }
752 default: {
753 // FIXME: handle different kinds of casts.
754 til::SExpr *E0 = translate(S: CE->getSubExpr(), Ctx);
755 if (CapabilityExprMode)
756 return E0;
757 return new (Arena) til::Cast(til::CAST_none, E0);
758 }
759 }
760}
761
762til::SExpr *
763SExprBuilder::translateArraySubscriptExpr(const ArraySubscriptExpr *E,
764 CallingContext *Ctx) {
765 til::SExpr *E0 = translate(S: E->getBase(), Ctx);
766 til::SExpr *E1 = translate(S: E->getIdx(), Ctx);
767 return new (Arena) til::ArrayIndex(E0, E1);
768}
769
770til::SExpr *
771SExprBuilder::translateAbstractConditionalOperator(
772 const AbstractConditionalOperator *CO, CallingContext *Ctx) {
773 auto *C = translate(S: CO->getCond(), Ctx);
774 auto *T = translate(S: CO->getTrueExpr(), Ctx);
775 auto *E = translate(S: CO->getFalseExpr(), Ctx);
776 return new (Arena) til::IfThenElse(C, T, E);
777}
778
779til::SExpr *
780SExprBuilder::translateDeclStmt(const DeclStmt *S, CallingContext *Ctx) {
781 DeclGroupRef DGrp = S->getDeclGroup();
782 for (auto *I : DGrp) {
783 if (auto *VD = dyn_cast_or_null<VarDecl>(Val: I)) {
784 Expr *E = VD->getInit();
785 til::SExpr* SE = translate(S: E, Ctx);
786
787 // Add local variables with trivial type to the variable map
788 QualType T = VD->getType();
789 if (T.isTrivialType(Context: VD->getASTContext()))
790 return addVarDecl(VD, E: SE);
791 else {
792 // TODO: add alloca
793 }
794 }
795 }
796 return nullptr;
797}
798
799til::SExpr *SExprBuilder::translateStmtExpr(const StmtExpr *SE,
800 CallingContext *Ctx) {
801 // The value of a statement expression is the value of the last statement,
802 // which must be an expression.
803 const CompoundStmt *CS = SE->getSubStmt();
804 return CS->body_empty() ? new (Arena) til::Undefined(SE)
805 : translate(S: CS->body_back(), Ctx);
806}
807
808// If (E) is non-trivial, then add it to the current basic block, and
809// update the statement map so that S refers to E. Returns a new variable
810// that refers to E.
811// If E is trivial returns E.
812til::SExpr *SExprBuilder::addStatement(til::SExpr* E, const Stmt *S,
813 const ValueDecl *VD) {
814 if (!E || !CurrentBB || E->block() || til::ThreadSafetyTIL::isTrivial(E))
815 return E;
816 if (VD)
817 E = new (Arena) til::Variable(E, VD);
818 CurrentInstructions.push_back(x: E);
819 if (S)
820 insertStmt(S, E);
821 return E;
822}
823
824// Returns the current value of VD, if known, and nullptr otherwise.
825til::SExpr *SExprBuilder::lookupVarDecl(const ValueDecl *VD) {
826 auto It = LVarIdxMap.find(Val: VD);
827 if (It != LVarIdxMap.end()) {
828 assert(CurrentLVarMap[It->second].first == VD);
829 return CurrentLVarMap[It->second].second;
830 }
831 return nullptr;
832}
833
834// if E is a til::Variable, update its clangDecl.
835static void maybeUpdateVD(til::SExpr *E, const ValueDecl *VD) {
836 if (!E)
837 return;
838 if (auto *V = dyn_cast<til::Variable>(Val: E)) {
839 if (!V->clangDecl())
840 V->setClangDecl(VD);
841 }
842}
843
844// Adds a new variable declaration.
845til::SExpr *SExprBuilder::addVarDecl(const ValueDecl *VD, til::SExpr *E) {
846 maybeUpdateVD(E, VD);
847 LVarIdxMap.insert(KV: std::make_pair(x&: VD, y: CurrentLVarMap.size()));
848 CurrentLVarMap.makeWritable();
849 CurrentLVarMap.push_back(Elem: std::make_pair(x&: VD, y&: E));
850 return E;
851}
852
853// Updates a current variable declaration. (E.g. by assignment)
854til::SExpr *SExprBuilder::updateVarDecl(const ValueDecl *VD, til::SExpr *E) {
855 maybeUpdateVD(E, VD);
856 auto It = LVarIdxMap.find(Val: VD);
857 if (It == LVarIdxMap.end()) {
858 til::SExpr *Ptr = new (Arena) til::LiteralPtr(VD);
859 til::SExpr *St = new (Arena) til::Store(Ptr, E);
860 return St;
861 }
862 CurrentLVarMap.makeWritable();
863 CurrentLVarMap.elem(i: It->second).second = E;
864 return E;
865}
866
867// Make a Phi node in the current block for the i^th variable in CurrentVarMap.
868// If E != null, sets Phi[CurrentBlockInfo->ArgIndex] = E.
869// If E == null, this is a backedge and will be set later.
870void SExprBuilder::makePhiNodeVar(unsigned i, unsigned NPreds, til::SExpr *E) {
871 unsigned ArgIndex = CurrentBlockInfo->ProcessedPredecessors;
872 assert(ArgIndex > 0 && ArgIndex < NPreds);
873
874 til::SExpr *CurrE = CurrentLVarMap[i].second;
875 if (CurrE->block() == CurrentBB) {
876 // We already have a Phi node in the current block,
877 // so just add the new variable to the Phi node.
878 auto *Ph = dyn_cast<til::Phi>(Val: CurrE);
879 assert(Ph && "Expecting Phi node.");
880 if (E)
881 Ph->values()[ArgIndex] = E;
882 return;
883 }
884
885 // Make a new phi node: phi(..., E)
886 // All phi args up to the current index are set to the current value.
887 til::Phi *Ph = new (Arena) til::Phi(Arena, NPreds);
888 Ph->values().setValues(Sz: NPreds, C: nullptr);
889 for (unsigned PIdx = 0; PIdx < ArgIndex; ++PIdx)
890 Ph->values()[PIdx] = CurrE;
891 if (E)
892 Ph->values()[ArgIndex] = E;
893 Ph->setClangDecl(CurrentLVarMap[i].first);
894 // If E is from a back-edge, or either E or CurrE are incomplete, then
895 // mark this node as incomplete; we may need to remove it later.
896 if (!E || isIncompletePhi(E) || isIncompletePhi(E: CurrE))
897 Ph->setStatus(til::Phi::PH_Incomplete);
898
899 // Add Phi node to current block, and update CurrentLVarMap[i]
900 CurrentArguments.push_back(x: Ph);
901 if (Ph->status() == til::Phi::PH_Incomplete)
902 IncompleteArgs.push_back(x: Ph);
903
904 CurrentLVarMap.makeWritable();
905 CurrentLVarMap.elem(i).second = Ph;
906}
907
908// Merge values from Map into the current variable map.
909// This will construct Phi nodes in the current basic block as necessary.
910void SExprBuilder::mergeEntryMap(LVarDefinitionMap Map) {
911 assert(CurrentBlockInfo && "Not processing a block!");
912
913 if (!CurrentLVarMap.valid()) {
914 // Steal Map, using copy-on-write.
915 CurrentLVarMap = std::move(Map);
916 return;
917 }
918 if (CurrentLVarMap.sameAs(V: Map))
919 return; // Easy merge: maps from different predecessors are unchanged.
920
921 unsigned NPreds = CurrentBB->numPredecessors();
922 unsigned ESz = CurrentLVarMap.size();
923 unsigned MSz = Map.size();
924 unsigned Sz = std::min(a: ESz, b: MSz);
925
926 for (unsigned i = 0; i < Sz; ++i) {
927 if (CurrentLVarMap[i].first != Map[i].first) {
928 // We've reached the end of variables in common.
929 CurrentLVarMap.makeWritable();
930 CurrentLVarMap.downsize(i);
931 break;
932 }
933 if (CurrentLVarMap[i].second != Map[i].second)
934 makePhiNodeVar(i, NPreds, E: Map[i].second);
935 }
936 if (ESz > MSz) {
937 CurrentLVarMap.makeWritable();
938 CurrentLVarMap.downsize(i: Map.size());
939 }
940}
941
942// Merge a back edge into the current variable map.
943// This will create phi nodes for all variables in the variable map.
944void SExprBuilder::mergeEntryMapBackEdge() {
945 // We don't have definitions for variables on the backedge, because we
946 // haven't gotten that far in the CFG. Thus, when encountering a back edge,
947 // we conservatively create Phi nodes for all variables. Unnecessary Phi
948 // nodes will be marked as incomplete, and stripped out at the end.
949 //
950 // An Phi node is unnecessary if it only refers to itself and one other
951 // variable, e.g. x = Phi(y, y, x) can be reduced to x = y.
952
953 assert(CurrentBlockInfo && "Not processing a block!");
954
955 if (CurrentBlockInfo->HasBackEdges)
956 return;
957 CurrentBlockInfo->HasBackEdges = true;
958
959 CurrentLVarMap.makeWritable();
960 unsigned Sz = CurrentLVarMap.size();
961 unsigned NPreds = CurrentBB->numPredecessors();
962
963 for (unsigned i = 0; i < Sz; ++i)
964 makePhiNodeVar(i, NPreds, E: nullptr);
965}
966
967// Update the phi nodes that were initially created for a back edge
968// once the variable definitions have been computed.
969// I.e., merge the current variable map into the phi nodes for Blk.
970void SExprBuilder::mergePhiNodesBackEdge(const CFGBlock *Blk) {
971 til::BasicBlock *BB = lookupBlock(B: Blk);
972 unsigned ArgIndex = BBInfo[Blk->getBlockID()].ProcessedPredecessors;
973 assert(ArgIndex > 0 && ArgIndex < BB->numPredecessors());
974
975 for (til::SExpr *PE : BB->arguments()) {
976 auto *Ph = dyn_cast_or_null<til::Phi>(Val: PE);
977 assert(Ph && "Expecting Phi Node.");
978 assert(Ph->values()[ArgIndex] == nullptr && "Wrong index for back edge.");
979
980 til::SExpr *E = lookupVarDecl(VD: Ph->clangDecl());
981 assert(E && "Couldn't find local variable for Phi node.");
982 Ph->values()[ArgIndex] = E;
983 }
984}
985
986void SExprBuilder::enterCFG(CFG *Cfg, const NamedDecl *D,
987 const CFGBlock *First) {
988 // Perform initial setup operations.
989 unsigned NBlocks = Cfg->getNumBlockIDs();
990 Scfg = new (Arena) til::SCFG(Arena, NBlocks);
991
992 // allocate all basic blocks immediately, to handle forward references.
993 BBInfo.resize(new_size: NBlocks);
994 BlockMap.resize(new_size: NBlocks, x: nullptr);
995 // create map from clang blockID to til::BasicBlocks
996 for (auto *B : *Cfg) {
997 auto *BB = new (Arena) til::BasicBlock(Arena);
998 BB->reserveInstructions(Nins: B->size());
999 BlockMap[B->getBlockID()] = BB;
1000 }
1001
1002 CurrentBB = lookupBlock(B: &Cfg->getEntry());
1003 auto Parms = isa<ObjCMethodDecl>(Val: D) ? cast<ObjCMethodDecl>(Val: D)->parameters()
1004 : cast<FunctionDecl>(Val: D)->parameters();
1005 for (auto *Pm : Parms) {
1006 QualType T = Pm->getType();
1007 if (!T.isTrivialType(Context: Pm->getASTContext()))
1008 continue;
1009
1010 // Add parameters to local variable map.
1011 // FIXME: right now we emulate params with loads; that should be fixed.
1012 til::SExpr *Lp = new (Arena) til::LiteralPtr(Pm);
1013 til::SExpr *Ld = new (Arena) til::Load(Lp);
1014 til::SExpr *V = addStatement(E: Ld, S: nullptr, VD: Pm);
1015 addVarDecl(VD: Pm, E: V);
1016 }
1017}
1018
1019void SExprBuilder::enterCFGBlock(const CFGBlock *B) {
1020 // Initialize TIL basic block and add it to the CFG.
1021 CurrentBB = lookupBlock(B);
1022 CurrentBB->reservePredecessors(NumPreds: B->pred_size());
1023 Scfg->add(BB: CurrentBB);
1024
1025 CurrentBlockInfo = &BBInfo[B->getBlockID()];
1026
1027 // CurrentLVarMap is moved to ExitMap on block exit.
1028 // FIXME: the entry block will hold function parameters.
1029 // assert(!CurrentLVarMap.valid() && "CurrentLVarMap already initialized.");
1030}
1031
1032void SExprBuilder::handlePredecessor(const CFGBlock *Pred) {
1033 // Compute CurrentLVarMap on entry from ExitMaps of predecessors
1034
1035 CurrentBB->addPredecessor(Pred: BlockMap[Pred->getBlockID()]);
1036 BlockInfo *PredInfo = &BBInfo[Pred->getBlockID()];
1037 assert(PredInfo->UnprocessedSuccessors > 0);
1038
1039 if (--PredInfo->UnprocessedSuccessors == 0)
1040 mergeEntryMap(Map: std::move(PredInfo->ExitMap));
1041 else
1042 mergeEntryMap(Map: PredInfo->ExitMap.clone());
1043
1044 ++CurrentBlockInfo->ProcessedPredecessors;
1045}
1046
1047void SExprBuilder::handlePredecessorBackEdge(const CFGBlock *Pred) {
1048 mergeEntryMapBackEdge();
1049}
1050
1051void SExprBuilder::enterCFGBlockBody(const CFGBlock *B) {
1052 // The merge*() methods have created arguments.
1053 // Push those arguments onto the basic block.
1054 CurrentBB->arguments().reserve(
1055 Ncp: static_cast<unsigned>(CurrentArguments.size()), A: Arena);
1056 for (auto *A : CurrentArguments)
1057 CurrentBB->addArgument(V: A);
1058}
1059
1060void SExprBuilder::handleStatement(const Stmt *S) {
1061 til::SExpr *E = translate(S, Ctx: nullptr);
1062 addStatement(E, S);
1063}
1064
1065void SExprBuilder::handleDestructorCall(const VarDecl *VD,
1066 const CXXDestructorDecl *DD) {
1067 til::SExpr *Sf = new (Arena) til::LiteralPtr(VD);
1068 til::SExpr *Dr = new (Arena) til::LiteralPtr(DD);
1069 til::SExpr *Ap = new (Arena) til::Apply(Dr, Sf);
1070 til::SExpr *E = new (Arena) til::Call(Ap);
1071 addStatement(E, S: nullptr);
1072}
1073
1074void SExprBuilder::exitCFGBlockBody(const CFGBlock *B) {
1075 CurrentBB->instructions().reserve(
1076 Ncp: static_cast<unsigned>(CurrentInstructions.size()), A: Arena);
1077 for (auto *V : CurrentInstructions)
1078 CurrentBB->addInstruction(V);
1079
1080 // Create an appropriate terminator
1081 unsigned N = B->succ_size();
1082 auto It = B->succ_begin();
1083 if (N == 1) {
1084 til::BasicBlock *BB = *It ? lookupBlock(B: *It) : nullptr;
1085 // TODO: set index
1086 unsigned Idx = BB ? BB->findPredecessorIndex(BB: CurrentBB) : 0;
1087 auto *Tm = new (Arena) til::Goto(BB, Idx);
1088 CurrentBB->setTerminator(Tm);
1089 }
1090 else if (N == 2) {
1091 til::SExpr *C = translate(S: B->getTerminatorCondition(StripParens: true), Ctx: nullptr);
1092 til::BasicBlock *BB1 = *It ? lookupBlock(B: *It) : nullptr;
1093 ++It;
1094 til::BasicBlock *BB2 = *It ? lookupBlock(B: *It) : nullptr;
1095 // FIXME: make sure these aren't critical edges.
1096 auto *Tm = new (Arena) til::Branch(C, BB1, BB2);
1097 CurrentBB->setTerminator(Tm);
1098 }
1099}
1100
1101void SExprBuilder::handleSuccessor(const CFGBlock *Succ) {
1102 ++CurrentBlockInfo->UnprocessedSuccessors;
1103}
1104
1105void SExprBuilder::handleSuccessorBackEdge(const CFGBlock *Succ) {
1106 mergePhiNodesBackEdge(Blk: Succ);
1107 ++BBInfo[Succ->getBlockID()].ProcessedPredecessors;
1108}
1109
1110void SExprBuilder::exitCFGBlock(const CFGBlock *B) {
1111 CurrentArguments.clear();
1112 CurrentInstructions.clear();
1113 CurrentBlockInfo->ExitMap = std::move(CurrentLVarMap);
1114 CurrentBB = nullptr;
1115 CurrentBlockInfo = nullptr;
1116}
1117
1118void SExprBuilder::exitCFG(const CFGBlock *Last) {
1119 for (auto *Ph : IncompleteArgs) {
1120 if (Ph->status() == til::Phi::PH_Incomplete)
1121 simplifyIncompleteArg(Ph);
1122 }
1123
1124 CurrentArguments.clear();
1125 CurrentInstructions.clear();
1126 IncompleteArgs.clear();
1127}
1128
1129#ifndef NDEBUG
1130namespace {
1131
1132class TILPrinter :
1133 public til::PrettyPrinter<TILPrinter, llvm::raw_ostream> {};
1134
1135} // namespace
1136
1137namespace clang {
1138namespace threadSafety {
1139
1140void printSCFG(CFGWalker &Walker) {
1141 llvm::BumpPtrAllocator Bpa;
1142 til::MemRegionRef Arena(&Bpa);
1143 SExprBuilder SxBuilder(Arena);
1144 til::SCFG *Scfg = SxBuilder.buildCFG(Walker);
1145 TILPrinter::print(Scfg, llvm::errs());
1146}
1147
1148} // namespace threadSafety
1149} // namespace clang
1150#endif // NDEBUG
1151