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