1 //===- ThreadSafetyCommon.cpp -----------------------------------*- C++ -*-===//
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/DeclCXX.h"
17 #include "clang/AST/DeclObjC.h"
18 #include "clang/AST/ExprCXX.h"
19 #include "clang/AST/StmtCXX.h"
20 #include "clang/Analysis/Analyses/PostOrderCFGView.h"
21 #include "clang/Analysis/Analyses/ThreadSafetyTIL.h"
22 #include "clang/Analysis/Analyses/ThreadSafetyTraverse.h"
23 #include "clang/Analysis/AnalysisContext.h"
24 #include "clang/Analysis/CFG.h"
25 #include "clang/Basic/OperatorKinds.h"
26 #include "clang/Basic/SourceLocation.h"
27 #include "clang/Basic/SourceManager.h"
28 #include "llvm/ADT/DenseMap.h"
29 #include "llvm/ADT/SmallVector.h"
30 #include "llvm/ADT/StringRef.h"
31 #include <algorithm>
32 #include <climits>
33 #include <vector>
34 
35 using namespace clang;
36 using namespace threadSafety;
37 
38 // From ThreadSafetyUtil.h
39 std::string threadSafety::getSourceLiteralString(const clang::Expr *CE) {
40   switch (CE->getStmtClass()) {
41     case Stmt::IntegerLiteralClass:
42       return cast<IntegerLiteral>(CE)->getValue().toString(10, true);
43     case Stmt::StringLiteralClass: {
44       std::string ret("\"");
45       ret += cast<StringLiteral>(CE)->getString();
46       ret += "\"";
47       return ret;
48     }
49     case Stmt::CharacterLiteralClass:
50     case Stmt::CXXNullPtrLiteralExprClass:
51     case Stmt::GNUNullExprClass:
52     case Stmt::CXXBoolLiteralExprClass:
53     case Stmt::FloatingLiteralClass:
54     case Stmt::ImaginaryLiteralClass:
55     case Stmt::ObjCStringLiteralClass:
56     default:
57       return "#lit";
58   }
59 }
60 
61 // Return true if E is a variable that points to an incomplete Phi node.
62 static bool isIncompletePhi(const til::SExpr *E) {
63   if (const auto *Ph = dyn_cast<til::Phi>(E))
64     return Ph->status() == til::Phi::PH_Incomplete;
65   return false;
66 }
67 
68 typedef SExprBuilder::CallingContext CallingContext;
69 
70 til::SExpr *SExprBuilder::lookupStmt(const Stmt *S) {
71   auto It = SMap.find(S);
72   if (It != SMap.end())
73     return It->second;
74   return nullptr;
75 }
76 
77 til::SCFG *SExprBuilder::buildCFG(CFGWalker &Walker) {
78   Walker.walk(*this);
79   return Scfg;
80 }
81 
82 static bool isCalleeArrow(const Expr *E) {
83   const MemberExpr *ME = dyn_cast<MemberExpr>(E->IgnoreParenCasts());
84   return ME ? ME->isArrow() : false;
85 }
86 
87 /// \brief Translate a clang expression in an attribute to a til::SExpr.
88 /// Constructs the context from D, DeclExp, and SelfDecl.
89 ///
90 /// \param AttrExp The expression to translate.
91 /// \param D       The declaration to which the attribute is attached.
92 /// \param DeclExp An expression involving the Decl to which the attribute
93 ///                is attached.  E.g. the call to a function.
94 CapabilityExpr SExprBuilder::translateAttrExpr(const Expr *AttrExp,
95                                                const NamedDecl *D,
96                                                const Expr *DeclExp,
97                                                VarDecl *SelfDecl) {
98   // If we are processing a raw attribute expression, with no substitutions.
99   if (!DeclExp)
100     return translateAttrExpr(AttrExp, nullptr);
101 
102   CallingContext Ctx(nullptr, D);
103 
104   // Examine DeclExp to find SelfArg and FunArgs, which are used to substitute
105   // for formal parameters when we call buildMutexID later.
106   if (const MemberExpr *ME = dyn_cast<MemberExpr>(DeclExp)) {
107     Ctx.SelfArg   = ME->getBase();
108     Ctx.SelfArrow = ME->isArrow();
109   } else if (const CXXMemberCallExpr *CE =
110              dyn_cast<CXXMemberCallExpr>(DeclExp)) {
111     Ctx.SelfArg   = CE->getImplicitObjectArgument();
112     Ctx.SelfArrow = isCalleeArrow(CE->getCallee());
113     Ctx.NumArgs   = CE->getNumArgs();
114     Ctx.FunArgs   = CE->getArgs();
115   } else if (const CallExpr *CE = dyn_cast<CallExpr>(DeclExp)) {
116     Ctx.NumArgs = CE->getNumArgs();
117     Ctx.FunArgs = CE->getArgs();
118   } else if (const CXXConstructExpr *CE =
119              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 /// \brief Translate a clang expression in an attribute to a til::SExpr.
150 // This assumes a CallingContext has already been created.
151 CapabilityExpr SExprBuilder::translateAttrExpr(const Expr *AttrExp,
152                                                CallingContext *Ctx) {
153   if (!AttrExp)
154     return CapabilityExpr(nullptr, false);
155 
156   if (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 (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 (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 (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.
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 
243   // Collect all literals
244   case Stmt::CharacterLiteralClass:
245   case Stmt::CXXNullPtrLiteralExprClass:
246   case Stmt::GNUNullExprClass:
247   case Stmt::CXXBoolLiteralExprClass:
248   case Stmt::FloatingLiteralClass:
249   case Stmt::ImaginaryLiteralClass:
250   case Stmt::IntegerLiteralClass:
251   case Stmt::StringLiteralClass:
252   case Stmt::ObjCStringLiteralClass:
253     return new (Arena) til::Literal(cast<Expr>(S));
254 
255   case Stmt::DeclStmtClass:
256     return translateDeclStmt(cast<DeclStmt>(S), Ctx);
257   default:
258     break;
259   }
260   if (const CastExpr *CE = dyn_cast<CastExpr>(S))
261     return translateCastExpr(CE, Ctx);
262 
263   return new (Arena) til::Undefined(S);
264 }
265 
266 til::SExpr *SExprBuilder::translateDeclRefExpr(const DeclRefExpr *DRE,
267                                                CallingContext *Ctx) {
268   const ValueDecl *VD = cast<ValueDecl>(DRE->getDecl()->getCanonicalDecl());
269 
270   // Function parameters require substitution and/or renaming.
271   if (const ParmVarDecl *PV = dyn_cast_or_null<ParmVarDecl>(VD)) {
272     const FunctionDecl *FD =
273         cast<FunctionDecl>(PV->getDeclContext())->getCanonicalDecl();
274     unsigned I = PV->getFunctionScopeIndex();
275 
276     if (Ctx && Ctx->FunArgs && FD == Ctx->AttrDecl->getCanonicalDecl()) {
277       // Substitute call arguments for references to function parameters
278       assert(I < Ctx->NumArgs);
279       return translate(Ctx->FunArgs[I], Ctx->Prev);
280     }
281     // Map the param back to the param of the original function declaration
282     // for consistent comparisons.
283     VD = FD->getParamDecl(I);
284   }
285 
286   // For non-local variables, treat it as a reference to a named object.
287   return new (Arena) til::LiteralPtr(VD);
288 }
289 
290 til::SExpr *SExprBuilder::translateCXXThisExpr(const CXXThisExpr *TE,
291                                                CallingContext *Ctx) {
292   // Substitute for 'this'
293   if (Ctx && Ctx->SelfArg)
294     return translate(Ctx->SelfArg, Ctx->Prev);
295   assert(SelfVar && "We have no variable for 'this'!");
296   return SelfVar;
297 }
298 
299 static const ValueDecl *getValueDeclFromSExpr(const til::SExpr *E) {
300   if (auto *V = dyn_cast<til::Variable>(E))
301     return V->clangDecl();
302   if (auto *Ph = dyn_cast<til::Phi>(E))
303     return Ph->clangDecl();
304   if (auto *P = dyn_cast<til::Project>(E))
305     return P->clangDecl();
306   if (auto *L = dyn_cast<til::LiteralPtr>(E))
307     return L->clangDecl();
308   return nullptr;
309 }
310 
311 static bool hasCppPointerType(const til::SExpr *E) {
312   auto *VD = getValueDeclFromSExpr(E);
313   if (VD && VD->getType()->isPointerType())
314     return true;
315   if (auto *C = dyn_cast<til::Cast>(E))
316     return C->castOpcode() == til::CAST_objToPtr;
317 
318   return false;
319 }
320 
321 // Grab the very first declaration of virtual method D
322 static const CXXMethodDecl *getFirstVirtualDecl(const CXXMethodDecl *D) {
323   while (true) {
324     D = D->getCanonicalDecl();
325     CXXMethodDecl::method_iterator I = D->begin_overridden_methods(),
326                                    E = D->end_overridden_methods();
327     if (I == E)
328       return D;  // Method does not override anything
329     D = *I;      // FIXME: this does not work with multiple inheritance.
330   }
331   return nullptr;
332 }
333 
334 til::SExpr *SExprBuilder::translateMemberExpr(const MemberExpr *ME,
335                                               CallingContext *Ctx) {
336   til::SExpr *BE = translate(ME->getBase(), Ctx);
337   til::SExpr *E  = new (Arena) til::SApply(BE);
338 
339   const ValueDecl *D =
340       cast<ValueDecl>(ME->getMemberDecl()->getCanonicalDecl());
341   if (auto *VD = dyn_cast<CXXMethodDecl>(D))
342     D = getFirstVirtualDecl(VD);
343 
344   til::Project *P = new (Arena) til::Project(E, D);
345   if (hasCppPointerType(BE))
346     P->setArrow(true);
347   return P;
348 }
349 
350 til::SExpr *SExprBuilder::translateCallExpr(const CallExpr *CE,
351                                             CallingContext *Ctx,
352                                             const Expr *SelfE) {
353   if (CapabilityExprMode) {
354     // Handle LOCK_RETURNED
355     const FunctionDecl *FD = CE->getDirectCallee()->getMostRecentDecl();
356     if (LockReturnedAttr* At = FD->getAttr<LockReturnedAttr>()) {
357       CallingContext LRCallCtx(Ctx);
358       LRCallCtx.AttrDecl = CE->getDirectCallee();
359       LRCallCtx.SelfArg  = SelfE;
360       LRCallCtx.NumArgs  = CE->getNumArgs();
361       LRCallCtx.FunArgs  = CE->getArgs();
362       return const_cast<til::SExpr*>(
363           translateAttrExpr(At->getArg(), &LRCallCtx).sexpr());
364     }
365   }
366 
367   til::SExpr *E = translate(CE->getCallee(), Ctx);
368   for (const auto *Arg : CE->arguments()) {
369     til::SExpr *A = translate(Arg, Ctx);
370     E = new (Arena) til::Apply(E, A);
371   }
372   return new (Arena) til::Call(E, CE);
373 }
374 
375 til::SExpr *SExprBuilder::translateCXXMemberCallExpr(
376     const CXXMemberCallExpr *ME, CallingContext *Ctx) {
377   if (CapabilityExprMode) {
378     // Ignore calls to get() on smart pointers.
379     if (ME->getMethodDecl()->getNameAsString() == "get" &&
380         ME->getNumArgs() == 0) {
381       auto *E = translate(ME->getImplicitObjectArgument(), Ctx);
382       return new (Arena) til::Cast(til::CAST_objToPtr, E);
383       // return E;
384     }
385   }
386   return translateCallExpr(cast<CallExpr>(ME), Ctx,
387                            ME->getImplicitObjectArgument());
388 }
389 
390 til::SExpr *SExprBuilder::translateCXXOperatorCallExpr(
391     const CXXOperatorCallExpr *OCE, CallingContext *Ctx) {
392   if (CapabilityExprMode) {
393     // Ignore operator * and operator -> on smart pointers.
394     OverloadedOperatorKind k = OCE->getOperator();
395     if (k == OO_Star || k == OO_Arrow) {
396       auto *E = translate(OCE->getArg(0), Ctx);
397       return new (Arena) til::Cast(til::CAST_objToPtr, E);
398       // return E;
399     }
400   }
401   return translateCallExpr(cast<CallExpr>(OCE), Ctx);
402 }
403 
404 til::SExpr *SExprBuilder::translateUnaryOperator(const UnaryOperator *UO,
405                                                  CallingContext *Ctx) {
406   switch (UO->getOpcode()) {
407   case UO_PostInc:
408   case UO_PostDec:
409   case UO_PreInc:
410   case UO_PreDec:
411     return new (Arena) til::Undefined(UO);
412 
413   case UO_AddrOf: {
414     if (CapabilityExprMode) {
415       // interpret &Graph::mu_ as an existential.
416       if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(UO->getSubExpr())) {
417         if (DRE->getDecl()->isCXXInstanceMember()) {
418           // This is a pointer-to-member expression, e.g. &MyClass::mu_.
419           // We interpret this syntax specially, as a wildcard.
420           auto *W = new (Arena) til::Wildcard();
421           return new (Arena) til::Project(W, DRE->getDecl());
422         }
423       }
424     }
425     // otherwise, & is a no-op
426     return translate(UO->getSubExpr(), Ctx);
427   }
428 
429   // We treat these as no-ops
430   case UO_Deref:
431   case UO_Plus:
432     return translate(UO->getSubExpr(), Ctx);
433 
434   case UO_Minus:
435     return new (Arena)
436       til::UnaryOp(til::UOP_Minus, translate(UO->getSubExpr(), Ctx));
437   case UO_Not:
438     return new (Arena)
439       til::UnaryOp(til::UOP_BitNot, translate(UO->getSubExpr(), Ctx));
440   case UO_LNot:
441     return new (Arena)
442       til::UnaryOp(til::UOP_LogicNot, translate(UO->getSubExpr(), Ctx));
443 
444   // Currently unsupported
445   case UO_Real:
446   case UO_Imag:
447   case UO_Extension:
448     return new (Arena) til::Undefined(UO);
449   }
450   return new (Arena) til::Undefined(UO);
451 }
452 
453 til::SExpr *SExprBuilder::translateBinOp(til::TIL_BinaryOpcode Op,
454                                          const BinaryOperator *BO,
455                                          CallingContext *Ctx, bool Reverse) {
456    til::SExpr *E0 = translate(BO->getLHS(), Ctx);
457    til::SExpr *E1 = translate(BO->getRHS(), Ctx);
458    if (Reverse)
459      return new (Arena) til::BinaryOp(Op, E1, E0);
460    else
461      return new (Arena) til::BinaryOp(Op, E0, E1);
462 }
463 
464 til::SExpr *SExprBuilder::translateBinAssign(til::TIL_BinaryOpcode Op,
465                                              const BinaryOperator *BO,
466                                              CallingContext *Ctx,
467                                              bool Assign) {
468   const Expr *LHS = BO->getLHS();
469   const Expr *RHS = BO->getRHS();
470   til::SExpr *E0 = translate(LHS, Ctx);
471   til::SExpr *E1 = translate(RHS, Ctx);
472 
473   const ValueDecl *VD = nullptr;
474   til::SExpr *CV = nullptr;
475   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(LHS)) {
476     VD = DRE->getDecl();
477     CV = lookupVarDecl(VD);
478   }
479 
480   if (!Assign) {
481     til::SExpr *Arg = CV ? CV : new (Arena) til::Load(E0);
482     E1 = new (Arena) til::BinaryOp(Op, Arg, E1);
483     E1 = addStatement(E1, nullptr, VD);
484   }
485   if (VD && CV)
486     return updateVarDecl(VD, E1);
487   return new (Arena) til::Store(E0, E1);
488 }
489 
490 til::SExpr *SExprBuilder::translateBinaryOperator(const BinaryOperator *BO,
491                                                   CallingContext *Ctx) {
492   switch (BO->getOpcode()) {
493   case BO_PtrMemD:
494   case BO_PtrMemI:
495     return new (Arena) til::Undefined(BO);
496 
497   case BO_Mul:  return translateBinOp(til::BOP_Mul, BO, Ctx);
498   case BO_Div:  return translateBinOp(til::BOP_Div, BO, Ctx);
499   case BO_Rem:  return translateBinOp(til::BOP_Rem, BO, Ctx);
500   case BO_Add:  return translateBinOp(til::BOP_Add, BO, Ctx);
501   case BO_Sub:  return translateBinOp(til::BOP_Sub, BO, Ctx);
502   case BO_Shl:  return translateBinOp(til::BOP_Shl, BO, Ctx);
503   case BO_Shr:  return translateBinOp(til::BOP_Shr, BO, Ctx);
504   case BO_LT:   return translateBinOp(til::BOP_Lt,  BO, Ctx);
505   case BO_GT:   return translateBinOp(til::BOP_Lt,  BO, Ctx, true);
506   case BO_LE:   return translateBinOp(til::BOP_Leq, BO, Ctx);
507   case BO_GE:   return translateBinOp(til::BOP_Leq, BO, Ctx, true);
508   case BO_EQ:   return translateBinOp(til::BOP_Eq,  BO, Ctx);
509   case BO_NE:   return translateBinOp(til::BOP_Neq, BO, Ctx);
510   case BO_And:  return translateBinOp(til::BOP_BitAnd,   BO, Ctx);
511   case BO_Xor:  return translateBinOp(til::BOP_BitXor,   BO, Ctx);
512   case BO_Or:   return translateBinOp(til::BOP_BitOr,    BO, Ctx);
513   case BO_LAnd: return translateBinOp(til::BOP_LogicAnd, BO, Ctx);
514   case BO_LOr:  return translateBinOp(til::BOP_LogicOr,  BO, Ctx);
515 
516   case BO_Assign:    return translateBinAssign(til::BOP_Eq,  BO, Ctx, true);
517   case BO_MulAssign: return translateBinAssign(til::BOP_Mul, BO, Ctx);
518   case BO_DivAssign: return translateBinAssign(til::BOP_Div, BO, Ctx);
519   case BO_RemAssign: return translateBinAssign(til::BOP_Rem, BO, Ctx);
520   case BO_AddAssign: return translateBinAssign(til::BOP_Add, BO, Ctx);
521   case BO_SubAssign: return translateBinAssign(til::BOP_Sub, BO, Ctx);
522   case BO_ShlAssign: return translateBinAssign(til::BOP_Shl, BO, Ctx);
523   case BO_ShrAssign: return translateBinAssign(til::BOP_Shr, BO, Ctx);
524   case BO_AndAssign: return translateBinAssign(til::BOP_BitAnd, BO, Ctx);
525   case BO_XorAssign: return translateBinAssign(til::BOP_BitXor, BO, Ctx);
526   case BO_OrAssign:  return translateBinAssign(til::BOP_BitOr,  BO, Ctx);
527 
528   case BO_Comma:
529     // The clang CFG should have already processed both sides.
530     return translate(BO->getRHS(), Ctx);
531   }
532   return new (Arena) til::Undefined(BO);
533 }
534 
535 til::SExpr *SExprBuilder::translateCastExpr(const CastExpr *CE,
536                                             CallingContext *Ctx) {
537   clang::CastKind K = CE->getCastKind();
538   switch (K) {
539   case CK_LValueToRValue: {
540     if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CE->getSubExpr())) {
541       til::SExpr *E0 = lookupVarDecl(DRE->getDecl());
542       if (E0)
543         return E0;
544     }
545     til::SExpr *E0 = translate(CE->getSubExpr(), Ctx);
546     return E0;
547     // FIXME!! -- get Load working properly
548     // return new (Arena) til::Load(E0);
549   }
550   case CK_NoOp:
551   case CK_DerivedToBase:
552   case CK_UncheckedDerivedToBase:
553   case CK_ArrayToPointerDecay:
554   case CK_FunctionToPointerDecay: {
555     til::SExpr *E0 = translate(CE->getSubExpr(), Ctx);
556     return E0;
557   }
558   default: {
559     // FIXME: handle different kinds of casts.
560     til::SExpr *E0 = translate(CE->getSubExpr(), Ctx);
561     if (CapabilityExprMode)
562       return E0;
563     return new (Arena) til::Cast(til::CAST_none, E0);
564   }
565   }
566 }
567 
568 til::SExpr *
569 SExprBuilder::translateArraySubscriptExpr(const ArraySubscriptExpr *E,
570                                           CallingContext *Ctx) {
571   til::SExpr *E0 = translate(E->getBase(), Ctx);
572   til::SExpr *E1 = translate(E->getIdx(), Ctx);
573   return new (Arena) til::ArrayIndex(E0, E1);
574 }
575 
576 til::SExpr *
577 SExprBuilder::translateAbstractConditionalOperator(
578     const AbstractConditionalOperator *CO, CallingContext *Ctx) {
579   auto *C = translate(CO->getCond(), Ctx);
580   auto *T = translate(CO->getTrueExpr(), Ctx);
581   auto *E = translate(CO->getFalseExpr(), Ctx);
582   return new (Arena) til::IfThenElse(C, T, E);
583 }
584 
585 til::SExpr *
586 SExprBuilder::translateDeclStmt(const DeclStmt *S, CallingContext *Ctx) {
587   DeclGroupRef DGrp = S->getDeclGroup();
588   for (DeclGroupRef::iterator I = DGrp.begin(), E = DGrp.end(); I != E; ++I) {
589     if (VarDecl *VD = dyn_cast_or_null<VarDecl>(*I)) {
590       Expr *E = VD->getInit();
591       til::SExpr* SE = translate(E, Ctx);
592 
593       // Add local variables with trivial type to the variable map
594       QualType T = VD->getType();
595       if (T.isTrivialType(VD->getASTContext())) {
596         return addVarDecl(VD, SE);
597       }
598       else {
599         // TODO: add alloca
600       }
601     }
602   }
603   return nullptr;
604 }
605 
606 // If (E) is non-trivial, then add it to the current basic block, and
607 // update the statement map so that S refers to E.  Returns a new variable
608 // that refers to E.
609 // If E is trivial returns E.
610 til::SExpr *SExprBuilder::addStatement(til::SExpr* E, const Stmt *S,
611                                        const ValueDecl *VD) {
612   if (!E || !CurrentBB || E->block() || til::ThreadSafetyTIL::isTrivial(E))
613     return E;
614   if (VD)
615     E = new (Arena) til::Variable(E, VD);
616   CurrentInstructions.push_back(E);
617   if (S)
618     insertStmt(S, E);
619   return E;
620 }
621 
622 // Returns the current value of VD, if known, and nullptr otherwise.
623 til::SExpr *SExprBuilder::lookupVarDecl(const ValueDecl *VD) {
624   auto It = LVarIdxMap.find(VD);
625   if (It != LVarIdxMap.end()) {
626     assert(CurrentLVarMap[It->second].first == VD);
627     return CurrentLVarMap[It->second].second;
628   }
629   return nullptr;
630 }
631 
632 // if E is a til::Variable, update its clangDecl.
633 static void maybeUpdateVD(til::SExpr *E, const ValueDecl *VD) {
634   if (!E)
635     return;
636   if (til::Variable *V = dyn_cast<til::Variable>(E)) {
637     if (!V->clangDecl())
638       V->setClangDecl(VD);
639   }
640 }
641 
642 // Adds a new variable declaration.
643 til::SExpr *SExprBuilder::addVarDecl(const ValueDecl *VD, til::SExpr *E) {
644   maybeUpdateVD(E, VD);
645   LVarIdxMap.insert(std::make_pair(VD, CurrentLVarMap.size()));
646   CurrentLVarMap.makeWritable();
647   CurrentLVarMap.push_back(std::make_pair(VD, E));
648   return E;
649 }
650 
651 // Updates a current variable declaration.  (E.g. by assignment)
652 til::SExpr *SExprBuilder::updateVarDecl(const ValueDecl *VD, til::SExpr *E) {
653   maybeUpdateVD(E, VD);
654   auto It = LVarIdxMap.find(VD);
655   if (It == LVarIdxMap.end()) {
656     til::SExpr *Ptr = new (Arena) til::LiteralPtr(VD);
657     til::SExpr *St  = new (Arena) til::Store(Ptr, E);
658     return St;
659   }
660   CurrentLVarMap.makeWritable();
661   CurrentLVarMap.elem(It->second).second = E;
662   return E;
663 }
664 
665 // Make a Phi node in the current block for the i^th variable in CurrentVarMap.
666 // If E != null, sets Phi[CurrentBlockInfo->ArgIndex] = E.
667 // If E == null, this is a backedge and will be set later.
668 void SExprBuilder::makePhiNodeVar(unsigned i, unsigned NPreds, til::SExpr *E) {
669   unsigned ArgIndex = CurrentBlockInfo->ProcessedPredecessors;
670   assert(ArgIndex > 0 && ArgIndex < NPreds);
671 
672   til::SExpr *CurrE = CurrentLVarMap[i].second;
673   if (CurrE->block() == CurrentBB) {
674     // We already have a Phi node in the current block,
675     // so just add the new variable to the Phi node.
676     til::Phi *Ph = dyn_cast<til::Phi>(CurrE);
677     assert(Ph && "Expecting Phi node.");
678     if (E)
679       Ph->values()[ArgIndex] = E;
680     return;
681   }
682 
683   // Make a new phi node: phi(..., E)
684   // All phi args up to the current index are set to the current value.
685   til::Phi *Ph = new (Arena) til::Phi(Arena, NPreds);
686   Ph->values().setValues(NPreds, nullptr);
687   for (unsigned PIdx = 0; PIdx < ArgIndex; ++PIdx)
688     Ph->values()[PIdx] = CurrE;
689   if (E)
690     Ph->values()[ArgIndex] = E;
691   Ph->setClangDecl(CurrentLVarMap[i].first);
692   // If E is from a back-edge, or either E or CurrE are incomplete, then
693   // mark this node as incomplete; we may need to remove it later.
694   if (!E || isIncompletePhi(E) || isIncompletePhi(CurrE)) {
695     Ph->setStatus(til::Phi::PH_Incomplete);
696   }
697 
698   // Add Phi node to current block, and update CurrentLVarMap[i]
699   CurrentArguments.push_back(Ph);
700   if (Ph->status() == til::Phi::PH_Incomplete)
701     IncompleteArgs.push_back(Ph);
702 
703   CurrentLVarMap.makeWritable();
704   CurrentLVarMap.elem(i).second = Ph;
705 }
706 
707 // Merge values from Map into the current variable map.
708 // This will construct Phi nodes in the current basic block as necessary.
709 void SExprBuilder::mergeEntryMap(LVarDefinitionMap Map) {
710   assert(CurrentBlockInfo && "Not processing a block!");
711 
712   if (!CurrentLVarMap.valid()) {
713     // Steal Map, using copy-on-write.
714     CurrentLVarMap = std::move(Map);
715     return;
716   }
717   if (CurrentLVarMap.sameAs(Map))
718     return;  // Easy merge: maps from different predecessors are unchanged.
719 
720   unsigned NPreds = CurrentBB->numPredecessors();
721   unsigned ESz = CurrentLVarMap.size();
722   unsigned MSz = Map.size();
723   unsigned Sz  = std::min(ESz, MSz);
724 
725   for (unsigned i=0; i<Sz; ++i) {
726     if (CurrentLVarMap[i].first != Map[i].first) {
727       // We've reached the end of variables in common.
728       CurrentLVarMap.makeWritable();
729       CurrentLVarMap.downsize(i);
730       break;
731     }
732     if (CurrentLVarMap[i].second != Map[i].second)
733       makePhiNodeVar(i, NPreds, Map[i].second);
734   }
735   if (ESz > MSz) {
736     CurrentLVarMap.makeWritable();
737     CurrentLVarMap.downsize(Map.size());
738   }
739 }
740 
741 // Merge a back edge into the current variable map.
742 // This will create phi nodes for all variables in the variable map.
743 void SExprBuilder::mergeEntryMapBackEdge() {
744   // We don't have definitions for variables on the backedge, because we
745   // haven't gotten that far in the CFG.  Thus, when encountering a back edge,
746   // we conservatively create Phi nodes for all variables.  Unnecessary Phi
747   // nodes will be marked as incomplete, and stripped out at the end.
748   //
749   // An Phi node is unnecessary if it only refers to itself and one other
750   // variable, e.g. x = Phi(y, y, x)  can be reduced to x = y.
751 
752   assert(CurrentBlockInfo && "Not processing a block!");
753 
754   if (CurrentBlockInfo->HasBackEdges)
755     return;
756   CurrentBlockInfo->HasBackEdges = true;
757 
758   CurrentLVarMap.makeWritable();
759   unsigned Sz = CurrentLVarMap.size();
760   unsigned NPreds = CurrentBB->numPredecessors();
761 
762   for (unsigned i=0; i < Sz; ++i) {
763     makePhiNodeVar(i, NPreds, nullptr);
764   }
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.
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     til::Phi *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 
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 
819 void SExprBuilder::enterCFGBlock(const CFGBlock *B) {
820   // Intialize 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 
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 
847 void SExprBuilder::handlePredecessorBackEdge(const CFGBlock *Pred) {
848   mergeEntryMapBackEdge();
849 }
850 
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 
860 void SExprBuilder::handleStatement(const Stmt *S) {
861   til::SExpr *E = translate(S, nullptr);
862   addStatement(E, S);
863 }
864 
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 
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 arent' critical edges.
896     auto *Tm = new (Arena) til::Branch(C, BB1, BB2);
897     CurrentBB->setTerminator(Tm);
898   }
899 }
900 
901 void SExprBuilder::handleSuccessor(const CFGBlock *Succ) {
902   ++CurrentBlockInfo->UnprocessedSuccessors;
903 }
904 
905 void SExprBuilder::handleSuccessorBackEdge(const CFGBlock *Succ) {
906   mergePhiNodesBackEdge(Succ);
907   ++BBInfo[Succ->getBlockID()].ProcessedPredecessors;
908 }
909 
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 
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