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 isIncompletePhi(const SExpr *E) {
67   if (const auto *Ph = dyn_cast<Phi>(E))
68     return Ph->status() == Phi::PH_Incomplete;
69   return false;
70 }
71 
72 }  // end namespace til
73 
74 
75 typedef SExprBuilder::CallingContext CallingContext;
76 
77 
78 til::SExpr *SExprBuilder::lookupStmt(const Stmt *S) {
79   auto It = SMap.find(S);
80   if (It != SMap.end())
81     return It->second;
82   return nullptr;
83 }
84 
85 
86 til::SCFG *SExprBuilder::buildCFG(CFGWalker &Walker) {
87   Walker.walk(*this);
88   return Scfg;
89 }
90 
91 
92 
93 inline bool isCalleeArrow(const Expr *E) {
94   const MemberExpr *ME = dyn_cast<MemberExpr>(E->IgnoreParenCasts());
95   return ME ? ME->isArrow() : false;
96 }
97 
98 
99 /// \brief Translate a clang expression in an attribute to a til::SExpr.
100 /// Constructs the context from D, DeclExp, and SelfDecl.
101 ///
102 /// \param AttrExp The expression to translate.
103 /// \param D       The declaration to which the attribute is attached.
104 /// \param DeclExp An expression involving the Decl to which the attribute
105 ///                is attached.  E.g. the call to a function.
106 CapabilityExpr SExprBuilder::translateAttrExpr(const Expr *AttrExp,
107                                                const NamedDecl *D,
108                                                const Expr *DeclExp,
109                                                VarDecl *SelfDecl) {
110   // If we are processing a raw attribute expression, with no substitutions.
111   if (!DeclExp)
112     return translateAttrExpr(AttrExp, nullptr);
113 
114   CallingContext Ctx(nullptr, D);
115 
116   // Examine DeclExp to find SelfArg and FunArgs, which are used to substitute
117   // for formal parameters when we call buildMutexID later.
118   if (const MemberExpr *ME = dyn_cast<MemberExpr>(DeclExp)) {
119     Ctx.SelfArg   = ME->getBase();
120     Ctx.SelfArrow = ME->isArrow();
121   } else if (const CXXMemberCallExpr *CE =
122              dyn_cast<CXXMemberCallExpr>(DeclExp)) {
123     Ctx.SelfArg   = CE->getImplicitObjectArgument();
124     Ctx.SelfArrow = isCalleeArrow(CE->getCallee());
125     Ctx.NumArgs   = CE->getNumArgs();
126     Ctx.FunArgs   = CE->getArgs();
127   } else if (const CallExpr *CE = dyn_cast<CallExpr>(DeclExp)) {
128     Ctx.NumArgs = CE->getNumArgs();
129     Ctx.FunArgs = CE->getArgs();
130   } else if (const CXXConstructExpr *CE =
131              dyn_cast<CXXConstructExpr>(DeclExp)) {
132     Ctx.SelfArg = nullptr;  // Will be set below
133     Ctx.NumArgs = CE->getNumArgs();
134     Ctx.FunArgs = CE->getArgs();
135   } else if (D && isa<CXXDestructorDecl>(D)) {
136     // There's no such thing as a "destructor call" in the AST.
137     Ctx.SelfArg = DeclExp;
138   }
139 
140   // Hack to handle constructors, where self cannot be recovered from
141   // the expression.
142   if (SelfDecl && !Ctx.SelfArg) {
143     DeclRefExpr SelfDRE(SelfDecl, false, SelfDecl->getType(), VK_LValue,
144                         SelfDecl->getLocation());
145     Ctx.SelfArg = &SelfDRE;
146 
147     // If the attribute has no arguments, then assume the argument is "this".
148     if (!AttrExp)
149       return translateAttrExpr(Ctx.SelfArg, nullptr);
150     else  // For most attributes.
151       return translateAttrExpr(AttrExp, &Ctx);
152   }
153 
154   // If the attribute has no arguments, then assume the argument is "this".
155   if (!AttrExp)
156     return translateAttrExpr(Ctx.SelfArg, nullptr);
157   else  // For most attributes.
158     return translateAttrExpr(AttrExp, &Ctx);
159 }
160 
161 
162 /// \brief Translate a clang expression in an attribute to a til::SExpr.
163 // This assumes a CallingContext has already been created.
164 CapabilityExpr SExprBuilder::translateAttrExpr(const Expr *AttrExp,
165                                                CallingContext *Ctx) {
166   if (!AttrExp)
167     return CapabilityExpr(nullptr, false);
168 
169   if (auto* SLit = dyn_cast<StringLiteral>(AttrExp)) {
170     if (SLit->getString() == StringRef("*"))
171       // The "*" expr is a universal lock, which essentially turns off
172       // checks until it is removed from the lockset.
173       return CapabilityExpr(new (Arena) til::Wildcard(), false);
174     else
175       // Ignore other string literals for now.
176       return CapabilityExpr(nullptr, false);
177   }
178 
179   bool Neg = false;
180   if (auto *OE = dyn_cast<CXXOperatorCallExpr>(AttrExp)) {
181     if (OE->getOperator() == OO_Exclaim) {
182       Neg = true;
183       AttrExp = OE->getArg(0);
184     }
185   }
186   else if (auto *UO = dyn_cast<UnaryOperator>(AttrExp)) {
187     if (UO->getOpcode() == UO_LNot) {
188       Neg = true;
189       AttrExp = UO->getSubExpr();
190     }
191   }
192 
193   til::SExpr *E = translate(AttrExp, Ctx);
194 
195   // Trap mutex expressions like nullptr, or 0.
196   // Any literal value is nonsense.
197   if (!E || isa<til::Literal>(E))
198     return CapabilityExpr(nullptr, false);
199 
200   // Hack to deal with smart pointers -- strip off top-level pointer casts.
201   if (auto *CE = dyn_cast_or_null<til::Cast>(E)) {
202     if (CE->castOpcode() == til::CAST_objToPtr)
203       return CapabilityExpr(CE->expr(), Neg);
204   }
205   return CapabilityExpr(E, Neg);
206 }
207 
208 
209 
210 // Translate a clang statement or expression to a TIL expression.
211 // Also performs substitution of variables; Ctx provides the context.
212 // Dispatches on the type of S.
213 til::SExpr *SExprBuilder::translate(const Stmt *S, CallingContext *Ctx) {
214   if (!S)
215     return nullptr;
216 
217   // Check if S has already been translated and cached.
218   // This handles the lookup of SSA names for DeclRefExprs here.
219   if (til::SExpr *E = lookupStmt(S))
220     return E;
221 
222   switch (S->getStmtClass()) {
223   case Stmt::DeclRefExprClass:
224     return translateDeclRefExpr(cast<DeclRefExpr>(S), Ctx);
225   case Stmt::CXXThisExprClass:
226     return translateCXXThisExpr(cast<CXXThisExpr>(S), Ctx);
227   case Stmt::MemberExprClass:
228     return translateMemberExpr(cast<MemberExpr>(S), Ctx);
229   case Stmt::CallExprClass:
230     return translateCallExpr(cast<CallExpr>(S), Ctx);
231   case Stmt::CXXMemberCallExprClass:
232     return translateCXXMemberCallExpr(cast<CXXMemberCallExpr>(S), Ctx);
233   case Stmt::CXXOperatorCallExprClass:
234     return translateCXXOperatorCallExpr(cast<CXXOperatorCallExpr>(S), Ctx);
235   case Stmt::UnaryOperatorClass:
236     return translateUnaryOperator(cast<UnaryOperator>(S), Ctx);
237   case Stmt::BinaryOperatorClass:
238   case Stmt::CompoundAssignOperatorClass:
239     return translateBinaryOperator(cast<BinaryOperator>(S), Ctx);
240 
241   case Stmt::ArraySubscriptExprClass:
242     return translateArraySubscriptExpr(cast<ArraySubscriptExpr>(S), Ctx);
243   case Stmt::ConditionalOperatorClass:
244     return translateAbstractConditionalOperator(
245              cast<ConditionalOperator>(S), Ctx);
246   case Stmt::BinaryConditionalOperatorClass:
247     return translateAbstractConditionalOperator(
248              cast<BinaryConditionalOperator>(S), Ctx);
249 
250   // We treat these as no-ops
251   case Stmt::ParenExprClass:
252     return translate(cast<ParenExpr>(S)->getSubExpr(), Ctx);
253   case Stmt::ExprWithCleanupsClass:
254     return translate(cast<ExprWithCleanups>(S)->getSubExpr(), Ctx);
255   case Stmt::CXXBindTemporaryExprClass:
256     return translate(cast<CXXBindTemporaryExpr>(S)->getSubExpr(), Ctx);
257 
258   // Collect all literals
259   case Stmt::CharacterLiteralClass:
260   case Stmt::CXXNullPtrLiteralExprClass:
261   case Stmt::GNUNullExprClass:
262   case Stmt::CXXBoolLiteralExprClass:
263   case Stmt::FloatingLiteralClass:
264   case Stmt::ImaginaryLiteralClass:
265   case Stmt::IntegerLiteralClass:
266   case Stmt::StringLiteralClass:
267   case Stmt::ObjCStringLiteralClass:
268     return new (Arena) til::Literal(cast<Expr>(S));
269 
270   case Stmt::DeclStmtClass:
271     return translateDeclStmt(cast<DeclStmt>(S), Ctx);
272   default:
273     break;
274   }
275   if (const CastExpr *CE = dyn_cast<CastExpr>(S))
276     return translateCastExpr(CE, Ctx);
277 
278   return new (Arena) til::Undefined(S);
279 }
280 
281 
282 
283 til::SExpr *SExprBuilder::translateDeclRefExpr(const DeclRefExpr *DRE,
284                                                CallingContext *Ctx) {
285   const ValueDecl *VD = cast<ValueDecl>(DRE->getDecl()->getCanonicalDecl());
286 
287   // Function parameters require substitution and/or renaming.
288   if (const ParmVarDecl *PV = dyn_cast_or_null<ParmVarDecl>(VD)) {
289     const FunctionDecl *FD =
290         cast<FunctionDecl>(PV->getDeclContext())->getCanonicalDecl();
291     unsigned I = PV->getFunctionScopeIndex();
292 
293     if (Ctx && Ctx->FunArgs && FD == Ctx->AttrDecl->getCanonicalDecl()) {
294       // Substitute call arguments for references to function parameters
295       assert(I < Ctx->NumArgs);
296       return translate(Ctx->FunArgs[I], Ctx->Prev);
297     }
298     // Map the param back to the param of the original function declaration
299     // for consistent comparisons.
300     VD = FD->getParamDecl(I);
301   }
302 
303   // For non-local variables, treat it as a referenced to a named object.
304   return new (Arena) til::LiteralPtr(VD);
305 }
306 
307 
308 til::SExpr *SExprBuilder::translateCXXThisExpr(const CXXThisExpr *TE,
309                                                CallingContext *Ctx) {
310   // Substitute for 'this'
311   if (Ctx && Ctx->SelfArg)
312     return translate(Ctx->SelfArg, Ctx->Prev);
313   assert(SelfVar && "We have no variable for 'this'!");
314   return SelfVar;
315 }
316 
317 
318 const ValueDecl *getValueDeclFromSExpr(const til::SExpr *E) {
319   if (auto *V = dyn_cast<til::Variable>(E))
320     return V->clangDecl();
321   if (auto *Ph = dyn_cast<til::Phi>(E))
322     return Ph->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 || E->block() || til::ThreadSafetyTIL::isTrivial(E))
645     return E;
646   if (VD)
647     E = new (Arena) til::Variable(E, VD);
648   CurrentInstructions.push_back(E);
649   if (S)
650     insertStmt(S, E);
651   return E;
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::SExpr *CurrE = CurrentLVarMap[i].second;
709   if (CurrE->block() == CurrentBB) {
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>(CurrE);
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::Phi *Ph = new (Arena) til::Phi(Arena, NPreds);
722   Ph->values().setValues(NPreds, nullptr);
723   for (unsigned PIdx = 0; PIdx < ArgIndex; ++PIdx)
724     Ph->values()[PIdx] = CurrE;
725   if (E)
726     Ph->values()[ArgIndex] = E;
727   Ph->setClangDecl(CurrentLVarMap[i].first);
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 || isIncompletePhi(E) || isIncompletePhi(CurrE)) {
731     Ph->setStatus(til::Phi::PH_Incomplete);
732   }
733 
734   // Add Phi node to current block, and update CurrentLVarMap[i]
735   CurrentArguments.push_back(Ph);
736   if (Ph->status() == til::Phi::PH_Incomplete)
737     IncompleteArgs.push_back(Ph);
738 
739   CurrentLVarMap.makeWritable();
740   CurrentLVarMap.elem(i).second = Ph;
741 }
742 
743 
744 // Merge values from Map into the current variable map.
745 // This will construct Phi nodes in the current basic block as necessary.
746 void SExprBuilder::mergeEntryMap(LVarDefinitionMap Map) {
747   assert(CurrentBlockInfo && "Not processing a block!");
748 
749   if (!CurrentLVarMap.valid()) {
750     // Steal Map, using copy-on-write.
751     CurrentLVarMap = std::move(Map);
752     return;
753   }
754   if (CurrentLVarMap.sameAs(Map))
755     return;  // Easy merge: maps from different predecessors are unchanged.
756 
757   unsigned NPreds = CurrentBB->numPredecessors();
758   unsigned ESz = CurrentLVarMap.size();
759   unsigned MSz = Map.size();
760   unsigned Sz  = std::min(ESz, MSz);
761 
762   for (unsigned i=0; i<Sz; ++i) {
763     if (CurrentLVarMap[i].first != Map[i].first) {
764       // We've reached the end of variables in common.
765       CurrentLVarMap.makeWritable();
766       CurrentLVarMap.downsize(i);
767       break;
768     }
769     if (CurrentLVarMap[i].second != Map[i].second)
770       makePhiNodeVar(i, NPreds, Map[i].second);
771   }
772   if (ESz > MSz) {
773     CurrentLVarMap.makeWritable();
774     CurrentLVarMap.downsize(Map.size());
775   }
776 }
777 
778 
779 // Merge a back edge into the current variable map.
780 // This will create phi nodes for all variables in the variable map.
781 void SExprBuilder::mergeEntryMapBackEdge() {
782   // We don't have definitions for variables on the backedge, because we
783   // haven't gotten that far in the CFG.  Thus, when encountering a back edge,
784   // we conservatively create Phi nodes for all variables.  Unnecessary Phi
785   // nodes will be marked as incomplete, and stripped out at the end.
786   //
787   // An Phi node is unnecessary if it only refers to itself and one other
788   // variable, e.g. x = Phi(y, y, x)  can be reduced to x = y.
789 
790   assert(CurrentBlockInfo && "Not processing a block!");
791 
792   if (CurrentBlockInfo->HasBackEdges)
793     return;
794   CurrentBlockInfo->HasBackEdges = true;
795 
796   CurrentLVarMap.makeWritable();
797   unsigned Sz = CurrentLVarMap.size();
798   unsigned NPreds = CurrentBB->numPredecessors();
799 
800   for (unsigned i=0; i < Sz; ++i) {
801     makePhiNodeVar(i, NPreds, nullptr);
802   }
803 }
804 
805 
806 // Update the phi nodes that were initially created for a back edge
807 // once the variable definitions have been computed.
808 // I.e., merge the current variable map into the phi nodes for Blk.
809 void SExprBuilder::mergePhiNodesBackEdge(const CFGBlock *Blk) {
810   til::BasicBlock *BB = lookupBlock(Blk);
811   unsigned ArgIndex = BBInfo[Blk->getBlockID()].ProcessedPredecessors;
812   assert(ArgIndex > 0 && ArgIndex < BB->numPredecessors());
813 
814   for (til::SExpr *PE : BB->arguments()) {
815     til::Phi *Ph = dyn_cast_or_null<til::Phi>(PE);
816     assert(Ph && "Expecting Phi Node.");
817     assert(Ph->values()[ArgIndex] == nullptr && "Wrong index for back edge.");
818 
819     til::SExpr *E = lookupVarDecl(Ph->clangDecl());
820     assert(E && "Couldn't find local variable for Phi node.");
821     Ph->values()[ArgIndex] = E;
822   }
823 }
824 
825 void SExprBuilder::enterCFG(CFG *Cfg, const NamedDecl *D,
826                             const CFGBlock *First) {
827   // Perform initial setup operations.
828   unsigned NBlocks = Cfg->getNumBlockIDs();
829   Scfg = new (Arena) til::SCFG(Arena, NBlocks);
830 
831   // allocate all basic blocks immediately, to handle forward references.
832   BBInfo.resize(NBlocks);
833   BlockMap.resize(NBlocks, nullptr);
834   // create map from clang blockID to til::BasicBlocks
835   for (auto *B : *Cfg) {
836     auto *BB = new (Arena) til::BasicBlock(Arena);
837     BB->reserveInstructions(B->size());
838     BlockMap[B->getBlockID()] = BB;
839   }
840 
841   CurrentBB = lookupBlock(&Cfg->getEntry());
842   auto Parms = isa<ObjCMethodDecl>(D) ? cast<ObjCMethodDecl>(D)->parameters()
843                                       : cast<FunctionDecl>(D)->parameters();
844   for (auto *Pm : Parms) {
845     QualType T = Pm->getType();
846     if (!T.isTrivialType(Pm->getASTContext()))
847       continue;
848 
849     // Add parameters to local variable map.
850     // FIXME: right now we emulate params with loads; that should be fixed.
851     til::SExpr *Lp = new (Arena) til::LiteralPtr(Pm);
852     til::SExpr *Ld = new (Arena) til::Load(Lp);
853     til::SExpr *V  = addStatement(Ld, nullptr, Pm);
854     addVarDecl(Pm, V);
855   }
856 }
857 
858 
859 void SExprBuilder::enterCFGBlock(const CFGBlock *B) {
860   // Intialize TIL basic block and add it to the CFG.
861   CurrentBB = lookupBlock(B);
862   CurrentBB->reservePredecessors(B->pred_size());
863   Scfg->add(CurrentBB);
864 
865   CurrentBlockInfo = &BBInfo[B->getBlockID()];
866 
867   // CurrentLVarMap is moved to ExitMap on block exit.
868   // FIXME: the entry block will hold function parameters.
869   // assert(!CurrentLVarMap.valid() && "CurrentLVarMap already initialized.");
870 }
871 
872 
873 void SExprBuilder::handlePredecessor(const CFGBlock *Pred) {
874   // Compute CurrentLVarMap on entry from ExitMaps of predecessors
875 
876   CurrentBB->addPredecessor(BlockMap[Pred->getBlockID()]);
877   BlockInfo *PredInfo = &BBInfo[Pred->getBlockID()];
878   assert(PredInfo->UnprocessedSuccessors > 0);
879 
880   if (--PredInfo->UnprocessedSuccessors == 0)
881     mergeEntryMap(std::move(PredInfo->ExitMap));
882   else
883     mergeEntryMap(PredInfo->ExitMap.clone());
884 
885   ++CurrentBlockInfo->ProcessedPredecessors;
886 }
887 
888 
889 void SExprBuilder::handlePredecessorBackEdge(const CFGBlock *Pred) {
890   mergeEntryMapBackEdge();
891 }
892 
893 
894 void SExprBuilder::enterCFGBlockBody(const CFGBlock *B) {
895   // The merge*() methods have created arguments.
896   // Push those arguments onto the basic block.
897   CurrentBB->arguments().reserve(
898     static_cast<unsigned>(CurrentArguments.size()), Arena);
899   for (auto *A : CurrentArguments)
900     CurrentBB->addArgument(A);
901 }
902 
903 
904 void SExprBuilder::handleStatement(const Stmt *S) {
905   til::SExpr *E = translate(S, nullptr);
906   addStatement(E, S);
907 }
908 
909 
910 void SExprBuilder::handleDestructorCall(const VarDecl *VD,
911                                         const CXXDestructorDecl *DD) {
912   til::SExpr *Sf = new (Arena) til::LiteralPtr(VD);
913   til::SExpr *Dr = new (Arena) til::LiteralPtr(DD);
914   til::SExpr *Ap = new (Arena) til::Apply(Dr, Sf);
915   til::SExpr *E = new (Arena) til::Call(Ap);
916   addStatement(E, nullptr);
917 }
918 
919 
920 
921 void SExprBuilder::exitCFGBlockBody(const CFGBlock *B) {
922   CurrentBB->instructions().reserve(
923     static_cast<unsigned>(CurrentInstructions.size()), Arena);
924   for (auto *V : CurrentInstructions)
925     CurrentBB->addInstruction(V);
926 
927   // Create an appropriate terminator
928   unsigned N = B->succ_size();
929   auto It = B->succ_begin();
930   if (N == 1) {
931     til::BasicBlock *BB = *It ? lookupBlock(*It) : nullptr;
932     // TODO: set index
933     unsigned Idx = BB ? BB->findPredecessorIndex(CurrentBB) : 0;
934     auto *Tm = new (Arena) til::Goto(BB, Idx);
935     CurrentBB->setTerminator(Tm);
936   }
937   else if (N == 2) {
938     til::SExpr *C = translate(B->getTerminatorCondition(true), nullptr);
939     til::BasicBlock *BB1 = *It ? lookupBlock(*It) : nullptr;
940     ++It;
941     til::BasicBlock *BB2 = *It ? lookupBlock(*It) : nullptr;
942     // FIXME: make sure these arent' critical edges.
943     auto *Tm = new (Arena) til::Branch(C, BB1, BB2);
944     CurrentBB->setTerminator(Tm);
945   }
946 }
947 
948 
949 void SExprBuilder::handleSuccessor(const CFGBlock *Succ) {
950   ++CurrentBlockInfo->UnprocessedSuccessors;
951 }
952 
953 
954 void SExprBuilder::handleSuccessorBackEdge(const CFGBlock *Succ) {
955   mergePhiNodesBackEdge(Succ);
956   ++BBInfo[Succ->getBlockID()].ProcessedPredecessors;
957 }
958 
959 
960 void SExprBuilder::exitCFGBlock(const CFGBlock *B) {
961   CurrentArguments.clear();
962   CurrentInstructions.clear();
963   CurrentBlockInfo->ExitMap = std::move(CurrentLVarMap);
964   CurrentBB = nullptr;
965   CurrentBlockInfo = nullptr;
966 }
967 
968 
969 void SExprBuilder::exitCFG(const CFGBlock *Last) {
970   for (auto *Ph : IncompleteArgs) {
971     if (Ph->status() == til::Phi::PH_Incomplete)
972       simplifyIncompleteArg(Ph);
973   }
974 
975   CurrentArguments.clear();
976   CurrentInstructions.clear();
977   IncompleteArgs.clear();
978 }
979 
980 
981 /*
982 void printSCFG(CFGWalker &Walker) {
983   llvm::BumpPtrAllocator Bpa;
984   til::MemRegionRef Arena(&Bpa);
985   SExprBuilder SxBuilder(Arena);
986   til::SCFG *Scfg = SxBuilder.buildCFG(Walker);
987   TILPrinter::print(Scfg, llvm::errs());
988 }
989 */
990 
991 
992 } // end namespace threadSafety
993 
994 } // end namespace clang
995