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