xref: /llvm-project/clang/lib/Analysis/Consumed.cpp (revision d5d62a99a91391f7dd6f18cb1e8f2cb7ab06ded6)
1 //===- Consumed.cpp -------------------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // A intra-procedural analysis for checking consumed properties.  This is based,
10 // in part, on research on linear types.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "clang/Analysis/Analyses/Consumed.h"
15 #include "clang/AST/Attr.h"
16 #include "clang/AST/Decl.h"
17 #include "clang/AST/DeclCXX.h"
18 #include "clang/AST/Expr.h"
19 #include "clang/AST/ExprCXX.h"
20 #include "clang/AST/Stmt.h"
21 #include "clang/AST/StmtVisitor.h"
22 #include "clang/AST/Type.h"
23 #include "clang/Analysis/Analyses/PostOrderCFGView.h"
24 #include "clang/Analysis/AnalysisDeclContext.h"
25 #include "clang/Analysis/CFG.h"
26 #include "clang/Basic/LLVM.h"
27 #include "clang/Basic/OperatorKinds.h"
28 #include "clang/Basic/SourceLocation.h"
29 #include "llvm/ADT/DenseMap.h"
30 #include "llvm/ADT/Optional.h"
31 #include "llvm/ADT/STLExtras.h"
32 #include "llvm/ADT/StringRef.h"
33 #include "llvm/Support/Casting.h"
34 #include "llvm/Support/ErrorHandling.h"
35 #include <cassert>
36 #include <memory>
37 #include <utility>
38 
39 // TODO: Adjust states of args to constructors in the same way that arguments to
40 //       function calls are handled.
41 // TODO: Use information from tests in for- and while-loop conditional.
42 // TODO: Add notes about the actual and expected state for
43 // TODO: Correctly identify unreachable blocks when chaining boolean operators.
44 // TODO: Adjust the parser and AttributesList class to support lists of
45 //       identifiers.
46 // TODO: Warn about unreachable code.
47 // TODO: Switch to using a bitmap to track unreachable blocks.
48 // TODO: Handle variable definitions, e.g. bool valid = x.isValid();
49 //       if (valid) ...; (Deferred)
50 // TODO: Take notes on state transitions to provide better warning messages.
51 //       (Deferred)
52 // TODO: Test nested conditionals: A) Checking the same value multiple times,
53 //       and 2) Checking different values. (Deferred)
54 
55 using namespace clang;
56 using namespace consumed;
57 
58 // Key method definition
59 ConsumedWarningsHandlerBase::~ConsumedWarningsHandlerBase() = default;
60 
61 static SourceLocation getFirstStmtLoc(const CFGBlock *Block) {
62   // Find the source location of the first statement in the block, if the block
63   // is not empty.
64   for (const auto &B : *Block)
65     if (Optional<CFGStmt> CS = B.getAs<CFGStmt>())
66       return CS->getStmt()->getBeginLoc();
67 
68   // Block is empty.
69   // If we have one successor, return the first statement in that block
70   if (Block->succ_size() == 1 && *Block->succ_begin())
71     return getFirstStmtLoc(*Block->succ_begin());
72 
73   return {};
74 }
75 
76 static SourceLocation getLastStmtLoc(const CFGBlock *Block) {
77   // Find the source location of the last statement in the block, if the block
78   // is not empty.
79   if (const Stmt *StmtNode = Block->getTerminatorStmt()) {
80     return StmtNode->getBeginLoc();
81   } else {
82     for (CFGBlock::const_reverse_iterator BI = Block->rbegin(),
83          BE = Block->rend(); BI != BE; ++BI) {
84       if (Optional<CFGStmt> CS = BI->getAs<CFGStmt>())
85         return CS->getStmt()->getBeginLoc();
86     }
87   }
88 
89   // If we have one successor, return the first statement in that block
90   SourceLocation Loc;
91   if (Block->succ_size() == 1 && *Block->succ_begin())
92     Loc = getFirstStmtLoc(*Block->succ_begin());
93   if (Loc.isValid())
94     return Loc;
95 
96   // If we have one predecessor, return the last statement in that block
97   if (Block->pred_size() == 1 && *Block->pred_begin())
98     return getLastStmtLoc(*Block->pred_begin());
99 
100   return Loc;
101 }
102 
103 static ConsumedState invertConsumedUnconsumed(ConsumedState State) {
104   switch (State) {
105   case CS_Unconsumed:
106     return CS_Consumed;
107   case CS_Consumed:
108     return CS_Unconsumed;
109   case CS_None:
110     return CS_None;
111   case CS_Unknown:
112     return CS_Unknown;
113   }
114   llvm_unreachable("invalid enum");
115 }
116 
117 static bool isCallableInState(const CallableWhenAttr *CWAttr,
118                               ConsumedState State) {
119   for (const auto &S : CWAttr->callableStates()) {
120     ConsumedState MappedAttrState = CS_None;
121 
122     switch (S) {
123     case CallableWhenAttr::Unknown:
124       MappedAttrState = CS_Unknown;
125       break;
126 
127     case CallableWhenAttr::Unconsumed:
128       MappedAttrState = CS_Unconsumed;
129       break;
130 
131     case CallableWhenAttr::Consumed:
132       MappedAttrState = CS_Consumed;
133       break;
134     }
135 
136     if (MappedAttrState == State)
137       return true;
138   }
139 
140   return false;
141 }
142 
143 static bool isConsumableType(const QualType &QT) {
144   if (QT->isPointerType() || QT->isReferenceType())
145     return false;
146 
147   if (const CXXRecordDecl *RD = QT->getAsCXXRecordDecl())
148     return RD->hasAttr<ConsumableAttr>();
149 
150   return false;
151 }
152 
153 static bool isAutoCastType(const QualType &QT) {
154   if (QT->isPointerType() || QT->isReferenceType())
155     return false;
156 
157   if (const CXXRecordDecl *RD = QT->getAsCXXRecordDecl())
158     return RD->hasAttr<ConsumableAutoCastAttr>();
159 
160   return false;
161 }
162 
163 static bool isSetOnReadPtrType(const QualType &QT) {
164   if (const CXXRecordDecl *RD = QT->getPointeeCXXRecordDecl())
165     return RD->hasAttr<ConsumableSetOnReadAttr>();
166   return false;
167 }
168 
169 static bool isKnownState(ConsumedState State) {
170   switch (State) {
171   case CS_Unconsumed:
172   case CS_Consumed:
173     return true;
174   case CS_None:
175   case CS_Unknown:
176     return false;
177   }
178   llvm_unreachable("invalid enum");
179 }
180 
181 static bool isRValueRef(QualType ParamType) {
182   return ParamType->isRValueReferenceType();
183 }
184 
185 static bool isTestingFunction(const FunctionDecl *FunDecl) {
186   return FunDecl->hasAttr<TestTypestateAttr>();
187 }
188 
189 static bool isPointerOrRef(QualType ParamType) {
190   return ParamType->isPointerType() || ParamType->isReferenceType();
191 }
192 
193 static ConsumedState mapConsumableAttrState(const QualType QT) {
194   assert(isConsumableType(QT));
195 
196   const ConsumableAttr *CAttr =
197       QT->getAsCXXRecordDecl()->getAttr<ConsumableAttr>();
198 
199   switch (CAttr->getDefaultState()) {
200   case ConsumableAttr::Unknown:
201     return CS_Unknown;
202   case ConsumableAttr::Unconsumed:
203     return CS_Unconsumed;
204   case ConsumableAttr::Consumed:
205     return CS_Consumed;
206   }
207   llvm_unreachable("invalid enum");
208 }
209 
210 static ConsumedState
211 mapParamTypestateAttrState(const ParamTypestateAttr *PTAttr) {
212   switch (PTAttr->getParamState()) {
213   case ParamTypestateAttr::Unknown:
214     return CS_Unknown;
215   case ParamTypestateAttr::Unconsumed:
216     return CS_Unconsumed;
217   case ParamTypestateAttr::Consumed:
218     return CS_Consumed;
219   }
220   llvm_unreachable("invalid_enum");
221 }
222 
223 static ConsumedState
224 mapReturnTypestateAttrState(const ReturnTypestateAttr *RTSAttr) {
225   switch (RTSAttr->getState()) {
226   case ReturnTypestateAttr::Unknown:
227     return CS_Unknown;
228   case ReturnTypestateAttr::Unconsumed:
229     return CS_Unconsumed;
230   case ReturnTypestateAttr::Consumed:
231     return CS_Consumed;
232   }
233   llvm_unreachable("invalid enum");
234 }
235 
236 static ConsumedState mapSetTypestateAttrState(const SetTypestateAttr *STAttr) {
237   switch (STAttr->getNewState()) {
238   case SetTypestateAttr::Unknown:
239     return CS_Unknown;
240   case SetTypestateAttr::Unconsumed:
241     return CS_Unconsumed;
242   case SetTypestateAttr::Consumed:
243     return CS_Consumed;
244   }
245   llvm_unreachable("invalid_enum");
246 }
247 
248 static StringRef stateToString(ConsumedState State) {
249   switch (State) {
250   case consumed::CS_None:
251     return "none";
252 
253   case consumed::CS_Unknown:
254     return "unknown";
255 
256   case consumed::CS_Unconsumed:
257     return "unconsumed";
258 
259   case consumed::CS_Consumed:
260     return "consumed";
261   }
262   llvm_unreachable("invalid enum");
263 }
264 
265 static ConsumedState testsFor(const FunctionDecl *FunDecl) {
266   assert(isTestingFunction(FunDecl));
267   switch (FunDecl->getAttr<TestTypestateAttr>()->getTestState()) {
268   case TestTypestateAttr::Unconsumed:
269     return CS_Unconsumed;
270   case TestTypestateAttr::Consumed:
271     return CS_Consumed;
272   }
273   llvm_unreachable("invalid enum");
274 }
275 
276 namespace {
277 
278 struct VarTestResult {
279   const VarDecl *Var;
280   ConsumedState TestsFor;
281 };
282 
283 } // namespace
284 
285 namespace clang {
286 namespace consumed {
287 
288 enum EffectiveOp {
289   EO_And,
290   EO_Or
291 };
292 
293 class PropagationInfo {
294   enum {
295     IT_None,
296     IT_State,
297     IT_VarTest,
298     IT_BinTest,
299     IT_Var,
300     IT_Tmp
301   } InfoType = IT_None;
302 
303   struct BinTestTy {
304     const BinaryOperator *Source;
305     EffectiveOp EOp;
306     VarTestResult LTest;
307     VarTestResult RTest;
308   };
309 
310   union {
311     ConsumedState State;
312     VarTestResult VarTest;
313     const VarDecl *Var;
314     const CXXBindTemporaryExpr *Tmp;
315     BinTestTy BinTest;
316   };
317 
318 public:
319   PropagationInfo() = default;
320   PropagationInfo(const VarTestResult &VarTest)
321       : InfoType(IT_VarTest), VarTest(VarTest) {}
322 
323   PropagationInfo(const VarDecl *Var, ConsumedState TestsFor)
324       : InfoType(IT_VarTest) {
325     VarTest.Var      = Var;
326     VarTest.TestsFor = TestsFor;
327   }
328 
329   PropagationInfo(const BinaryOperator *Source, EffectiveOp EOp,
330                   const VarTestResult &LTest, const VarTestResult &RTest)
331       : InfoType(IT_BinTest) {
332     BinTest.Source  = Source;
333     BinTest.EOp     = EOp;
334     BinTest.LTest   = LTest;
335     BinTest.RTest   = RTest;
336   }
337 
338   PropagationInfo(const BinaryOperator *Source, EffectiveOp EOp,
339                   const VarDecl *LVar, ConsumedState LTestsFor,
340                   const VarDecl *RVar, ConsumedState RTestsFor)
341       : InfoType(IT_BinTest) {
342     BinTest.Source         = Source;
343     BinTest.EOp            = EOp;
344     BinTest.LTest.Var      = LVar;
345     BinTest.LTest.TestsFor = LTestsFor;
346     BinTest.RTest.Var      = RVar;
347     BinTest.RTest.TestsFor = RTestsFor;
348   }
349 
350   PropagationInfo(ConsumedState State)
351       : InfoType(IT_State), State(State) {}
352   PropagationInfo(const VarDecl *Var) : InfoType(IT_Var), Var(Var) {}
353   PropagationInfo(const CXXBindTemporaryExpr *Tmp)
354       : InfoType(IT_Tmp), Tmp(Tmp) {}
355 
356   const ConsumedState &getState() const {
357     assert(InfoType == IT_State);
358     return State;
359   }
360 
361   const VarTestResult &getVarTest() const {
362     assert(InfoType == IT_VarTest);
363     return VarTest;
364   }
365 
366   const VarTestResult &getLTest() const {
367     assert(InfoType == IT_BinTest);
368     return BinTest.LTest;
369   }
370 
371   const VarTestResult &getRTest() const {
372     assert(InfoType == IT_BinTest);
373     return BinTest.RTest;
374   }
375 
376   const VarDecl *getVar() const {
377     assert(InfoType == IT_Var);
378     return Var;
379   }
380 
381   const CXXBindTemporaryExpr *getTmp() const {
382     assert(InfoType == IT_Tmp);
383     return Tmp;
384   }
385 
386   ConsumedState getAsState(const ConsumedStateMap *StateMap) const {
387     assert(isVar() || isTmp() || isState());
388 
389     if (isVar())
390       return StateMap->getState(Var);
391     else if (isTmp())
392       return StateMap->getState(Tmp);
393     else if (isState())
394       return State;
395     else
396       return CS_None;
397   }
398 
399   EffectiveOp testEffectiveOp() const {
400     assert(InfoType == IT_BinTest);
401     return BinTest.EOp;
402   }
403 
404   const BinaryOperator * testSourceNode() const {
405     assert(InfoType == IT_BinTest);
406     return BinTest.Source;
407   }
408 
409   bool isValid() const { return InfoType != IT_None; }
410   bool isState() const { return InfoType == IT_State; }
411   bool isVarTest() const { return InfoType == IT_VarTest; }
412   bool isBinTest() const { return InfoType == IT_BinTest; }
413   bool isVar() const { return InfoType == IT_Var; }
414   bool isTmp() const { return InfoType == IT_Tmp; }
415 
416   bool isTest() const {
417     return InfoType == IT_VarTest || InfoType == IT_BinTest;
418   }
419 
420   bool isPointerToValue() const {
421     return InfoType == IT_Var || InfoType == IT_Tmp;
422   }
423 
424   PropagationInfo invertTest() const {
425     assert(InfoType == IT_VarTest || InfoType == IT_BinTest);
426 
427     if (InfoType == IT_VarTest) {
428       return PropagationInfo(VarTest.Var,
429                              invertConsumedUnconsumed(VarTest.TestsFor));
430 
431     } else if (InfoType == IT_BinTest) {
432       return PropagationInfo(BinTest.Source,
433         BinTest.EOp == EO_And ? EO_Or : EO_And,
434         BinTest.LTest.Var, invertConsumedUnconsumed(BinTest.LTest.TestsFor),
435         BinTest.RTest.Var, invertConsumedUnconsumed(BinTest.RTest.TestsFor));
436     } else {
437       return {};
438     }
439   }
440 };
441 
442 } // namespace consumed
443 } // namespace clang
444 
445 static void
446 setStateForVarOrTmp(ConsumedStateMap *StateMap, const PropagationInfo &PInfo,
447                     ConsumedState State) {
448   assert(PInfo.isVar() || PInfo.isTmp());
449 
450   if (PInfo.isVar())
451     StateMap->setState(PInfo.getVar(), State);
452   else
453     StateMap->setState(PInfo.getTmp(), State);
454 }
455 
456 namespace clang {
457 namespace consumed {
458 
459 class ConsumedStmtVisitor : public ConstStmtVisitor<ConsumedStmtVisitor> {
460   using MapType = llvm::DenseMap<const Stmt *, PropagationInfo>;
461   using PairType= std::pair<const Stmt *, PropagationInfo>;
462   using InfoEntry = MapType::iterator;
463   using ConstInfoEntry = MapType::const_iterator;
464 
465   ConsumedAnalyzer &Analyzer;
466   ConsumedStateMap *StateMap;
467   MapType PropagationMap;
468 
469   InfoEntry findInfo(const Expr *E) {
470     if (const auto Cleanups = dyn_cast<ExprWithCleanups>(E))
471       if (!Cleanups->cleanupsHaveSideEffects())
472         E = Cleanups->getSubExpr();
473     return PropagationMap.find(E->IgnoreParens());
474   }
475 
476   ConstInfoEntry findInfo(const Expr *E) const {
477     if (const auto Cleanups = dyn_cast<ExprWithCleanups>(E))
478       if (!Cleanups->cleanupsHaveSideEffects())
479         E = Cleanups->getSubExpr();
480     return PropagationMap.find(E->IgnoreParens());
481   }
482 
483   void insertInfo(const Expr *E, const PropagationInfo &PI) {
484     PropagationMap.insert(PairType(E->IgnoreParens(), PI));
485   }
486 
487   void forwardInfo(const Expr *From, const Expr *To);
488   void copyInfo(const Expr *From, const Expr *To, ConsumedState CS);
489   ConsumedState getInfo(const Expr *From);
490   void setInfo(const Expr *To, ConsumedState NS);
491   void propagateReturnType(const Expr *Call, const FunctionDecl *Fun);
492 
493 public:
494   void checkCallability(const PropagationInfo &PInfo,
495                         const FunctionDecl *FunDecl,
496                         SourceLocation BlameLoc);
497 
498   using ArgRange = llvm::iterator_range<CallExpr::const_arg_iterator>;
499   bool handleCall(const Expr *Call, const Expr *ObjArg,
500                   ArgRange args, const FunctionDecl *FunD);
501 
502   void VisitBinaryOperator(const BinaryOperator *BinOp);
503   void VisitCallExpr(const CallExpr *Call);
504   void VisitCastExpr(const CastExpr *Cast);
505   void VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *Temp);
506   void VisitCXXConstructExpr(const CXXConstructExpr *Call);
507   void VisitCXXMemberCallExpr(const CXXMemberCallExpr *Call);
508   void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *Call);
509   void VisitDeclRefExpr(const DeclRefExpr *DeclRef);
510   void VisitDeclStmt(const DeclStmt *DelcS);
511   void VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *Temp);
512   void VisitMemberExpr(const MemberExpr *MExpr);
513   void VisitParmVarDecl(const ParmVarDecl *Param);
514   void VisitReturnStmt(const ReturnStmt *Ret);
515   void VisitUnaryOperator(const UnaryOperator *UOp);
516   void VisitVarDecl(const VarDecl *Var);
517 
518   ConsumedStmtVisitor(ConsumedAnalyzer &Analyzer, ConsumedStateMap *StateMap)
519       : Analyzer(Analyzer), StateMap(StateMap) {}
520 
521   PropagationInfo getInfo(const Expr *StmtNode) const {
522     ConstInfoEntry Entry = findInfo(StmtNode);
523 
524     if (Entry != PropagationMap.end())
525       return Entry->second;
526     else
527       return {};
528   }
529 
530   void reset(ConsumedStateMap *NewStateMap) {
531     StateMap = NewStateMap;
532   }
533 };
534 
535 } // namespace consumed
536 } // namespace clang
537 
538 void ConsumedStmtVisitor::forwardInfo(const Expr *From, const Expr *To) {
539   InfoEntry Entry = findInfo(From);
540   if (Entry != PropagationMap.end())
541     insertInfo(To, Entry->second);
542 }
543 
544 // Create a new state for To, which is initialized to the state of From.
545 // If NS is not CS_None, sets the state of From to NS.
546 void ConsumedStmtVisitor::copyInfo(const Expr *From, const Expr *To,
547                                    ConsumedState NS) {
548   InfoEntry Entry = findInfo(From);
549   if (Entry != PropagationMap.end()) {
550     PropagationInfo& PInfo = Entry->second;
551     ConsumedState CS = PInfo.getAsState(StateMap);
552     if (CS != CS_None)
553       insertInfo(To, PropagationInfo(CS));
554     if (NS != CS_None && PInfo.isPointerToValue())
555       setStateForVarOrTmp(StateMap, PInfo, NS);
556   }
557 }
558 
559 // Get the ConsumedState for From
560 ConsumedState ConsumedStmtVisitor::getInfo(const Expr *From) {
561   InfoEntry Entry = findInfo(From);
562   if (Entry != PropagationMap.end()) {
563     PropagationInfo& PInfo = Entry->second;
564     return PInfo.getAsState(StateMap);
565   }
566   return CS_None;
567 }
568 
569 // If we already have info for To then update it, otherwise create a new entry.
570 void ConsumedStmtVisitor::setInfo(const Expr *To, ConsumedState NS) {
571   InfoEntry Entry = findInfo(To);
572   if (Entry != PropagationMap.end()) {
573     PropagationInfo& PInfo = Entry->second;
574     if (PInfo.isPointerToValue())
575       setStateForVarOrTmp(StateMap, PInfo, NS);
576   } else if (NS != CS_None) {
577      insertInfo(To, PropagationInfo(NS));
578   }
579 }
580 
581 void ConsumedStmtVisitor::checkCallability(const PropagationInfo &PInfo,
582                                            const FunctionDecl *FunDecl,
583                                            SourceLocation BlameLoc) {
584   assert(!PInfo.isTest());
585 
586   const CallableWhenAttr *CWAttr = FunDecl->getAttr<CallableWhenAttr>();
587   if (!CWAttr)
588     return;
589 
590   if (PInfo.isVar()) {
591     ConsumedState VarState = StateMap->getState(PInfo.getVar());
592 
593     if (VarState == CS_None || isCallableInState(CWAttr, VarState))
594       return;
595 
596     Analyzer.WarningsHandler.warnUseInInvalidState(
597       FunDecl->getNameAsString(), PInfo.getVar()->getNameAsString(),
598       stateToString(VarState), BlameLoc);
599   } else {
600     ConsumedState TmpState = PInfo.getAsState(StateMap);
601 
602     if (TmpState == CS_None || isCallableInState(CWAttr, TmpState))
603       return;
604 
605     Analyzer.WarningsHandler.warnUseOfTempInInvalidState(
606       FunDecl->getNameAsString(), stateToString(TmpState), BlameLoc);
607   }
608 }
609 
610 // Factors out common behavior for function, method, and operator calls.
611 // Check parameters and set parameter state if necessary.
612 // Returns true if the state of ObjArg is set, or false otherwise.
613 bool ConsumedStmtVisitor::handleCall(const Expr *Call,
614                                      const Expr *ObjArg,
615                                      ArgRange Args,
616                                      const FunctionDecl *FunD) {
617   // check explicit parameters
618   unsigned Index = 0;
619   for (const Expr *Arg : Args) {
620     // Skip variable argument lists.
621     if (Index >= FunD->getNumParams())
622       break;
623 
624     const ParmVarDecl *Param = FunD->getParamDecl(Index++);
625     QualType ParamType = Param->getType();
626 
627     InfoEntry Entry = findInfo(Arg);
628 
629     if (Entry == PropagationMap.end() || Entry->second.isTest())
630       continue;
631     PropagationInfo PInfo = Entry->second;
632 
633     // Check that the parameter is in the correct state.
634     if (ParamTypestateAttr *PTA = Param->getAttr<ParamTypestateAttr>()) {
635       ConsumedState ParamState = PInfo.getAsState(StateMap);
636       ConsumedState ExpectedState = mapParamTypestateAttrState(PTA);
637 
638       if (ParamState != ExpectedState)
639         Analyzer.WarningsHandler.warnParamTypestateMismatch(
640           Arg->getExprLoc(),
641           stateToString(ExpectedState), stateToString(ParamState));
642     }
643 
644     if (!(Entry->second.isVar() || Entry->second.isTmp()))
645       continue;
646 
647     // Adjust state on the caller side.
648     if (ReturnTypestateAttr *RT = Param->getAttr<ReturnTypestateAttr>())
649       setStateForVarOrTmp(StateMap, PInfo, mapReturnTypestateAttrState(RT));
650     else if (isRValueRef(ParamType) || isConsumableType(ParamType))
651       setStateForVarOrTmp(StateMap, PInfo, consumed::CS_Consumed);
652     else if (isPointerOrRef(ParamType) &&
653              (!ParamType->getPointeeType().isConstQualified() ||
654               isSetOnReadPtrType(ParamType)))
655       setStateForVarOrTmp(StateMap, PInfo, consumed::CS_Unknown);
656   }
657 
658   if (!ObjArg)
659     return false;
660 
661   // check implicit 'self' parameter, if present
662   InfoEntry Entry = findInfo(ObjArg);
663   if (Entry != PropagationMap.end()) {
664     PropagationInfo PInfo = Entry->second;
665     checkCallability(PInfo, FunD, Call->getExprLoc());
666 
667     if (SetTypestateAttr *STA = FunD->getAttr<SetTypestateAttr>()) {
668       if (PInfo.isVar()) {
669         StateMap->setState(PInfo.getVar(), mapSetTypestateAttrState(STA));
670         return true;
671       }
672       else if (PInfo.isTmp()) {
673         StateMap->setState(PInfo.getTmp(), mapSetTypestateAttrState(STA));
674         return true;
675       }
676     }
677     else if (isTestingFunction(FunD) && PInfo.isVar()) {
678       PropagationMap.insert(PairType(Call,
679         PropagationInfo(PInfo.getVar(), testsFor(FunD))));
680     }
681   }
682   return false;
683 }
684 
685 void ConsumedStmtVisitor::propagateReturnType(const Expr *Call,
686                                               const FunctionDecl *Fun) {
687   QualType RetType = Fun->getCallResultType();
688   if (RetType->isReferenceType())
689     RetType = RetType->getPointeeType();
690 
691   if (isConsumableType(RetType)) {
692     ConsumedState ReturnState;
693     if (ReturnTypestateAttr *RTA = Fun->getAttr<ReturnTypestateAttr>())
694       ReturnState = mapReturnTypestateAttrState(RTA);
695     else
696       ReturnState = mapConsumableAttrState(RetType);
697 
698     PropagationMap.insert(PairType(Call, PropagationInfo(ReturnState)));
699   }
700 }
701 
702 void ConsumedStmtVisitor::VisitBinaryOperator(const BinaryOperator *BinOp) {
703   switch (BinOp->getOpcode()) {
704   case BO_LAnd:
705   case BO_LOr : {
706     InfoEntry LEntry = findInfo(BinOp->getLHS()),
707               REntry = findInfo(BinOp->getRHS());
708 
709     VarTestResult LTest, RTest;
710 
711     if (LEntry != PropagationMap.end() && LEntry->second.isVarTest()) {
712       LTest = LEntry->second.getVarTest();
713     } else {
714       LTest.Var      = nullptr;
715       LTest.TestsFor = CS_None;
716     }
717 
718     if (REntry != PropagationMap.end() && REntry->second.isVarTest()) {
719       RTest = REntry->second.getVarTest();
720     } else {
721       RTest.Var      = nullptr;
722       RTest.TestsFor = CS_None;
723     }
724 
725     if (!(LTest.Var == nullptr && RTest.Var == nullptr))
726       PropagationMap.insert(PairType(BinOp, PropagationInfo(BinOp,
727         static_cast<EffectiveOp>(BinOp->getOpcode() == BO_LOr), LTest, RTest)));
728     break;
729   }
730 
731   case BO_PtrMemD:
732   case BO_PtrMemI:
733     forwardInfo(BinOp->getLHS(), BinOp);
734     break;
735 
736   default:
737     break;
738   }
739 }
740 
741 void ConsumedStmtVisitor::VisitCallExpr(const CallExpr *Call) {
742   const FunctionDecl *FunDecl = Call->getDirectCallee();
743   if (!FunDecl)
744     return;
745 
746   // Special case for the std::move function.
747   // TODO: Make this more specific. (Deferred)
748   if (Call->isCallToStdMove()) {
749     copyInfo(Call->getArg(0), Call, CS_Consumed);
750     return;
751   }
752 
753   handleCall(Call, nullptr, Call->arguments(), FunDecl);
754   propagateReturnType(Call, FunDecl);
755 }
756 
757 void ConsumedStmtVisitor::VisitCastExpr(const CastExpr *Cast) {
758   forwardInfo(Cast->getSubExpr(), Cast);
759 }
760 
761 void ConsumedStmtVisitor::VisitCXXBindTemporaryExpr(
762   const CXXBindTemporaryExpr *Temp) {
763 
764   InfoEntry Entry = findInfo(Temp->getSubExpr());
765 
766   if (Entry != PropagationMap.end() && !Entry->second.isTest()) {
767     StateMap->setState(Temp, Entry->second.getAsState(StateMap));
768     PropagationMap.insert(PairType(Temp, PropagationInfo(Temp)));
769   }
770 }
771 
772 void ConsumedStmtVisitor::VisitCXXConstructExpr(const CXXConstructExpr *Call) {
773   CXXConstructorDecl *Constructor = Call->getConstructor();
774 
775   QualType ThisType = Constructor->getThisType()->getPointeeType();
776 
777   if (!isConsumableType(ThisType))
778     return;
779 
780   // FIXME: What should happen if someone annotates the move constructor?
781   if (ReturnTypestateAttr *RTA = Constructor->getAttr<ReturnTypestateAttr>()) {
782     // TODO: Adjust state of args appropriately.
783     ConsumedState RetState = mapReturnTypestateAttrState(RTA);
784     PropagationMap.insert(PairType(Call, PropagationInfo(RetState)));
785   } else if (Constructor->isDefaultConstructor()) {
786     PropagationMap.insert(PairType(Call,
787       PropagationInfo(consumed::CS_Consumed)));
788   } else if (Constructor->isMoveConstructor()) {
789     copyInfo(Call->getArg(0), Call, CS_Consumed);
790   } else if (Constructor->isCopyConstructor()) {
791     // Copy state from arg.  If setStateOnRead then set arg to CS_Unknown.
792     ConsumedState NS =
793       isSetOnReadPtrType(Constructor->getThisType()) ?
794       CS_Unknown : CS_None;
795     copyInfo(Call->getArg(0), Call, NS);
796   } else {
797     // TODO: Adjust state of args appropriately.
798     ConsumedState RetState = mapConsumableAttrState(ThisType);
799     PropagationMap.insert(PairType(Call, PropagationInfo(RetState)));
800   }
801 }
802 
803 void ConsumedStmtVisitor::VisitCXXMemberCallExpr(
804     const CXXMemberCallExpr *Call) {
805   CXXMethodDecl* MD = Call->getMethodDecl();
806   if (!MD)
807     return;
808 
809   handleCall(Call, Call->getImplicitObjectArgument(), Call->arguments(), MD);
810   propagateReturnType(Call, MD);
811 }
812 
813 void ConsumedStmtVisitor::VisitCXXOperatorCallExpr(
814     const CXXOperatorCallExpr *Call) {
815   const auto *FunDecl = dyn_cast_or_null<FunctionDecl>(Call->getDirectCallee());
816   if (!FunDecl) return;
817   ArgRange Args = Call->arguments();
818 
819   if (Call->getOperator() == OO_Equal) {
820     ConsumedState CS = getInfo(llvm::index(Args, 1));
821     if (!handleCall(Call, llvm::index(Args, 0), llvm::drop_begin(Args, 1),
822                     FunDecl))
823       setInfo(llvm::index(Args, 0), CS);
824     return;
825   }
826 
827   if (isa<CXXMethodDecl>(FunDecl))
828     handleCall(Call, llvm::index(Args, 0), llvm::drop_begin(Args, 1), FunDecl);
829   else
830     handleCall(Call, nullptr, Args, FunDecl);
831 
832   propagateReturnType(Call, FunDecl);
833 }
834 
835 void ConsumedStmtVisitor::VisitDeclRefExpr(const DeclRefExpr *DeclRef) {
836   if (const auto *Var = dyn_cast_or_null<VarDecl>(DeclRef->getDecl()))
837     if (StateMap->getState(Var) != consumed::CS_None)
838       PropagationMap.insert(PairType(DeclRef, PropagationInfo(Var)));
839 }
840 
841 void ConsumedStmtVisitor::VisitDeclStmt(const DeclStmt *DeclS) {
842   for (const auto *DI : DeclS->decls())
843     if (isa<VarDecl>(DI))
844       VisitVarDecl(cast<VarDecl>(DI));
845 
846   if (DeclS->isSingleDecl())
847     if (const auto *Var = dyn_cast_or_null<VarDecl>(DeclS->getSingleDecl()))
848       PropagationMap.insert(PairType(DeclS, PropagationInfo(Var)));
849 }
850 
851 void ConsumedStmtVisitor::VisitMaterializeTemporaryExpr(
852   const MaterializeTemporaryExpr *Temp) {
853   forwardInfo(Temp->GetTemporaryExpr(), Temp);
854 }
855 
856 void ConsumedStmtVisitor::VisitMemberExpr(const MemberExpr *MExpr) {
857   forwardInfo(MExpr->getBase(), MExpr);
858 }
859 
860 void ConsumedStmtVisitor::VisitParmVarDecl(const ParmVarDecl *Param) {
861   QualType ParamType = Param->getType();
862   ConsumedState ParamState = consumed::CS_None;
863 
864   if (const ParamTypestateAttr *PTA = Param->getAttr<ParamTypestateAttr>())
865     ParamState = mapParamTypestateAttrState(PTA);
866   else if (isConsumableType(ParamType))
867     ParamState = mapConsumableAttrState(ParamType);
868   else if (isRValueRef(ParamType) &&
869            isConsumableType(ParamType->getPointeeType()))
870     ParamState = mapConsumableAttrState(ParamType->getPointeeType());
871   else if (ParamType->isReferenceType() &&
872            isConsumableType(ParamType->getPointeeType()))
873     ParamState = consumed::CS_Unknown;
874 
875   if (ParamState != CS_None)
876     StateMap->setState(Param, ParamState);
877 }
878 
879 void ConsumedStmtVisitor::VisitReturnStmt(const ReturnStmt *Ret) {
880   ConsumedState ExpectedState = Analyzer.getExpectedReturnState();
881 
882   if (ExpectedState != CS_None) {
883     InfoEntry Entry = findInfo(Ret->getRetValue());
884 
885     if (Entry != PropagationMap.end()) {
886       ConsumedState RetState = Entry->second.getAsState(StateMap);
887 
888       if (RetState != ExpectedState)
889         Analyzer.WarningsHandler.warnReturnTypestateMismatch(
890           Ret->getReturnLoc(), stateToString(ExpectedState),
891           stateToString(RetState));
892     }
893   }
894 
895   StateMap->checkParamsForReturnTypestate(Ret->getBeginLoc(),
896                                           Analyzer.WarningsHandler);
897 }
898 
899 void ConsumedStmtVisitor::VisitUnaryOperator(const UnaryOperator *UOp) {
900   InfoEntry Entry = findInfo(UOp->getSubExpr());
901   if (Entry == PropagationMap.end()) return;
902 
903   switch (UOp->getOpcode()) {
904   case UO_AddrOf:
905     PropagationMap.insert(PairType(UOp, Entry->second));
906     break;
907 
908   case UO_LNot:
909     if (Entry->second.isTest())
910       PropagationMap.insert(PairType(UOp, Entry->second.invertTest()));
911     break;
912 
913   default:
914     break;
915   }
916 }
917 
918 // TODO: See if I need to check for reference types here.
919 void ConsumedStmtVisitor::VisitVarDecl(const VarDecl *Var) {
920   if (isConsumableType(Var->getType())) {
921     if (Var->hasInit()) {
922       MapType::iterator VIT = findInfo(Var->getInit()->IgnoreImplicit());
923       if (VIT != PropagationMap.end()) {
924         PropagationInfo PInfo = VIT->second;
925         ConsumedState St = PInfo.getAsState(StateMap);
926 
927         if (St != consumed::CS_None) {
928           StateMap->setState(Var, St);
929           return;
930         }
931       }
932     }
933     // Otherwise
934     StateMap->setState(Var, consumed::CS_Unknown);
935   }
936 }
937 
938 static void splitVarStateForIf(const IfStmt *IfNode, const VarTestResult &Test,
939                                ConsumedStateMap *ThenStates,
940                                ConsumedStateMap *ElseStates) {
941   ConsumedState VarState = ThenStates->getState(Test.Var);
942 
943   if (VarState == CS_Unknown) {
944     ThenStates->setState(Test.Var, Test.TestsFor);
945     ElseStates->setState(Test.Var, invertConsumedUnconsumed(Test.TestsFor));
946   } else if (VarState == invertConsumedUnconsumed(Test.TestsFor)) {
947     ThenStates->markUnreachable();
948   } else if (VarState == Test.TestsFor) {
949     ElseStates->markUnreachable();
950   }
951 }
952 
953 static void splitVarStateForIfBinOp(const PropagationInfo &PInfo,
954                                     ConsumedStateMap *ThenStates,
955                                     ConsumedStateMap *ElseStates) {
956   const VarTestResult &LTest = PInfo.getLTest(),
957                       &RTest = PInfo.getRTest();
958 
959   ConsumedState LState = LTest.Var ? ThenStates->getState(LTest.Var) : CS_None,
960                 RState = RTest.Var ? ThenStates->getState(RTest.Var) : CS_None;
961 
962   if (LTest.Var) {
963     if (PInfo.testEffectiveOp() == EO_And) {
964       if (LState == CS_Unknown) {
965         ThenStates->setState(LTest.Var, LTest.TestsFor);
966       } else if (LState == invertConsumedUnconsumed(LTest.TestsFor)) {
967         ThenStates->markUnreachable();
968       } else if (LState == LTest.TestsFor && isKnownState(RState)) {
969         if (RState == RTest.TestsFor)
970           ElseStates->markUnreachable();
971         else
972           ThenStates->markUnreachable();
973       }
974     } else {
975       if (LState == CS_Unknown) {
976         ElseStates->setState(LTest.Var,
977                              invertConsumedUnconsumed(LTest.TestsFor));
978       } else if (LState == LTest.TestsFor) {
979         ElseStates->markUnreachable();
980       } else if (LState == invertConsumedUnconsumed(LTest.TestsFor) &&
981                  isKnownState(RState)) {
982         if (RState == RTest.TestsFor)
983           ElseStates->markUnreachable();
984         else
985           ThenStates->markUnreachable();
986       }
987     }
988   }
989 
990   if (RTest.Var) {
991     if (PInfo.testEffectiveOp() == EO_And) {
992       if (RState == CS_Unknown)
993         ThenStates->setState(RTest.Var, RTest.TestsFor);
994       else if (RState == invertConsumedUnconsumed(RTest.TestsFor))
995         ThenStates->markUnreachable();
996     } else {
997       if (RState == CS_Unknown)
998         ElseStates->setState(RTest.Var,
999                              invertConsumedUnconsumed(RTest.TestsFor));
1000       else if (RState == RTest.TestsFor)
1001         ElseStates->markUnreachable();
1002     }
1003   }
1004 }
1005 
1006 bool ConsumedBlockInfo::allBackEdgesVisited(const CFGBlock *CurrBlock,
1007                                             const CFGBlock *TargetBlock) {
1008   assert(CurrBlock && "Block pointer must not be NULL");
1009   assert(TargetBlock && "TargetBlock pointer must not be NULL");
1010 
1011   unsigned int CurrBlockOrder = VisitOrder[CurrBlock->getBlockID()];
1012   for (CFGBlock::const_pred_iterator PI = TargetBlock->pred_begin(),
1013        PE = TargetBlock->pred_end(); PI != PE; ++PI) {
1014     if (*PI && CurrBlockOrder < VisitOrder[(*PI)->getBlockID()] )
1015       return false;
1016   }
1017   return true;
1018 }
1019 
1020 void ConsumedBlockInfo::addInfo(
1021     const CFGBlock *Block, ConsumedStateMap *StateMap,
1022     std::unique_ptr<ConsumedStateMap> &OwnedStateMap) {
1023   assert(Block && "Block pointer must not be NULL");
1024 
1025   auto &Entry = StateMapsArray[Block->getBlockID()];
1026 
1027   if (Entry) {
1028     Entry->intersect(*StateMap);
1029   } else if (OwnedStateMap)
1030     Entry = std::move(OwnedStateMap);
1031   else
1032     Entry = std::make_unique<ConsumedStateMap>(*StateMap);
1033 }
1034 
1035 void ConsumedBlockInfo::addInfo(const CFGBlock *Block,
1036                                 std::unique_ptr<ConsumedStateMap> StateMap) {
1037   assert(Block && "Block pointer must not be NULL");
1038 
1039   auto &Entry = StateMapsArray[Block->getBlockID()];
1040 
1041   if (Entry) {
1042     Entry->intersect(*StateMap);
1043   } else {
1044     Entry = std::move(StateMap);
1045   }
1046 }
1047 
1048 ConsumedStateMap* ConsumedBlockInfo::borrowInfo(const CFGBlock *Block) {
1049   assert(Block && "Block pointer must not be NULL");
1050   assert(StateMapsArray[Block->getBlockID()] && "Block has no block info");
1051 
1052   return StateMapsArray[Block->getBlockID()].get();
1053 }
1054 
1055 void ConsumedBlockInfo::discardInfo(const CFGBlock *Block) {
1056   StateMapsArray[Block->getBlockID()] = nullptr;
1057 }
1058 
1059 std::unique_ptr<ConsumedStateMap>
1060 ConsumedBlockInfo::getInfo(const CFGBlock *Block) {
1061   assert(Block && "Block pointer must not be NULL");
1062 
1063   auto &Entry = StateMapsArray[Block->getBlockID()];
1064   return isBackEdgeTarget(Block) ? std::make_unique<ConsumedStateMap>(*Entry)
1065                                  : std::move(Entry);
1066 }
1067 
1068 bool ConsumedBlockInfo::isBackEdge(const CFGBlock *From, const CFGBlock *To) {
1069   assert(From && "From block must not be NULL");
1070   assert(To   && "From block must not be NULL");
1071 
1072   return VisitOrder[From->getBlockID()] > VisitOrder[To->getBlockID()];
1073 }
1074 
1075 bool ConsumedBlockInfo::isBackEdgeTarget(const CFGBlock *Block) {
1076   assert(Block && "Block pointer must not be NULL");
1077 
1078   // Anything with less than two predecessors can't be the target of a back
1079   // edge.
1080   if (Block->pred_size() < 2)
1081     return false;
1082 
1083   unsigned int BlockVisitOrder = VisitOrder[Block->getBlockID()];
1084   for (CFGBlock::const_pred_iterator PI = Block->pred_begin(),
1085        PE = Block->pred_end(); PI != PE; ++PI) {
1086     if (*PI && BlockVisitOrder < VisitOrder[(*PI)->getBlockID()])
1087       return true;
1088   }
1089   return false;
1090 }
1091 
1092 void ConsumedStateMap::checkParamsForReturnTypestate(SourceLocation BlameLoc,
1093   ConsumedWarningsHandlerBase &WarningsHandler) const {
1094 
1095   for (const auto &DM : VarMap) {
1096     if (isa<ParmVarDecl>(DM.first)) {
1097       const auto *Param = cast<ParmVarDecl>(DM.first);
1098       const ReturnTypestateAttr *RTA = Param->getAttr<ReturnTypestateAttr>();
1099 
1100       if (!RTA)
1101         continue;
1102 
1103       ConsumedState ExpectedState = mapReturnTypestateAttrState(RTA);
1104       if (DM.second != ExpectedState)
1105         WarningsHandler.warnParamReturnTypestateMismatch(BlameLoc,
1106           Param->getNameAsString(), stateToString(ExpectedState),
1107           stateToString(DM.second));
1108     }
1109   }
1110 }
1111 
1112 void ConsumedStateMap::clearTemporaries() {
1113   TmpMap.clear();
1114 }
1115 
1116 ConsumedState ConsumedStateMap::getState(const VarDecl *Var) const {
1117   VarMapType::const_iterator Entry = VarMap.find(Var);
1118 
1119   if (Entry != VarMap.end())
1120     return Entry->second;
1121 
1122   return CS_None;
1123 }
1124 
1125 ConsumedState
1126 ConsumedStateMap::getState(const CXXBindTemporaryExpr *Tmp) const {
1127   TmpMapType::const_iterator Entry = TmpMap.find(Tmp);
1128 
1129   if (Entry != TmpMap.end())
1130     return Entry->second;
1131 
1132   return CS_None;
1133 }
1134 
1135 void ConsumedStateMap::intersect(const ConsumedStateMap &Other) {
1136   ConsumedState LocalState;
1137 
1138   if (this->From && this->From == Other.From && !Other.Reachable) {
1139     this->markUnreachable();
1140     return;
1141   }
1142 
1143   for (const auto &DM : Other.VarMap) {
1144     LocalState = this->getState(DM.first);
1145 
1146     if (LocalState == CS_None)
1147       continue;
1148 
1149     if (LocalState != DM.second)
1150      VarMap[DM.first] = CS_Unknown;
1151   }
1152 }
1153 
1154 void ConsumedStateMap::intersectAtLoopHead(const CFGBlock *LoopHead,
1155   const CFGBlock *LoopBack, const ConsumedStateMap *LoopBackStates,
1156   ConsumedWarningsHandlerBase &WarningsHandler) {
1157 
1158   ConsumedState LocalState;
1159   SourceLocation BlameLoc = getLastStmtLoc(LoopBack);
1160 
1161   for (const auto &DM : LoopBackStates->VarMap) {
1162     LocalState = this->getState(DM.first);
1163 
1164     if (LocalState == CS_None)
1165       continue;
1166 
1167     if (LocalState != DM.second) {
1168       VarMap[DM.first] = CS_Unknown;
1169       WarningsHandler.warnLoopStateMismatch(BlameLoc,
1170                                             DM.first->getNameAsString());
1171     }
1172   }
1173 }
1174 
1175 void ConsumedStateMap::markUnreachable() {
1176   this->Reachable = false;
1177   VarMap.clear();
1178   TmpMap.clear();
1179 }
1180 
1181 void ConsumedStateMap::setState(const VarDecl *Var, ConsumedState State) {
1182   VarMap[Var] = State;
1183 }
1184 
1185 void ConsumedStateMap::setState(const CXXBindTemporaryExpr *Tmp,
1186                                 ConsumedState State) {
1187   TmpMap[Tmp] = State;
1188 }
1189 
1190 void ConsumedStateMap::remove(const CXXBindTemporaryExpr *Tmp) {
1191   TmpMap.erase(Tmp);
1192 }
1193 
1194 bool ConsumedStateMap::operator!=(const ConsumedStateMap *Other) const {
1195   for (const auto &DM : Other->VarMap)
1196     if (this->getState(DM.first) != DM.second)
1197       return true;
1198   return false;
1199 }
1200 
1201 void ConsumedAnalyzer::determineExpectedReturnState(AnalysisDeclContext &AC,
1202                                                     const FunctionDecl *D) {
1203   QualType ReturnType;
1204   if (const auto *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
1205     ReturnType = Constructor->getThisType()->getPointeeType();
1206   } else
1207     ReturnType = D->getCallResultType();
1208 
1209   if (const ReturnTypestateAttr *RTSAttr = D->getAttr<ReturnTypestateAttr>()) {
1210     const CXXRecordDecl *RD = ReturnType->getAsCXXRecordDecl();
1211     if (!RD || !RD->hasAttr<ConsumableAttr>()) {
1212       // FIXME: This should be removed when template instantiation propagates
1213       //        attributes at template specialization definition, not
1214       //        declaration. When it is removed the test needs to be enabled
1215       //        in SemaDeclAttr.cpp.
1216       WarningsHandler.warnReturnTypestateForUnconsumableType(
1217           RTSAttr->getLocation(), ReturnType.getAsString());
1218       ExpectedReturnState = CS_None;
1219     } else
1220       ExpectedReturnState = mapReturnTypestateAttrState(RTSAttr);
1221   } else if (isConsumableType(ReturnType)) {
1222     if (isAutoCastType(ReturnType))   // We can auto-cast the state to the
1223       ExpectedReturnState = CS_None;  // expected state.
1224     else
1225       ExpectedReturnState = mapConsumableAttrState(ReturnType);
1226   }
1227   else
1228     ExpectedReturnState = CS_None;
1229 }
1230 
1231 bool ConsumedAnalyzer::splitState(const CFGBlock *CurrBlock,
1232                                   const ConsumedStmtVisitor &Visitor) {
1233   std::unique_ptr<ConsumedStateMap> FalseStates(
1234       new ConsumedStateMap(*CurrStates));
1235   PropagationInfo PInfo;
1236 
1237   if (const auto *IfNode =
1238           dyn_cast_or_null<IfStmt>(CurrBlock->getTerminator().getStmt())) {
1239     const Expr *Cond = IfNode->getCond();
1240 
1241     PInfo = Visitor.getInfo(Cond);
1242     if (!PInfo.isValid() && isa<BinaryOperator>(Cond))
1243       PInfo = Visitor.getInfo(cast<BinaryOperator>(Cond)->getRHS());
1244 
1245     if (PInfo.isVarTest()) {
1246       CurrStates->setSource(Cond);
1247       FalseStates->setSource(Cond);
1248       splitVarStateForIf(IfNode, PInfo.getVarTest(), CurrStates.get(),
1249                          FalseStates.get());
1250     } else if (PInfo.isBinTest()) {
1251       CurrStates->setSource(PInfo.testSourceNode());
1252       FalseStates->setSource(PInfo.testSourceNode());
1253       splitVarStateForIfBinOp(PInfo, CurrStates.get(), FalseStates.get());
1254     } else {
1255       return false;
1256     }
1257   } else if (const auto *BinOp =
1258        dyn_cast_or_null<BinaryOperator>(CurrBlock->getTerminator().getStmt())) {
1259     PInfo = Visitor.getInfo(BinOp->getLHS());
1260     if (!PInfo.isVarTest()) {
1261       if ((BinOp = dyn_cast_or_null<BinaryOperator>(BinOp->getLHS()))) {
1262         PInfo = Visitor.getInfo(BinOp->getRHS());
1263 
1264         if (!PInfo.isVarTest())
1265           return false;
1266       } else {
1267         return false;
1268       }
1269     }
1270 
1271     CurrStates->setSource(BinOp);
1272     FalseStates->setSource(BinOp);
1273 
1274     const VarTestResult &Test = PInfo.getVarTest();
1275     ConsumedState VarState = CurrStates->getState(Test.Var);
1276 
1277     if (BinOp->getOpcode() == BO_LAnd) {
1278       if (VarState == CS_Unknown)
1279         CurrStates->setState(Test.Var, Test.TestsFor);
1280       else if (VarState == invertConsumedUnconsumed(Test.TestsFor))
1281         CurrStates->markUnreachable();
1282 
1283     } else if (BinOp->getOpcode() == BO_LOr) {
1284       if (VarState == CS_Unknown)
1285         FalseStates->setState(Test.Var,
1286                               invertConsumedUnconsumed(Test.TestsFor));
1287       else if (VarState == Test.TestsFor)
1288         FalseStates->markUnreachable();
1289     }
1290   } else {
1291     return false;
1292   }
1293 
1294   CFGBlock::const_succ_iterator SI = CurrBlock->succ_begin();
1295 
1296   if (*SI)
1297     BlockInfo.addInfo(*SI, std::move(CurrStates));
1298   else
1299     CurrStates = nullptr;
1300 
1301   if (*++SI)
1302     BlockInfo.addInfo(*SI, std::move(FalseStates));
1303 
1304   return true;
1305 }
1306 
1307 void ConsumedAnalyzer::run(AnalysisDeclContext &AC) {
1308   const auto *D = dyn_cast_or_null<FunctionDecl>(AC.getDecl());
1309   if (!D)
1310     return;
1311 
1312   CFG *CFGraph = AC.getCFG();
1313   if (!CFGraph)
1314     return;
1315 
1316   determineExpectedReturnState(AC, D);
1317 
1318   PostOrderCFGView *SortedGraph = AC.getAnalysis<PostOrderCFGView>();
1319   // AC.getCFG()->viewCFG(LangOptions());
1320 
1321   BlockInfo = ConsumedBlockInfo(CFGraph->getNumBlockIDs(), SortedGraph);
1322 
1323   CurrStates = std::make_unique<ConsumedStateMap>();
1324   ConsumedStmtVisitor Visitor(*this, CurrStates.get());
1325 
1326   // Add all trackable parameters to the state map.
1327   for (const auto *PI : D->parameters())
1328     Visitor.VisitParmVarDecl(PI);
1329 
1330   // Visit all of the function's basic blocks.
1331   for (const auto *CurrBlock : *SortedGraph) {
1332     if (!CurrStates)
1333       CurrStates = BlockInfo.getInfo(CurrBlock);
1334 
1335     if (!CurrStates) {
1336       continue;
1337     } else if (!CurrStates->isReachable()) {
1338       CurrStates = nullptr;
1339       continue;
1340     }
1341 
1342     Visitor.reset(CurrStates.get());
1343 
1344     // Visit all of the basic block's statements.
1345     for (const auto &B : *CurrBlock) {
1346       switch (B.getKind()) {
1347       case CFGElement::Statement:
1348         Visitor.Visit(B.castAs<CFGStmt>().getStmt());
1349         break;
1350 
1351       case CFGElement::TemporaryDtor: {
1352         const CFGTemporaryDtor &DTor = B.castAs<CFGTemporaryDtor>();
1353         const CXXBindTemporaryExpr *BTE = DTor.getBindTemporaryExpr();
1354 
1355         Visitor.checkCallability(PropagationInfo(BTE),
1356                                  DTor.getDestructorDecl(AC.getASTContext()),
1357                                  BTE->getExprLoc());
1358         CurrStates->remove(BTE);
1359         break;
1360       }
1361 
1362       case CFGElement::AutomaticObjectDtor: {
1363         const CFGAutomaticObjDtor &DTor = B.castAs<CFGAutomaticObjDtor>();
1364         SourceLocation Loc = DTor.getTriggerStmt()->getEndLoc();
1365         const VarDecl *Var = DTor.getVarDecl();
1366 
1367         Visitor.checkCallability(PropagationInfo(Var),
1368                                  DTor.getDestructorDecl(AC.getASTContext()),
1369                                  Loc);
1370         break;
1371       }
1372 
1373       default:
1374         break;
1375       }
1376     }
1377 
1378     // TODO: Handle other forms of branching with precision, including while-
1379     //       and for-loops. (Deferred)
1380     if (!splitState(CurrBlock, Visitor)) {
1381       CurrStates->setSource(nullptr);
1382 
1383       if (CurrBlock->succ_size() > 1 ||
1384           (CurrBlock->succ_size() == 1 &&
1385            (*CurrBlock->succ_begin())->pred_size() > 1)) {
1386 
1387         auto *RawState = CurrStates.get();
1388 
1389         for (CFGBlock::const_succ_iterator SI = CurrBlock->succ_begin(),
1390              SE = CurrBlock->succ_end(); SI != SE; ++SI) {
1391           if (*SI == nullptr) continue;
1392 
1393           if (BlockInfo.isBackEdge(CurrBlock, *SI)) {
1394             BlockInfo.borrowInfo(*SI)->intersectAtLoopHead(
1395                 *SI, CurrBlock, RawState, WarningsHandler);
1396 
1397             if (BlockInfo.allBackEdgesVisited(CurrBlock, *SI))
1398               BlockInfo.discardInfo(*SI);
1399           } else {
1400             BlockInfo.addInfo(*SI, RawState, CurrStates);
1401           }
1402         }
1403 
1404         CurrStates = nullptr;
1405       }
1406     }
1407 
1408     if (CurrBlock == &AC.getCFG()->getExit() &&
1409         D->getCallResultType()->isVoidType())
1410       CurrStates->checkParamsForReturnTypestate(D->getLocation(),
1411                                                 WarningsHandler);
1412   } // End of block iterator.
1413 
1414   // Delete the last existing state map.
1415   CurrStates = nullptr;
1416 
1417   WarningsHandler.emitDiagnostics();
1418 }
1419