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