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