clang 23.0.0git
ThreadSafetyCommon.cpp
Go to the documentation of this file.
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
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"
22#include "clang/AST/Stmt.h"
23#include "clang/AST/Type.h"
25#include "clang/Analysis/CFG.h"
26#include "clang/Basic/LLVM.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
42 switch (CE->getStmtClass()) {
43 case Stmt::IntegerLiteralClass:
44 return toString(cast<IntegerLiteral>(CE)->getValue(), 10, true);
45 case Stmt::StringLiteralClass: {
46 std::string ret("\"");
47 ret += cast<StringLiteral>(CE)->getString();
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>(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
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(*RD);
89 if (const auto *TT = QT->getAs<TypedefType>())
90 return classifyCapability(*TT->getDecl());
93
95}
96
98 const auto &[Kind, Reentrant] = classifyCapability(QT);
99 *this = CapabilityExpr(E, Kind, Neg, Reentrant);
100}
101
103
104til::SExpr *SExprBuilder::lookupStmt(const Stmt *S) { return SMap.lookup(S); }
105
107 Walker.walk(*this);
108 return Scfg;
109}
110
111static bool isCalleeArrow(const Expr *E) {
112 const auto *ME = dyn_cast<MemberExpr>(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.
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, 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>(DeclExp)) {
140 Ctx.SelfArg = ME->getBase();
141 Ctx.SelfArrow = ME->isArrow();
142 } else if (const auto *CE = dyn_cast<CXXMemberCallExpr>(DeclExp)) {
143 Ctx.SelfArg = CE->getImplicitObjectArgument();
144 Ctx.SelfArrow = isCalleeArrow(CE->getCallee());
145 Ctx.NumArgs = CE->getNumArgs();
146 Ctx.FunArgs = CE->getArgs();
147 } else if (const auto *CE = dyn_cast<CallExpr>(DeclExp)) {
148 // Calls to operators that are members need to be treated like member calls.
150 Ctx.SelfArg = CE->getArg(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>(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>(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>(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>(D)->getFunctionObjectParameterType(),
184 false);
185 else // For most attributes.
186 return translateAttrExpr(AttrExp, &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(cast<const Expr *>(Ctx.SelfArg), nullptr);
195 }
196
197 // For most attributes.
198 return translateAttrExpr(AttrExp, &Ctx);
199}
200
201/// Translate a clang expression in an attribute to a til::SExpr.
202// This assumes a CallingContext has already been created.
204 CallingContext *Ctx) {
205 if (!AttrExp)
206 return CapabilityExpr();
207
208 if (const auto* SLit = dyn_cast<StringLiteral>(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>(AttrExp)) {
221 if (OE->getOperator() == OO_Exclaim) {
222 Neg = true;
223 AttrExp = OE->getArg(0);
224 }
225 }
226 else if (const auto *UO = dyn_cast<UnaryOperator>(AttrExp)) {
227 if (UO->getOpcode() == UO_LNot) {
228 Neg = true;
229 AttrExp = UO->getSubExpr()->IgnoreImplicit();
230 }
231 }
232
233 const til::SExpr *E = translate(AttrExp, Ctx);
234
235 // Trap mutex expressions like nullptr, or 0.
236 // Any literal value is nonsense.
237 if (!E || isa<til::Literal>(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>(E)) {
242 if (CE->castOpcode() == til::CAST_objToPtr)
243 E = CE->expr();
244 }
245 return CapabilityExpr(E, AttrExp->getType(), Neg);
246}
247
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(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(VD->getCanonicalDecl());
263 if (VarsBeingTranslated.empty())
264 LookupLocalVarExpr = RestoreClosure;
265 });
266 VarsBeingTranslated.insert(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(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.
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.
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(cast<DeclRefExpr>(S), Ctx);
304 case Stmt::CXXThisExprClass:
305 return translateCXXThisExpr(cast<CXXThisExpr>(S), Ctx);
306 case Stmt::MemberExprClass:
307 return translateMemberExpr(cast<MemberExpr>(S), Ctx);
308 case Stmt::ObjCIvarRefExprClass:
309 return translateObjCIVarRefExpr(cast<ObjCIvarRefExpr>(S), Ctx);
310 case Stmt::CallExprClass:
311 return translateCallExpr(cast<CallExpr>(S), Ctx);
312 case Stmt::CXXMemberCallExprClass:
313 return translateCXXMemberCallExpr(cast<CXXMemberCallExpr>(S), Ctx);
314 case Stmt::CXXOperatorCallExprClass:
315 return translateCXXOperatorCallExpr(cast<CXXOperatorCallExpr>(S), Ctx);
316 case Stmt::UnaryOperatorClass:
317 return translateUnaryOperator(cast<UnaryOperator>(S), Ctx);
318 case Stmt::BinaryOperatorClass:
319 case Stmt::CompoundAssignOperatorClass:
320 return translateBinaryOperator(cast<BinaryOperator>(S), Ctx);
321
322 case Stmt::ArraySubscriptExprClass:
323 return translateArraySubscriptExpr(cast<ArraySubscriptExpr>(S), Ctx);
324 case Stmt::ConditionalOperatorClass:
325 return translateAbstractConditionalOperator(
327 case Stmt::BinaryConditionalOperatorClass:
328 return translateAbstractConditionalOperator(
330
331 // We treat these as no-ops
332 case Stmt::ConstantExprClass:
333 return translate(cast<ConstantExpr>(S)->getSubExpr(), Ctx);
334 case Stmt::ParenExprClass:
335 return translate(cast<ParenExpr>(S)->getSubExpr(), Ctx);
336 case Stmt::ExprWithCleanupsClass:
337 return translate(cast<ExprWithCleanups>(S)->getSubExpr(), Ctx);
338 case Stmt::CXXBindTemporaryExprClass:
339 return translate(cast<CXXBindTemporaryExpr>(S)->getSubExpr(), Ctx);
340 case Stmt::MaterializeTemporaryExprClass:
341 return translate(cast<MaterializeTemporaryExpr>(S)->getSubExpr(), Ctx);
342
343 // Collect all literals
344 case Stmt::CharacterLiteralClass:
345 return new (Arena)
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>(S)->getValue());
352 case Stmt::IntegerLiteralClass: {
353 const auto *IL = cast<IntegerLiteral>(S);
354 const auto *BT = cast<BuiltinType>(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>(S)->getBytes());
365 case Stmt::ObjCStringLiteralClass:
366 return new (Arena)
367 til::LiteralT(cast<ObjCStringLiteral>(S)->getString()->getBytes());
368
369 case Stmt::DeclStmtClass:
370 return translateDeclStmt(cast<DeclStmt>(S), Ctx);
371 case Stmt::StmtExprClass:
372 return translateStmtExpr(cast<StmtExpr>(S), Ctx);
373 default:
374 break;
375 }
376 if (const auto *CE = dyn_cast<CastExpr>(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>(D))
387 return FD->getCanonicalDecl()->getParamDecl(I);
388 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
389 return MD->getCanonicalDecl()->getParamDecl(I);
390 if (const auto *DD = dyn_cast<DeclaratorDecl>(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);
401 }
402 }
403 return nullptr;
404}
405
407 if (const auto *V = dyn_cast<til::Variable>(E))
408 return V->clangDecl();
409 if (const auto *Ph = dyn_cast<til::Phi>(E))
410 return Ph->clangDecl();
411 if (const auto *P = dyn_cast<til::Project>(E))
412 return P->clangDecl();
413 if (const auto *L = dyn_cast<til::LiteralPtr>(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>(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>(DRE->getDecl()->getCanonicalDecl());
431
432 // Function parameters require substitution and/or renaming.
433 if (const auto *PV = dyn_cast<ParmVarDecl>(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>(D))
440 Match = (FD->getCanonicalDecl() == Canonical);
441 else if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
442 Match = (MD->getCanonicalDecl() == Canonical);
443 else if (getCanonicalParamDecl(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 *>(Ctx->FunArgs)) {
452 assert(I < Ctx->NumArgs);
453 return translate(FunArgs[I], Ctx->Prev);
454 }
455
456 assert(I == 0);
457 return cast<til::SExpr *>(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(cast<Decl>(D), I))
463 VD = PVD;
464 }
465
466 if (const auto *VarD = dyn_cast<VarDecl>(VD))
467 return translateVariable(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>(VD); FD && Ctx && Ctx->SelfArg) {
475 til::SExpr *BE = translateCXXThisExpr(nullptr, Ctx);
476 til::SExpr *E = new (Arena) til::SApply(BE);
477 til::Project *P = new (Arena) til::Project(E, FD);
478 if (hasAnyPointerType(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 *>(Ctx->SelfArg))
492 return translate(SelfArg, Ctx->Prev);
493 else
494 return cast<til::SExpr *>(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
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(ME->getBase(), Ctx);
516 til::SExpr *E = new (Arena) til::SApply(BE);
517
518 const auto *D = cast<ValueDecl>(ME->getMemberDecl()->getCanonicalDecl());
519 if (const auto *VD = dyn_cast<CXXMethodDecl>(D))
520 D = getFirstVirtualDecl(VD);
521
522 til::Project *P = new (Arena) til::Project(E, D);
523 if (hasAnyPointerType(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(IVRE->getBase(), Ctx);
531 til::SExpr *E = new (Arena) til::SApply(BE);
532
533 const auto *D = cast<ObjCIvarDecl>(IVRE->getDecl()->getCanonicalDecl());
534
535 til::Project *P = new (Arena) til::Project(E, D);
536 if (hasAnyPointerType(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(At->getArg(), &LRCallCtx).sexpr());
556 }
557 }
558 }
559
560 til::SExpr *E = translate(CE->getCallee(), Ctx);
561 for (const auto *Arg : CE->arguments()) {
562 til::SExpr *A = translate(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(ME->getImplicitObjectArgument(), Ctx);
575 return new (Arena) til::Cast(til::CAST_objToPtr, E);
576 // return E;
577 }
578 }
579 return translateCallExpr(cast<CallExpr>(ME), Ctx,
581}
582
583til::SExpr *SExprBuilder::translateCXXOperatorCallExpr(
584 const CXXOperatorCallExpr *OCE, CallingContext *Ctx) {
585 if (CapabilityExprMode) {
586 // Ignore operator * and operator -> on smart pointers.
588 if (k == OO_Star || k == OO_Arrow) {
589 auto *E = translate(OCE->getArg(0), Ctx);
590 return new (Arena) til::Cast(til::CAST_objToPtr, E);
591 // return E;
592 }
593 }
594 return translateCallExpr(cast<CallExpr>(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>(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(UO->getSubExpr(), Ctx);
620
621 // We treat these as no-ops
622 case UO_Deref:
623 case UO_Plus:
624 return translate(UO->getSubExpr(), Ctx);
625
626 case UO_Minus:
627 return new (Arena)
628 til::UnaryOp(til::UOP_Minus, translate(UO->getSubExpr(), Ctx));
629 case UO_Not:
630 return new (Arena)
631 til::UnaryOp(til::UOP_BitNot, translate(UO->getSubExpr(), Ctx));
632 case UO_LNot:
633 return new (Arena)
634 til::UnaryOp(til::UOP_LogicNot, translate(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(BO->getLHS(), Ctx);
650 til::SExpr *E1 = translate(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(LHS, Ctx);
664 til::SExpr *E1 = translate(RHS, Ctx);
665
666 const ValueDecl *VD = nullptr;
667 til::SExpr *CV = nullptr;
668 if (const auto *DRE = dyn_cast<DeclRefExpr>(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(E1, nullptr, VD);
677 }
678 if (VD && CV)
679 return updateVarDecl(VD, 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(til::BOP_Mul, BO, Ctx);
691 case BO_Div: return translateBinOp(til::BOP_Div, BO, Ctx);
692 case BO_Rem: return translateBinOp(til::BOP_Rem, BO, Ctx);
693 case BO_Add: return translateBinOp(til::BOP_Add, BO, Ctx);
694 case BO_Sub: return translateBinOp(til::BOP_Sub, BO, Ctx);
695 case BO_Shl: return translateBinOp(til::BOP_Shl, BO, Ctx);
696 case BO_Shr: return translateBinOp(til::BOP_Shr, BO, Ctx);
697 case BO_LT: return translateBinOp(til::BOP_Lt, BO, Ctx);
698 case BO_GT: return translateBinOp(til::BOP_Lt, BO, Ctx, true);
699 case BO_LE: return translateBinOp(til::BOP_Leq, BO, Ctx);
700 case BO_GE: return translateBinOp(til::BOP_Leq, BO, Ctx, true);
701 case BO_EQ: return translateBinOp(til::BOP_Eq, BO, Ctx);
702 case BO_NE: return translateBinOp(til::BOP_Neq, BO, Ctx);
703 case BO_Cmp: return translateBinOp(til::BOP_Cmp, BO, Ctx);
704 case BO_And: return translateBinOp(til::BOP_BitAnd, BO, Ctx);
705 case BO_Xor: return translateBinOp(til::BOP_BitXor, BO, Ctx);
706 case BO_Or: return translateBinOp(til::BOP_BitOr, BO, Ctx);
707 case BO_LAnd: return translateBinOp(til::BOP_LogicAnd, BO, Ctx);
708 case BO_LOr: return translateBinOp(til::BOP_LogicOr, BO, Ctx);
709
710 case BO_Assign: return translateBinAssign(til::BOP_Eq, BO, Ctx, true);
711 case BO_MulAssign: return translateBinAssign(til::BOP_Mul, BO, Ctx);
712 case BO_DivAssign: return translateBinAssign(til::BOP_Div, BO, Ctx);
713 case BO_RemAssign: return translateBinAssign(til::BOP_Rem, BO, Ctx);
714 case BO_AddAssign: return translateBinAssign(til::BOP_Add, BO, Ctx);
715 case BO_SubAssign: return translateBinAssign(til::BOP_Sub, BO, Ctx);
716 case BO_ShlAssign: return translateBinAssign(til::BOP_Shl, BO, Ctx);
717 case BO_ShrAssign: return translateBinAssign(til::BOP_Shr, BO, Ctx);
718 case BO_AndAssign: return translateBinAssign(til::BOP_BitAnd, BO, Ctx);
719 case BO_XorAssign: return translateBinAssign(til::BOP_BitXor, BO, Ctx);
720 case BO_OrAssign: return translateBinAssign(til::BOP_BitOr, BO, Ctx);
721
722 case BO_Comma:
723 // The clang CFG should have already processed both sides.
724 return translate(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>(CE->getSubExpr())) {
735 til::SExpr *E0 = lookupVarDecl(DRE->getDecl());
736 if (E0)
737 return E0;
738 }
739 til::SExpr *E0 = translate(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(CE->getSubExpr(), Ctx);
750 return E0;
751 }
752 default: {
753 // FIXME: handle different kinds of casts.
754 til::SExpr *E0 = translate(CE->getSubExpr(), Ctx);
755 if (CapabilityExprMode)
756 return E0;
757 return new (Arena) til::Cast(til::CAST_none, E0);
758 }
759 }
760}
761
763SExprBuilder::translateArraySubscriptExpr(const ArraySubscriptExpr *E,
764 CallingContext *Ctx) {
765 til::SExpr *E0 = translate(E->getBase(), Ctx);
766 til::SExpr *E1 = translate(E->getIdx(), Ctx);
767 return new (Arena) til::ArrayIndex(E0, E1);
768}
769
771SExprBuilder::translateAbstractConditionalOperator(
772 const AbstractConditionalOperator *CO, CallingContext *Ctx) {
773 auto *C = translate(CO->getCond(), Ctx);
774 auto *T = translate(CO->getTrueExpr(), Ctx);
775 auto *E = translate(CO->getFalseExpr(), Ctx);
776 return new (Arena) til::IfThenElse(C, T, E);
777}
778
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>(I)) {
784 Expr *E = VD->getInit();
785 til::SExpr* SE = translate(E, Ctx);
786
787 // Add local variables with trivial type to the variable map
788 QualType T = VD->getType();
789 if (T.isTrivialType(VD->getASTContext()))
790 return addVarDecl(VD, 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(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(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(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>(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(std::make_pair(VD, CurrentLVarMap.size()));
848 CurrentLVarMap.makeWritable();
849 CurrentLVarMap.push_back(std::make_pair(VD, 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(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(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>(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(NPreds, 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(CurrE))
898
899 // Add Phi node to current block, and update CurrentLVarMap[i]
900 CurrentArguments.push_back(Ph);
901 if (Ph->status() == til::Phi::PH_Incomplete)
902 IncompleteArgs.push_back(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(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(ESz, 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, Map[i].second);
935 }
936 if (ESz > MSz) {
937 CurrentLVarMap.makeWritable();
938 CurrentLVarMap.downsize(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, 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(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>(PE);
977 assert(Ph && "Expecting Phi Node.");
978 assert(Ph->values()[ArgIndex] == nullptr && "Wrong index for back edge.");
979
980 til::SExpr *E = lookupVarDecl(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(NBlocks);
994 BlockMap.resize(NBlocks, 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(B->size());
999 BlockMap[B->getBlockID()] = BB;
1000 }
1001
1002 CurrentBB = lookupBlock(&Cfg->getEntry());
1003 auto Parms = isa<ObjCMethodDecl>(D) ? cast<ObjCMethodDecl>(D)->parameters()
1004 : cast<FunctionDecl>(D)->parameters();
1005 for (auto *Pm : Parms) {
1006 QualType T = Pm->getType();
1007 if (!T.isTrivialType(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(Ld, nullptr, Pm);
1015 addVarDecl(Pm, 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(B->pred_size());
1023 Scfg->add(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(BlockMap[Pred->getBlockID()]);
1036 BlockInfo *PredInfo = &BBInfo[Pred->getBlockID()];
1037 assert(PredInfo->UnprocessedSuccessors > 0);
1038
1039 if (--PredInfo->UnprocessedSuccessors == 0)
1040 mergeEntryMap(std::move(PredInfo->ExitMap));
1041 else
1042 mergeEntryMap(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 static_cast<unsigned>(CurrentArguments.size()), Arena);
1056 for (auto *A : CurrentArguments)
1057 CurrentBB->addArgument(A);
1058}
1059
1060void SExprBuilder::handleStatement(const Stmt *S) {
1061 til::SExpr *E = translate(S, 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, nullptr);
1072}
1073
1074void SExprBuilder::exitCFGBlockBody(const CFGBlock *B) {
1075 CurrentBB->instructions().reserve(
1076 static_cast<unsigned>(CurrentInstructions.size()), 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(*It) : nullptr;
1085 // TODO: set index
1086 unsigned Idx = BB ? BB->findPredecessorIndex(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(B->getTerminatorCondition(true), nullptr);
1092 til::BasicBlock *BB1 = *It ? lookupBlock(*It) : nullptr;
1093 ++It;
1094 til::BasicBlock *BB2 = *It ? lookupBlock(*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(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)
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
#define V(N, I)
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
Defines the clang::Expr interface and subclasses for C++ expressions.
Forward-declares and imports various common LLVM datatypes that clang wants to use unqualified.
Defines an enumeration for C++ overloaded operators.
static std::string toString(const clang::SanitizerSet &Sanitizers)
Produce a string containing comma-separated names of sanitizers in Sanitizers set.
Defines various enumerations that describe declaration and type specifiers.
static bool isIncompletePhi(const til::SExpr *E)
SExprBuilder::CallingContext CallingContext
static const ParmVarDecl * getCanonicalParamDecl(const Decl *D, unsigned I)
Helper to extract the canonical parameter declaration from a function or function pointer.
static const ValueDecl * getValueDeclFromSExpr(const til::SExpr *E)
static void maybeUpdateVD(til::SExpr *E, const ValueDecl *VD)
static bool hasAnyPointerType(const til::SExpr *E)
static const CXXMethodDecl * getFirstVirtualDecl(const CXXMethodDecl *D)
static std::pair< StringRef, bool > classifyCapability(const TypeDecl &TD)
static bool isCalleeArrow(const Expr *E)
static constexpr std::pair< StringRef, bool > ClassifyCapabilityFallback
C Language Family Type Representation.
Expr * getCond() const
getCond - Return the expression representing the condition for the ?
Definition Expr.h:4534
Expr * getTrueExpr() const
getTrueExpr - Return the subexpression representing the value of the expression if the condition eval...
Definition Expr.h:4540
Expr * getFalseExpr() const
getFalseExpr - Return the subexpression representing the value of the expression if the condition eva...
Definition Expr.h:4546
Expr * getLHS() const
Definition Expr.h:4091
Expr * getRHS() const
Definition Expr.h:4093
Opcode getOpcode() const
Definition Expr.h:4086
succ_iterator succ_begin()
Definition CFG.h:1017
unsigned pred_size() const
Definition CFG.h:1038
const Stmt * getTerminatorCondition(bool StripParens=true) const
Definition CFG.cpp:6515
unsigned getBlockID() const
Definition CFG.h:1134
unsigned succ_size() const
Definition CFG.h:1035
unsigned getNumBlockIDs() const
Returns the total number of BlockIDs allocated (which start at 0).
Definition CFG.h:1443
CXXMethodDecl * getMethodDecl() const
Retrieve the declaration of the called method.
Definition ExprCXX.cpp:748
Expr * getImplicitObjectArgument() const
Retrieve the implicit object argument for the member call.
Definition ExprCXX.cpp:729
Represents a static or instance method of a struct/union/class.
Definition DeclCXX.h:2132
overridden_method_range overridden_methods() const
Definition DeclCXX.cpp:2830
CXXMethodDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition DeclCXX.h:2241
OverloadedOperatorKind getOperator() const
Returns the kind of overloaded operator that this expression refers to.
Definition ExprCXX.h:115
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition Expr.h:3150
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return null.
Definition Expr.h:3129
Expr * getCallee()
Definition Expr.h:3093
unsigned getNumArgs() const
getNumArgs - Return the number of actual arguments to this call.
Definition Expr.h:3137
Expr ** getArgs()
Retrieve the call arguments.
Definition Expr.h:3140
arg_range arguments()
Definition Expr.h:3198
CastKind getCastKind() const
Definition Expr.h:3723
Expr * getSubExpr()
Definition Expr.h:3729
bool body_empty() const
Definition Stmt.h:1794
Stmt * body_back()
Definition Stmt.h:1818
ValueDecl * getDecl()
Definition Expr.h:1341
const DeclGroupRef getDeclGroup() const
Definition Stmt.h:1659
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
T * getAttr() const
Definition DeclBase.h:581
ASTContext & getASTContext() const LLVM_READONLY
Definition DeclBase.cpp:547
bool hasAttr() const
Definition DeclBase.h:585
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition DeclBase.h:991
This represents one expression.
Definition Expr.h:112
Expr * IgnoreParenCasts() LLVM_READONLY
Skip past any parentheses and casts which might surround this expression until reaching a fixed point...
Definition Expr.cpp:3102
Expr * IgnoreImplicit() LLVM_READONLY
Skip past any implicit AST nodes which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3085
QualType getType() const
Definition Expr.h:144
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
Definition Expr.h:3450
Expr * getBase() const
Definition Expr.h:3444
This represents a decl that may have a name.
Definition Decl.h:274
std::string getNameAsString() const
Get a human-readable name for the declaration, even if it is one of the special kinds of names (C++ c...
Definition Decl.h:317
bool isCXXInstanceMember() const
Determine whether the given declaration is an instance member of a C++ class.
Definition Decl.cpp:1980
ObjCIvarDecl * getCanonicalDecl() override
Retrieves the canonical declaration of this field.
Definition DeclObjC.h:1991
ObjCIvarDecl * getDecl()
Definition ExprObjC.h:610
const Expr * getBase() const
Definition ExprObjC.h:614
Represents a parameter to a function.
Definition Decl.h:1808
Wrapper for source info for pointers.
Definition TypeLoc.h:1513
A (possibly-)qualified type.
Definition TypeBase.h:937
bool isTrivialType(const ASTContext &Context) const
Return true if this is a trivial type per (C++0x [basic.types]p9)
Definition Type.cpp:2852
CompoundStmt * getSubStmt()
Definition Expr.h:4615
Stmt - This represents one statement.
Definition Stmt.h:86
StmtClass getStmtClass() const
Definition Stmt.h:1503
Represents a declaration of a type.
Definition Decl.h:3531
Base wrapper for a particular "section" of type source info.
Definition TypeLoc.h:59
T getAsAdjusted() const
Convert to the specified TypeLoc type, returning a null TypeLoc if this TypeLoc is not of the desired...
Definition TypeLoc.h:2735
RecordDecl * getAsRecordDecl() const
Retrieves the RecordDecl this type refers to.
Definition Type.h:41
bool isPointerType() const
Definition TypeBase.h:8682
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:789
bool isPointerOrReferenceType() const
Definition TypeBase.h:8686
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9275
Expr * getSubExpr() const
Definition Expr.h:2288
Opcode getOpcode() const
Definition Expr.h:2283
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition Decl.h:712
QualType getType() const
Definition Decl.h:723
Represents a variable declaration or definition.
Definition Decl.h:924
VarDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition Decl.cpp:2241
bool isStaticLocal() const
Returns true if a variable with function scope is a static local variable.
Definition Decl.h:1206
CapabilityExpr translateAttrExpr(const Expr *AttrExp, const NamedDecl *D, const Expr *DeclExp, til::SExpr *Self=nullptr)
Translate a clang expression in an attribute to a til::SExpr.
til::SExpr * translate(const Stmt *S, CallingContext *Ctx)
til::SExpr * lookupStmt(const Stmt *S)
til::SCFG * buildCFG(CFGWalker &Walker)
til::SExpr * translateVariable(const VarDecl *VD, CallingContext *Ctx)
til::BasicBlock * lookupBlock(const CFGBlock *B)
const InstrArray & arguments() const
unsigned findPredecessorIndex(const BasicBlock *BB) const
Return the index of BB, or Predecessors.size if BB is not a predecessor.
A Literal pointer to an object allocated in memory.
const ValueDecl * clangDecl() const
Return the clang declaration of the variable for this Phi node, if any.
void setClangDecl(const ValueDecl *Cvd)
Set the clang variable associated with this Phi node.
const ValArray & values() const
An SCFG is a control-flow graph.
Base class for AST nodes in the typed intermediate language.
BasicBlock * block() const
Returns the block, if this is an instruction in a basic block, otherwise returns null.
void setValues(unsigned Sz, const T &C)
Placeholder for expressions that cannot be represented in the TIL.
Placeholder for a wildcard that matches any other expression.
std::variant< struct RequiresDecl, struct HeaderDecl, struct UmbrellaDirDecl, struct ModuleDecl, struct ExcludeDecl, struct ExportDecl, struct ExportAsDecl, struct ExternModuleDecl, struct UseDecl, struct LinkDecl, struct ConfigMacrosDecl, struct ConflictDecl > Decl
All declarations that can appear in a module declaration.
void simplifyIncompleteArg(til::Phi *Ph)
TIL_BinaryOpcode
Opcode for binary arithmetic operations.
void printSCFG(CFGWalker &Walker)
std::string getSourceLiteralString(const Expr *CE)
The JSON file list parser is used to communicate input to InstallAPI.
OverloadedOperatorKind
Enumeration specifying the different kinds of C++ overloaded operators.
@ Match
This is not an overload because the signature exactly matches an existing declaration.
Definition Sema.h:830
bool isa(CodeGen::Address addr)
Definition Address.h:330
@ Self
'self' clause, allowed on Compute and Combined Constructs, plus 'update'.
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
@ Result
The result type of a method or function.
Definition TypeBase.h:905
CastKind
CastKind - The kind of operation required for a conversion.
U cast(CodeGen::Address addr)
Definition Address.h:327
Encapsulates the lexical context of a function call.
llvm::PointerUnion< const Expr *const *, til::SExpr * > FunArgs
llvm::PointerUnion< const Expr *, til::SExpr * > SelfArg