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