AnalysisBasedWarnings.cpp 75 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106
  1. //=- AnalysisBasedWarnings.cpp - Sema warnings based on libAnalysis -*- 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. // This file defines analysis_warnings::[Policy,Executor].
  11. // Together they are used by Sema to issue warnings based on inexpensive
  12. // static analysis algorithms in libAnalysis.
  13. //
  14. //===----------------------------------------------------------------------===//
  15. #include "clang/Sema/AnalysisBasedWarnings.h"
  16. #include "clang/AST/DeclCXX.h"
  17. #include "clang/AST/DeclObjC.h"
  18. #include "clang/AST/EvaluatedExprVisitor.h"
  19. #include "clang/AST/ExprCXX.h"
  20. #include "clang/AST/ExprObjC.h"
  21. #include "clang/AST/ParentMap.h"
  22. #include "clang/AST/RecursiveASTVisitor.h"
  23. #include "clang/AST/StmtCXX.h"
  24. #include "clang/AST/StmtObjC.h"
  25. #include "clang/AST/StmtVisitor.h"
  26. #include "clang/Analysis/Analyses/CFGReachabilityAnalysis.h"
  27. #include "clang/Analysis/Analyses/Consumed.h"
  28. #include "clang/Analysis/Analyses/ReachableCode.h"
  29. #include "clang/Analysis/Analyses/ThreadSafety.h"
  30. #include "clang/Analysis/Analyses/UninitializedValues.h"
  31. #include "clang/Analysis/AnalysisContext.h"
  32. #include "clang/Analysis/CFG.h"
  33. #include "clang/Analysis/CFGStmtMap.h"
  34. #include "clang/Basic/SourceLocation.h"
  35. #include "clang/Basic/SourceManager.h"
  36. #include "clang/Lex/Lexer.h"
  37. #include "clang/Lex/Preprocessor.h"
  38. #include "clang/Sema/ScopeInfo.h"
  39. #include "clang/Sema/SemaInternal.h"
  40. #include "llvm/ADT/ArrayRef.h"
  41. #include "llvm/ADT/BitVector.h"
  42. #include "llvm/ADT/FoldingSet.h"
  43. #include "llvm/ADT/ImmutableMap.h"
  44. #include "llvm/ADT/MapVector.h"
  45. #include "llvm/ADT/PostOrderIterator.h"
  46. #include "llvm/ADT/SmallString.h"
  47. #include "llvm/ADT/SmallVector.h"
  48. #include "llvm/ADT/StringRef.h"
  49. #include "llvm/Support/Casting.h"
  50. #include <algorithm>
  51. #include <deque>
  52. #include <iterator>
  53. #include <vector>
  54. using namespace clang;
  55. //===----------------------------------------------------------------------===//
  56. // Unreachable code analysis.
  57. //===----------------------------------------------------------------------===//
  58. namespace {
  59. class UnreachableCodeHandler : public reachable_code::Callback {
  60. Sema &S;
  61. public:
  62. UnreachableCodeHandler(Sema &s) : S(s) {}
  63. void HandleUnreachable(reachable_code::UnreachableKind UK,
  64. SourceLocation L,
  65. SourceRange SilenceableCondVal,
  66. SourceRange R1,
  67. SourceRange R2) override {
  68. unsigned diag = diag::warn_unreachable;
  69. switch (UK) {
  70. case reachable_code::UK_Break:
  71. diag = diag::warn_unreachable_break;
  72. break;
  73. case reachable_code::UK_Return:
  74. diag = diag::warn_unreachable_return;
  75. break;
  76. case reachable_code::UK_Loop_Increment:
  77. diag = diag::warn_unreachable_loop_increment;
  78. break;
  79. case reachable_code::UK_Other:
  80. break;
  81. }
  82. S.Diag(L, diag) << R1 << R2;
  83. SourceLocation Open = SilenceableCondVal.getBegin();
  84. if (Open.isValid()) {
  85. SourceLocation Close = SilenceableCondVal.getEnd();
  86. Close = S.getLocForEndOfToken(Close);
  87. if (Close.isValid()) {
  88. S.Diag(Open, diag::note_unreachable_silence)
  89. << FixItHint::CreateInsertion(Open, "/* DISABLES CODE */ (")
  90. << FixItHint::CreateInsertion(Close, ")");
  91. }
  92. }
  93. }
  94. };
  95. }
  96. /// CheckUnreachable - Check for unreachable code.
  97. static void CheckUnreachable(Sema &S, AnalysisDeclContext &AC) {
  98. // As a heuristic prune all diagnostics not in the main file. Currently
  99. // the majority of warnings in headers are false positives. These
  100. // are largely caused by configuration state, e.g. preprocessor
  101. // defined code, etc.
  102. //
  103. // Note that this is also a performance optimization. Analyzing
  104. // headers many times can be expensive.
  105. if (!S.getSourceManager().isInMainFile(AC.getDecl()->getLocStart()))
  106. return;
  107. UnreachableCodeHandler UC(S);
  108. reachable_code::FindUnreachableCode(AC, S.getPreprocessor(), UC);
  109. }
  110. namespace {
  111. /// \brief Warn on logical operator errors in CFGBuilder
  112. class LogicalErrorHandler : public CFGCallback {
  113. Sema &S;
  114. public:
  115. LogicalErrorHandler(Sema &S) : CFGCallback(), S(S) {}
  116. static bool HasMacroID(const Expr *E) {
  117. if (E->getExprLoc().isMacroID())
  118. return true;
  119. // Recurse to children.
  120. for (const Stmt *SubStmt : E->children())
  121. if (const Expr *SubExpr = dyn_cast_or_null<Expr>(SubStmt))
  122. if (HasMacroID(SubExpr))
  123. return true;
  124. return false;
  125. }
  126. void compareAlwaysTrue(const BinaryOperator *B, bool isAlwaysTrue) override {
  127. if (HasMacroID(B))
  128. return;
  129. SourceRange DiagRange = B->getSourceRange();
  130. S.Diag(B->getExprLoc(), diag::warn_tautological_overlap_comparison)
  131. << DiagRange << isAlwaysTrue;
  132. }
  133. void compareBitwiseEquality(const BinaryOperator *B,
  134. bool isAlwaysTrue) override {
  135. if (HasMacroID(B))
  136. return;
  137. SourceRange DiagRange = B->getSourceRange();
  138. S.Diag(B->getExprLoc(), diag::warn_comparison_bitwise_always)
  139. << DiagRange << isAlwaysTrue;
  140. }
  141. };
  142. } // namespace
  143. //===----------------------------------------------------------------------===//
  144. // Check for infinite self-recursion in functions
  145. //===----------------------------------------------------------------------===//
  146. // All blocks are in one of three states. States are ordered so that blocks
  147. // can only move to higher states.
  148. enum RecursiveState {
  149. FoundNoPath,
  150. FoundPath,
  151. FoundPathWithNoRecursiveCall
  152. };
  153. static void checkForFunctionCall(Sema &S, const FunctionDecl *FD,
  154. CFGBlock &Block, unsigned ExitID,
  155. llvm::SmallVectorImpl<RecursiveState> &States,
  156. RecursiveState State) {
  157. unsigned ID = Block.getBlockID();
  158. // A block's state can only move to a higher state.
  159. if (States[ID] >= State)
  160. return;
  161. States[ID] = State;
  162. // Found a path to the exit node without a recursive call.
  163. if (ID == ExitID && State == FoundPathWithNoRecursiveCall)
  164. return;
  165. if (State == FoundPathWithNoRecursiveCall) {
  166. // If the current state is FoundPathWithNoRecursiveCall, the successors
  167. // will be either FoundPathWithNoRecursiveCall or FoundPath. To determine
  168. // which, process all the Stmt's in this block to find any recursive calls.
  169. for (const auto &B : Block) {
  170. if (B.getKind() != CFGElement::Statement)
  171. continue;
  172. const CallExpr *CE = dyn_cast<CallExpr>(B.getAs<CFGStmt>()->getStmt());
  173. if (CE && CE->getCalleeDecl() &&
  174. CE->getCalleeDecl()->getCanonicalDecl() == FD) {
  175. // Skip function calls which are qualified with a templated class.
  176. if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(
  177. CE->getCallee()->IgnoreParenImpCasts())) {
  178. if (NestedNameSpecifier *NNS = DRE->getQualifier()) {
  179. if (NNS->getKind() == NestedNameSpecifier::TypeSpec &&
  180. isa<TemplateSpecializationType>(NNS->getAsType())) {
  181. continue;
  182. }
  183. }
  184. }
  185. if (const CXXMemberCallExpr *MCE = dyn_cast<CXXMemberCallExpr>(CE)) {
  186. if (isa<CXXThisExpr>(MCE->getImplicitObjectArgument()) ||
  187. !MCE->getMethodDecl()->isVirtual()) {
  188. State = FoundPath;
  189. break;
  190. }
  191. } else {
  192. State = FoundPath;
  193. break;
  194. }
  195. }
  196. }
  197. }
  198. for (CFGBlock::succ_iterator I = Block.succ_begin(), E = Block.succ_end();
  199. I != E; ++I)
  200. if (*I)
  201. checkForFunctionCall(S, FD, **I, ExitID, States, State);
  202. }
  203. static void checkRecursiveFunction(Sema &S, const FunctionDecl *FD,
  204. const Stmt *Body,
  205. AnalysisDeclContext &AC) {
  206. FD = FD->getCanonicalDecl();
  207. // Only run on non-templated functions and non-templated members of
  208. // templated classes.
  209. if (FD->getTemplatedKind() != FunctionDecl::TK_NonTemplate &&
  210. FD->getTemplatedKind() != FunctionDecl::TK_MemberSpecialization)
  211. return;
  212. CFG *cfg = AC.getCFG();
  213. if (!cfg) return;
  214. // If the exit block is unreachable, skip processing the function.
  215. if (cfg->getExit().pred_empty())
  216. return;
  217. // Mark all nodes as FoundNoPath, then begin processing the entry block.
  218. llvm::SmallVector<RecursiveState, 16> states(cfg->getNumBlockIDs(),
  219. FoundNoPath);
  220. checkForFunctionCall(S, FD, cfg->getEntry(), cfg->getExit().getBlockID(),
  221. states, FoundPathWithNoRecursiveCall);
  222. // Check that the exit block is reachable. This prevents triggering the
  223. // warning on functions that do not terminate.
  224. if (states[cfg->getExit().getBlockID()] == FoundPath)
  225. S.Diag(Body->getLocStart(), diag::warn_infinite_recursive_function);
  226. }
  227. //===----------------------------------------------------------------------===//
  228. // Check for missing return value.
  229. //===----------------------------------------------------------------------===//
  230. enum ControlFlowKind {
  231. UnknownFallThrough,
  232. NeverFallThrough,
  233. MaybeFallThrough,
  234. AlwaysFallThrough,
  235. NeverFallThroughOrReturn
  236. };
  237. /// CheckFallThrough - Check that we don't fall off the end of a
  238. /// Statement that should return a value.
  239. ///
  240. /// \returns AlwaysFallThrough iff we always fall off the end of the statement,
  241. /// MaybeFallThrough iff we might or might not fall off the end,
  242. /// NeverFallThroughOrReturn iff we never fall off the end of the statement or
  243. /// return. We assume NeverFallThrough iff we never fall off the end of the
  244. /// statement but we may return. We assume that functions not marked noreturn
  245. /// will return.
  246. static ControlFlowKind CheckFallThrough(AnalysisDeclContext &AC) {
  247. CFG *cfg = AC.getCFG();
  248. if (!cfg) return UnknownFallThrough;
  249. // The CFG leaves in dead things, and we don't want the dead code paths to
  250. // confuse us, so we mark all live things first.
  251. llvm::BitVector live(cfg->getNumBlockIDs());
  252. unsigned count = reachable_code::ScanReachableFromBlock(&cfg->getEntry(),
  253. live);
  254. bool AddEHEdges = AC.getAddEHEdges();
  255. if (!AddEHEdges && count != cfg->getNumBlockIDs())
  256. // When there are things remaining dead, and we didn't add EH edges
  257. // from CallExprs to the catch clauses, we have to go back and
  258. // mark them as live.
  259. for (const auto *B : *cfg) {
  260. if (!live[B->getBlockID()]) {
  261. if (B->pred_begin() == B->pred_end()) {
  262. if (B->getTerminator() && isa<CXXTryStmt>(B->getTerminator()))
  263. // When not adding EH edges from calls, catch clauses
  264. // can otherwise seem dead. Avoid noting them as dead.
  265. count += reachable_code::ScanReachableFromBlock(B, live);
  266. continue;
  267. }
  268. }
  269. }
  270. // Now we know what is live, we check the live precessors of the exit block
  271. // and look for fall through paths, being careful to ignore normal returns,
  272. // and exceptional paths.
  273. bool HasLiveReturn = false;
  274. bool HasFakeEdge = false;
  275. bool HasPlainEdge = false;
  276. bool HasAbnormalEdge = false;
  277. // Ignore default cases that aren't likely to be reachable because all
  278. // enums in a switch(X) have explicit case statements.
  279. CFGBlock::FilterOptions FO;
  280. FO.IgnoreDefaultsWithCoveredEnums = 1;
  281. for (CFGBlock::filtered_pred_iterator
  282. I = cfg->getExit().filtered_pred_start_end(FO); I.hasMore(); ++I) {
  283. const CFGBlock& B = **I;
  284. if (!live[B.getBlockID()])
  285. continue;
  286. // Skip blocks which contain an element marked as no-return. They don't
  287. // represent actually viable edges into the exit block, so mark them as
  288. // abnormal.
  289. if (B.hasNoReturnElement()) {
  290. HasAbnormalEdge = true;
  291. continue;
  292. }
  293. // Destructors can appear after the 'return' in the CFG. This is
  294. // normal. We need to look pass the destructors for the return
  295. // statement (if it exists).
  296. CFGBlock::const_reverse_iterator ri = B.rbegin(), re = B.rend();
  297. for ( ; ri != re ; ++ri)
  298. if (ri->getAs<CFGStmt>())
  299. break;
  300. // No more CFGElements in the block?
  301. if (ri == re) {
  302. if (B.getTerminator() && isa<CXXTryStmt>(B.getTerminator())) {
  303. HasAbnormalEdge = true;
  304. continue;
  305. }
  306. // A labeled empty statement, or the entry block...
  307. HasPlainEdge = true;
  308. continue;
  309. }
  310. CFGStmt CS = ri->castAs<CFGStmt>();
  311. const Stmt *S = CS.getStmt();
  312. if (isa<ReturnStmt>(S)) {
  313. HasLiveReturn = true;
  314. continue;
  315. }
  316. if (isa<ObjCAtThrowStmt>(S)) {
  317. HasFakeEdge = true;
  318. continue;
  319. }
  320. if (isa<CXXThrowExpr>(S)) {
  321. HasFakeEdge = true;
  322. continue;
  323. }
  324. if (isa<MSAsmStmt>(S)) {
  325. // TODO: Verify this is correct.
  326. HasFakeEdge = true;
  327. HasLiveReturn = true;
  328. continue;
  329. }
  330. if (isa<CXXTryStmt>(S)) {
  331. HasAbnormalEdge = true;
  332. continue;
  333. }
  334. if (std::find(B.succ_begin(), B.succ_end(), &cfg->getExit())
  335. == B.succ_end()) {
  336. HasAbnormalEdge = true;
  337. continue;
  338. }
  339. HasPlainEdge = true;
  340. }
  341. if (!HasPlainEdge) {
  342. if (HasLiveReturn)
  343. return NeverFallThrough;
  344. return NeverFallThroughOrReturn;
  345. }
  346. if (HasAbnormalEdge || HasFakeEdge || HasLiveReturn)
  347. return MaybeFallThrough;
  348. // This says AlwaysFallThrough for calls to functions that are not marked
  349. // noreturn, that don't return. If people would like this warning to be more
  350. // accurate, such functions should be marked as noreturn.
  351. return AlwaysFallThrough;
  352. }
  353. namespace {
  354. struct CheckFallThroughDiagnostics {
  355. unsigned diag_MaybeFallThrough_HasNoReturn;
  356. unsigned diag_MaybeFallThrough_ReturnsNonVoid;
  357. unsigned diag_AlwaysFallThrough_HasNoReturn;
  358. unsigned diag_AlwaysFallThrough_ReturnsNonVoid;
  359. unsigned diag_NeverFallThroughOrReturn;
  360. enum { Function, Block, Lambda } funMode;
  361. SourceLocation FuncLoc;
  362. static CheckFallThroughDiagnostics MakeForFunction(const Decl *Func) {
  363. CheckFallThroughDiagnostics D;
  364. D.FuncLoc = Func->getLocation();
  365. D.diag_MaybeFallThrough_HasNoReturn =
  366. diag::warn_falloff_noreturn_function;
  367. D.diag_MaybeFallThrough_ReturnsNonVoid =
  368. diag::warn_maybe_falloff_nonvoid_function;
  369. D.diag_AlwaysFallThrough_HasNoReturn =
  370. diag::warn_falloff_noreturn_function;
  371. D.diag_AlwaysFallThrough_ReturnsNonVoid =
  372. diag::warn_falloff_nonvoid_function;
  373. // Don't suggest that virtual functions be marked "noreturn", since they
  374. // might be overridden by non-noreturn functions.
  375. bool isVirtualMethod = false;
  376. if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Func))
  377. isVirtualMethod = Method->isVirtual();
  378. // Don't suggest that template instantiations be marked "noreturn"
  379. bool isTemplateInstantiation = false;
  380. if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(Func))
  381. isTemplateInstantiation = Function->isTemplateInstantiation();
  382. if (!isVirtualMethod && !isTemplateInstantiation)
  383. D.diag_NeverFallThroughOrReturn =
  384. diag::warn_suggest_noreturn_function;
  385. else
  386. D.diag_NeverFallThroughOrReturn = 0;
  387. D.funMode = Function;
  388. return D;
  389. }
  390. static CheckFallThroughDiagnostics MakeForBlock() {
  391. CheckFallThroughDiagnostics D;
  392. D.diag_MaybeFallThrough_HasNoReturn =
  393. diag::err_noreturn_block_has_return_expr;
  394. D.diag_MaybeFallThrough_ReturnsNonVoid =
  395. diag::err_maybe_falloff_nonvoid_block;
  396. D.diag_AlwaysFallThrough_HasNoReturn =
  397. diag::err_noreturn_block_has_return_expr;
  398. D.diag_AlwaysFallThrough_ReturnsNonVoid =
  399. diag::err_falloff_nonvoid_block;
  400. D.diag_NeverFallThroughOrReturn = 0;
  401. D.funMode = Block;
  402. return D;
  403. }
  404. static CheckFallThroughDiagnostics MakeForLambda() {
  405. CheckFallThroughDiagnostics D;
  406. D.diag_MaybeFallThrough_HasNoReturn =
  407. diag::err_noreturn_lambda_has_return_expr;
  408. D.diag_MaybeFallThrough_ReturnsNonVoid =
  409. diag::warn_maybe_falloff_nonvoid_lambda;
  410. D.diag_AlwaysFallThrough_HasNoReturn =
  411. diag::err_noreturn_lambda_has_return_expr;
  412. D.diag_AlwaysFallThrough_ReturnsNonVoid =
  413. diag::warn_falloff_nonvoid_lambda;
  414. D.diag_NeverFallThroughOrReturn = 0;
  415. D.funMode = Lambda;
  416. return D;
  417. }
  418. bool checkDiagnostics(DiagnosticsEngine &D, bool ReturnsVoid,
  419. bool HasNoReturn) const {
  420. if (funMode == Function) {
  421. return (ReturnsVoid ||
  422. D.isIgnored(diag::warn_maybe_falloff_nonvoid_function,
  423. FuncLoc)) &&
  424. (!HasNoReturn ||
  425. D.isIgnored(diag::warn_noreturn_function_has_return_expr,
  426. FuncLoc)) &&
  427. (!ReturnsVoid ||
  428. D.isIgnored(diag::warn_suggest_noreturn_block, FuncLoc));
  429. }
  430. // For blocks / lambdas.
  431. return ReturnsVoid && !HasNoReturn;
  432. }
  433. };
  434. }
  435. /// CheckFallThroughForFunctionDef - Check that we don't fall off the end of a
  436. /// function that should return a value. Check that we don't fall off the end
  437. /// of a noreturn function. We assume that functions and blocks not marked
  438. /// noreturn will return.
  439. static void CheckFallThroughForBody(Sema &S, const Decl *D, const Stmt *Body,
  440. const BlockExpr *blkExpr,
  441. const CheckFallThroughDiagnostics& CD,
  442. AnalysisDeclContext &AC) {
  443. bool ReturnsVoid = false;
  444. bool HasNoReturn = false;
  445. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  446. ReturnsVoid = FD->getReturnType()->isVoidType();
  447. HasNoReturn = FD->isNoReturn();
  448. }
  449. else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
  450. ReturnsVoid = MD->getReturnType()->isVoidType();
  451. HasNoReturn = MD->hasAttr<NoReturnAttr>();
  452. }
  453. else if (isa<BlockDecl>(D)) {
  454. QualType BlockTy = blkExpr->getType();
  455. if (const FunctionType *FT =
  456. BlockTy->getPointeeType()->getAs<FunctionType>()) {
  457. if (FT->getReturnType()->isVoidType())
  458. ReturnsVoid = true;
  459. if (FT->getNoReturnAttr())
  460. HasNoReturn = true;
  461. }
  462. }
  463. DiagnosticsEngine &Diags = S.getDiagnostics();
  464. // Short circuit for compilation speed.
  465. if (CD.checkDiagnostics(Diags, ReturnsVoid, HasNoReturn))
  466. return;
  467. SourceLocation LBrace = Body->getLocStart(), RBrace = Body->getLocEnd();
  468. // Either in a function body compound statement, or a function-try-block.
  469. switch (CheckFallThrough(AC)) {
  470. case UnknownFallThrough:
  471. break;
  472. case MaybeFallThrough:
  473. if (HasNoReturn)
  474. S.Diag(RBrace, CD.diag_MaybeFallThrough_HasNoReturn);
  475. else if (!ReturnsVoid)
  476. S.Diag(RBrace, CD.diag_MaybeFallThrough_ReturnsNonVoid);
  477. break;
  478. case AlwaysFallThrough:
  479. if (HasNoReturn)
  480. S.Diag(RBrace, CD.diag_AlwaysFallThrough_HasNoReturn);
  481. else if (!ReturnsVoid)
  482. S.Diag(RBrace, CD.diag_AlwaysFallThrough_ReturnsNonVoid);
  483. break;
  484. case NeverFallThroughOrReturn:
  485. if (ReturnsVoid && !HasNoReturn && CD.diag_NeverFallThroughOrReturn) {
  486. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  487. S.Diag(LBrace, CD.diag_NeverFallThroughOrReturn) << 0 << FD;
  488. } else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
  489. S.Diag(LBrace, CD.diag_NeverFallThroughOrReturn) << 1 << MD;
  490. } else {
  491. S.Diag(LBrace, CD.diag_NeverFallThroughOrReturn);
  492. }
  493. }
  494. break;
  495. case NeverFallThrough:
  496. break;
  497. }
  498. }
  499. //===----------------------------------------------------------------------===//
  500. // -Wuninitialized
  501. //===----------------------------------------------------------------------===//
  502. namespace {
  503. /// ContainsReference - A visitor class to search for references to
  504. /// a particular declaration (the needle) within any evaluated component of an
  505. /// expression (recursively).
  506. class ContainsReference : public ConstEvaluatedExprVisitor<ContainsReference> {
  507. bool FoundReference;
  508. const DeclRefExpr *Needle;
  509. public:
  510. typedef ConstEvaluatedExprVisitor<ContainsReference> Inherited;
  511. ContainsReference(ASTContext &Context, const DeclRefExpr *Needle)
  512. : Inherited(Context), FoundReference(false), Needle(Needle) {}
  513. void VisitExpr(const Expr *E) {
  514. // Stop evaluating if we already have a reference.
  515. if (FoundReference)
  516. return;
  517. Inherited::VisitExpr(E);
  518. }
  519. void VisitDeclRefExpr(const DeclRefExpr *E) {
  520. if (E == Needle)
  521. FoundReference = true;
  522. else
  523. Inherited::VisitDeclRefExpr(E);
  524. }
  525. bool doesContainReference() const { return FoundReference; }
  526. };
  527. }
  528. static bool SuggestInitializationFixit(Sema &S, const VarDecl *VD) {
  529. QualType VariableTy = VD->getType().getCanonicalType();
  530. if (VariableTy->isBlockPointerType() &&
  531. !VD->hasAttr<BlocksAttr>()) {
  532. S.Diag(VD->getLocation(), diag::note_block_var_fixit_add_initialization)
  533. << VD->getDeclName()
  534. << FixItHint::CreateInsertion(VD->getLocation(), "__block ");
  535. return true;
  536. }
  537. // Don't issue a fixit if there is already an initializer.
  538. if (VD->getInit())
  539. return false;
  540. // Don't suggest a fixit inside macros.
  541. if (VD->getLocEnd().isMacroID())
  542. return false;
  543. SourceLocation Loc = S.getLocForEndOfToken(VD->getLocEnd());
  544. // Suggest possible initialization (if any).
  545. std::string Init = S.getFixItZeroInitializerForType(VariableTy, Loc);
  546. if (Init.empty())
  547. return false;
  548. S.Diag(Loc, diag::note_var_fixit_add_initialization) << VD->getDeclName()
  549. << FixItHint::CreateInsertion(Loc, Init);
  550. return true;
  551. }
  552. /// Create a fixit to remove an if-like statement, on the assumption that its
  553. /// condition is CondVal.
  554. static void CreateIfFixit(Sema &S, const Stmt *If, const Stmt *Then,
  555. const Stmt *Else, bool CondVal,
  556. FixItHint &Fixit1, FixItHint &Fixit2) {
  557. if (CondVal) {
  558. // If condition is always true, remove all but the 'then'.
  559. Fixit1 = FixItHint::CreateRemoval(
  560. CharSourceRange::getCharRange(If->getLocStart(),
  561. Then->getLocStart()));
  562. if (Else) {
  563. SourceLocation ElseKwLoc = Lexer::getLocForEndOfToken(
  564. Then->getLocEnd(), 0, S.getSourceManager(), S.getLangOpts());
  565. Fixit2 = FixItHint::CreateRemoval(
  566. SourceRange(ElseKwLoc, Else->getLocEnd()));
  567. }
  568. } else {
  569. // If condition is always false, remove all but the 'else'.
  570. if (Else)
  571. Fixit1 = FixItHint::CreateRemoval(
  572. CharSourceRange::getCharRange(If->getLocStart(),
  573. Else->getLocStart()));
  574. else
  575. Fixit1 = FixItHint::CreateRemoval(If->getSourceRange());
  576. }
  577. }
  578. /// DiagUninitUse -- Helper function to produce a diagnostic for an
  579. /// uninitialized use of a variable.
  580. static void DiagUninitUse(Sema &S, const VarDecl *VD, const UninitUse &Use,
  581. bool IsCapturedByBlock) {
  582. bool Diagnosed = false;
  583. switch (Use.getKind()) {
  584. case UninitUse::Always:
  585. S.Diag(Use.getUser()->getLocStart(), diag::warn_uninit_var)
  586. << VD->getDeclName() << IsCapturedByBlock
  587. << Use.getUser()->getSourceRange();
  588. return;
  589. case UninitUse::AfterDecl:
  590. case UninitUse::AfterCall:
  591. S.Diag(VD->getLocation(), diag::warn_sometimes_uninit_var)
  592. << VD->getDeclName() << IsCapturedByBlock
  593. << (Use.getKind() == UninitUse::AfterDecl ? 4 : 5)
  594. << const_cast<DeclContext*>(VD->getLexicalDeclContext())
  595. << VD->getSourceRange();
  596. S.Diag(Use.getUser()->getLocStart(), diag::note_uninit_var_use)
  597. << IsCapturedByBlock << Use.getUser()->getSourceRange();
  598. return;
  599. case UninitUse::Maybe:
  600. case UninitUse::Sometimes:
  601. // Carry on to report sometimes-uninitialized branches, if possible,
  602. // or a 'may be used uninitialized' diagnostic otherwise.
  603. break;
  604. }
  605. // Diagnose each branch which leads to a sometimes-uninitialized use.
  606. for (UninitUse::branch_iterator I = Use.branch_begin(), E = Use.branch_end();
  607. I != E; ++I) {
  608. assert(Use.getKind() == UninitUse::Sometimes);
  609. const Expr *User = Use.getUser();
  610. const Stmt *Term = I->Terminator;
  611. // Information used when building the diagnostic.
  612. unsigned DiagKind;
  613. StringRef Str;
  614. SourceRange Range;
  615. // FixIts to suppress the diagnostic by removing the dead condition.
  616. // For all binary terminators, branch 0 is taken if the condition is true,
  617. // and branch 1 is taken if the condition is false.
  618. int RemoveDiagKind = -1;
  619. const char *FixitStr =
  620. S.getLangOpts().CPlusPlus ? (I->Output ? "true" : "false")
  621. : (I->Output ? "1" : "0");
  622. FixItHint Fixit1, Fixit2;
  623. switch (Term ? Term->getStmtClass() : Stmt::DeclStmtClass) {
  624. default:
  625. // Don't know how to report this. Just fall back to 'may be used
  626. // uninitialized'. FIXME: Can this happen?
  627. continue;
  628. // "condition is true / condition is false".
  629. case Stmt::IfStmtClass: {
  630. const IfStmt *IS = cast<IfStmt>(Term);
  631. DiagKind = 0;
  632. Str = "if";
  633. Range = IS->getCond()->getSourceRange();
  634. RemoveDiagKind = 0;
  635. CreateIfFixit(S, IS, IS->getThen(), IS->getElse(),
  636. I->Output, Fixit1, Fixit2);
  637. break;
  638. }
  639. case Stmt::ConditionalOperatorClass: {
  640. const ConditionalOperator *CO = cast<ConditionalOperator>(Term);
  641. DiagKind = 0;
  642. Str = "?:";
  643. Range = CO->getCond()->getSourceRange();
  644. RemoveDiagKind = 0;
  645. CreateIfFixit(S, CO, CO->getTrueExpr(), CO->getFalseExpr(),
  646. I->Output, Fixit1, Fixit2);
  647. break;
  648. }
  649. case Stmt::BinaryOperatorClass: {
  650. const BinaryOperator *BO = cast<BinaryOperator>(Term);
  651. if (!BO->isLogicalOp())
  652. continue;
  653. DiagKind = 0;
  654. Str = BO->getOpcodeStr();
  655. Range = BO->getLHS()->getSourceRange();
  656. RemoveDiagKind = 0;
  657. if ((BO->getOpcode() == BO_LAnd && I->Output) ||
  658. (BO->getOpcode() == BO_LOr && !I->Output))
  659. // true && y -> y, false || y -> y.
  660. Fixit1 = FixItHint::CreateRemoval(SourceRange(BO->getLocStart(),
  661. BO->getOperatorLoc()));
  662. else
  663. // false && y -> false, true || y -> true.
  664. Fixit1 = FixItHint::CreateReplacement(BO->getSourceRange(), FixitStr);
  665. break;
  666. }
  667. // "loop is entered / loop is exited".
  668. case Stmt::WhileStmtClass:
  669. DiagKind = 1;
  670. Str = "while";
  671. Range = cast<WhileStmt>(Term)->getCond()->getSourceRange();
  672. RemoveDiagKind = 1;
  673. Fixit1 = FixItHint::CreateReplacement(Range, FixitStr);
  674. break;
  675. case Stmt::ForStmtClass:
  676. DiagKind = 1;
  677. Str = "for";
  678. Range = cast<ForStmt>(Term)->getCond()->getSourceRange();
  679. RemoveDiagKind = 1;
  680. if (I->Output)
  681. Fixit1 = FixItHint::CreateRemoval(Range);
  682. else
  683. Fixit1 = FixItHint::CreateReplacement(Range, FixitStr);
  684. break;
  685. case Stmt::CXXForRangeStmtClass:
  686. if (I->Output == 1) {
  687. // The use occurs if a range-based for loop's body never executes.
  688. // That may be impossible, and there's no syntactic fix for this,
  689. // so treat it as a 'may be uninitialized' case.
  690. continue;
  691. }
  692. DiagKind = 1;
  693. Str = "for";
  694. Range = cast<CXXForRangeStmt>(Term)->getRangeInit()->getSourceRange();
  695. break;
  696. // "condition is true / loop is exited".
  697. case Stmt::DoStmtClass:
  698. DiagKind = 2;
  699. Str = "do";
  700. Range = cast<DoStmt>(Term)->getCond()->getSourceRange();
  701. RemoveDiagKind = 1;
  702. Fixit1 = FixItHint::CreateReplacement(Range, FixitStr);
  703. break;
  704. // "switch case is taken".
  705. case Stmt::CaseStmtClass:
  706. DiagKind = 3;
  707. Str = "case";
  708. Range = cast<CaseStmt>(Term)->getLHS()->getSourceRange();
  709. break;
  710. case Stmt::DefaultStmtClass:
  711. DiagKind = 3;
  712. Str = "default";
  713. Range = cast<DefaultStmt>(Term)->getDefaultLoc();
  714. break;
  715. }
  716. S.Diag(Range.getBegin(), diag::warn_sometimes_uninit_var)
  717. << VD->getDeclName() << IsCapturedByBlock << DiagKind
  718. << Str << I->Output << Range;
  719. S.Diag(User->getLocStart(), diag::note_uninit_var_use)
  720. << IsCapturedByBlock << User->getSourceRange();
  721. if (RemoveDiagKind != -1)
  722. S.Diag(Fixit1.RemoveRange.getBegin(), diag::note_uninit_fixit_remove_cond)
  723. << RemoveDiagKind << Str << I->Output << Fixit1 << Fixit2;
  724. Diagnosed = true;
  725. }
  726. if (!Diagnosed)
  727. S.Diag(Use.getUser()->getLocStart(), diag::warn_maybe_uninit_var)
  728. << VD->getDeclName() << IsCapturedByBlock
  729. << Use.getUser()->getSourceRange();
  730. }
  731. /// DiagnoseUninitializedUse -- Helper function for diagnosing uses of an
  732. /// uninitialized variable. This manages the different forms of diagnostic
  733. /// emitted for particular types of uses. Returns true if the use was diagnosed
  734. /// as a warning. If a particular use is one we omit warnings for, returns
  735. /// false.
  736. static bool DiagnoseUninitializedUse(Sema &S, const VarDecl *VD,
  737. const UninitUse &Use,
  738. bool alwaysReportSelfInit = false) {
  739. if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Use.getUser())) {
  740. // Inspect the initializer of the variable declaration which is
  741. // being referenced prior to its initialization. We emit
  742. // specialized diagnostics for self-initialization, and we
  743. // specifically avoid warning about self references which take the
  744. // form of:
  745. //
  746. // int x = x;
  747. //
  748. // This is used to indicate to GCC that 'x' is intentionally left
  749. // uninitialized. Proven code paths which access 'x' in
  750. // an uninitialized state after this will still warn.
  751. if (const Expr *Initializer = VD->getInit()) {
  752. if (!alwaysReportSelfInit && DRE == Initializer->IgnoreParenImpCasts())
  753. return false;
  754. ContainsReference CR(S.Context, DRE);
  755. CR.Visit(Initializer);
  756. if (CR.doesContainReference()) {
  757. S.Diag(DRE->getLocStart(),
  758. diag::warn_uninit_self_reference_in_init)
  759. << VD->getDeclName() << VD->getLocation() << DRE->getSourceRange();
  760. return true;
  761. }
  762. }
  763. DiagUninitUse(S, VD, Use, false);
  764. } else {
  765. const BlockExpr *BE = cast<BlockExpr>(Use.getUser());
  766. if (VD->getType()->isBlockPointerType() && !VD->hasAttr<BlocksAttr>())
  767. S.Diag(BE->getLocStart(),
  768. diag::warn_uninit_byref_blockvar_captured_by_block)
  769. << VD->getDeclName();
  770. else
  771. DiagUninitUse(S, VD, Use, true);
  772. }
  773. // Report where the variable was declared when the use wasn't within
  774. // the initializer of that declaration & we didn't already suggest
  775. // an initialization fixit.
  776. if (!SuggestInitializationFixit(S, VD))
  777. S.Diag(VD->getLocStart(), diag::note_uninit_var_def)
  778. << VD->getDeclName();
  779. return true;
  780. }
  781. namespace {
  782. class FallthroughMapper : public RecursiveASTVisitor<FallthroughMapper> {
  783. public:
  784. FallthroughMapper(Sema &S)
  785. : FoundSwitchStatements(false),
  786. S(S) {
  787. }
  788. bool foundSwitchStatements() const { return FoundSwitchStatements; }
  789. void markFallthroughVisited(const AttributedStmt *Stmt) {
  790. bool Found = FallthroughStmts.erase(Stmt);
  791. assert(Found);
  792. (void)Found;
  793. }
  794. typedef llvm::SmallPtrSet<const AttributedStmt*, 8> AttrStmts;
  795. const AttrStmts &getFallthroughStmts() const {
  796. return FallthroughStmts;
  797. }
  798. void fillReachableBlocks(CFG *Cfg) {
  799. assert(ReachableBlocks.empty() && "ReachableBlocks already filled");
  800. std::deque<const CFGBlock *> BlockQueue;
  801. ReachableBlocks.insert(&Cfg->getEntry());
  802. BlockQueue.push_back(&Cfg->getEntry());
  803. // Mark all case blocks reachable to avoid problems with switching on
  804. // constants, covered enums, etc.
  805. // These blocks can contain fall-through annotations, and we don't want to
  806. // issue a warn_fallthrough_attr_unreachable for them.
  807. for (const auto *B : *Cfg) {
  808. const Stmt *L = B->getLabel();
  809. if (L && isa<SwitchCase>(L) && ReachableBlocks.insert(B).second)
  810. BlockQueue.push_back(B);
  811. }
  812. while (!BlockQueue.empty()) {
  813. const CFGBlock *P = BlockQueue.front();
  814. BlockQueue.pop_front();
  815. for (CFGBlock::const_succ_iterator I = P->succ_begin(),
  816. E = P->succ_end();
  817. I != E; ++I) {
  818. if (*I && ReachableBlocks.insert(*I).second)
  819. BlockQueue.push_back(*I);
  820. }
  821. }
  822. }
  823. bool checkFallThroughIntoBlock(const CFGBlock &B, int &AnnotatedCnt) {
  824. assert(!ReachableBlocks.empty() && "ReachableBlocks empty");
  825. int UnannotatedCnt = 0;
  826. AnnotatedCnt = 0;
  827. std::deque<const CFGBlock*> BlockQueue(B.pred_begin(), B.pred_end());
  828. while (!BlockQueue.empty()) {
  829. const CFGBlock *P = BlockQueue.front();
  830. BlockQueue.pop_front();
  831. if (!P) continue;
  832. const Stmt *Term = P->getTerminator();
  833. if (Term && isa<SwitchStmt>(Term))
  834. continue; // Switch statement, good.
  835. const SwitchCase *SW = dyn_cast_or_null<SwitchCase>(P->getLabel());
  836. if (SW && SW->getSubStmt() == B.getLabel() && P->begin() == P->end())
  837. continue; // Previous case label has no statements, good.
  838. const LabelStmt *L = dyn_cast_or_null<LabelStmt>(P->getLabel());
  839. if (L && L->getSubStmt() == B.getLabel() && P->begin() == P->end())
  840. continue; // Case label is preceded with a normal label, good.
  841. if (!ReachableBlocks.count(P)) {
  842. for (CFGBlock::const_reverse_iterator ElemIt = P->rbegin(),
  843. ElemEnd = P->rend();
  844. ElemIt != ElemEnd; ++ElemIt) {
  845. if (Optional<CFGStmt> CS = ElemIt->getAs<CFGStmt>()) {
  846. if (const AttributedStmt *AS = asFallThroughAttr(CS->getStmt())) {
  847. S.Diag(AS->getLocStart(),
  848. diag::warn_fallthrough_attr_unreachable);
  849. markFallthroughVisited(AS);
  850. ++AnnotatedCnt;
  851. break;
  852. }
  853. // Don't care about other unreachable statements.
  854. }
  855. }
  856. // If there are no unreachable statements, this may be a special
  857. // case in CFG:
  858. // case X: {
  859. // A a; // A has a destructor.
  860. // break;
  861. // }
  862. // // <<<< This place is represented by a 'hanging' CFG block.
  863. // case Y:
  864. continue;
  865. }
  866. const Stmt *LastStmt = getLastStmt(*P);
  867. if (const AttributedStmt *AS = asFallThroughAttr(LastStmt)) {
  868. markFallthroughVisited(AS);
  869. ++AnnotatedCnt;
  870. continue; // Fallthrough annotation, good.
  871. }
  872. if (!LastStmt) { // This block contains no executable statements.
  873. // Traverse its predecessors.
  874. std::copy(P->pred_begin(), P->pred_end(),
  875. std::back_inserter(BlockQueue));
  876. continue;
  877. }
  878. ++UnannotatedCnt;
  879. }
  880. return !!UnannotatedCnt;
  881. }
  882. // RecursiveASTVisitor setup.
  883. bool shouldWalkTypesOfTypeLocs() const { return false; }
  884. bool VisitAttributedStmt(AttributedStmt *S) {
  885. if (asFallThroughAttr(S))
  886. FallthroughStmts.insert(S);
  887. return true;
  888. }
  889. bool VisitSwitchStmt(SwitchStmt *S) {
  890. FoundSwitchStatements = true;
  891. return true;
  892. }
  893. // We don't want to traverse local type declarations. We analyze their
  894. // methods separately.
  895. bool TraverseDecl(Decl *D) { return true; }
  896. // We analyze lambda bodies separately. Skip them here.
  897. bool TraverseLambdaBody(LambdaExpr *LE) { return true; }
  898. private:
  899. static const AttributedStmt *asFallThroughAttr(const Stmt *S) {
  900. if (const AttributedStmt *AS = dyn_cast_or_null<AttributedStmt>(S)) {
  901. if (hasSpecificAttr<FallThroughAttr>(AS->getAttrs()))
  902. return AS;
  903. }
  904. return nullptr;
  905. }
  906. static const Stmt *getLastStmt(const CFGBlock &B) {
  907. if (const Stmt *Term = B.getTerminator())
  908. return Term;
  909. for (CFGBlock::const_reverse_iterator ElemIt = B.rbegin(),
  910. ElemEnd = B.rend();
  911. ElemIt != ElemEnd; ++ElemIt) {
  912. if (Optional<CFGStmt> CS = ElemIt->getAs<CFGStmt>())
  913. return CS->getStmt();
  914. }
  915. // Workaround to detect a statement thrown out by CFGBuilder:
  916. // case X: {} case Y:
  917. // case X: ; case Y:
  918. if (const SwitchCase *SW = dyn_cast_or_null<SwitchCase>(B.getLabel()))
  919. if (!isa<SwitchCase>(SW->getSubStmt()))
  920. return SW->getSubStmt();
  921. return nullptr;
  922. }
  923. bool FoundSwitchStatements;
  924. AttrStmts FallthroughStmts;
  925. Sema &S;
  926. llvm::SmallPtrSet<const CFGBlock *, 16> ReachableBlocks;
  927. };
  928. }
  929. static void DiagnoseSwitchLabelsFallthrough(Sema &S, AnalysisDeclContext &AC,
  930. bool PerFunction) {
  931. // Only perform this analysis when using C++11. There is no good workflow
  932. // for this warning when not using C++11. There is no good way to silence
  933. // the warning (no attribute is available) unless we are using C++11's support
  934. // for generalized attributes. Once could use pragmas to silence the warning,
  935. // but as a general solution that is gross and not in the spirit of this
  936. // warning.
  937. //
  938. // NOTE: This an intermediate solution. There are on-going discussions on
  939. // how to properly support this warning outside of C++11 with an annotation.
  940. if (!AC.getASTContext().getLangOpts().CPlusPlus11)
  941. return;
  942. FallthroughMapper FM(S);
  943. FM.TraverseStmt(AC.getBody());
  944. if (!FM.foundSwitchStatements())
  945. return;
  946. if (PerFunction && FM.getFallthroughStmts().empty())
  947. return;
  948. CFG *Cfg = AC.getCFG();
  949. if (!Cfg)
  950. return;
  951. FM.fillReachableBlocks(Cfg);
  952. for (CFG::reverse_iterator I = Cfg->rbegin(), E = Cfg->rend(); I != E; ++I) {
  953. const CFGBlock *B = *I;
  954. const Stmt *Label = B->getLabel();
  955. if (!Label || !isa<SwitchCase>(Label))
  956. continue;
  957. int AnnotatedCnt;
  958. if (!FM.checkFallThroughIntoBlock(*B, AnnotatedCnt))
  959. continue;
  960. S.Diag(Label->getLocStart(),
  961. PerFunction ? diag::warn_unannotated_fallthrough_per_function
  962. : diag::warn_unannotated_fallthrough);
  963. if (!AnnotatedCnt) {
  964. SourceLocation L = Label->getLocStart();
  965. if (L.isMacroID())
  966. continue;
  967. if (S.getLangOpts().CPlusPlus11) {
  968. const Stmt *Term = B->getTerminator();
  969. // Skip empty cases.
  970. while (B->empty() && !Term && B->succ_size() == 1) {
  971. B = *B->succ_begin();
  972. Term = B->getTerminator();
  973. }
  974. if (!(B->empty() && Term && isa<BreakStmt>(Term))) {
  975. Preprocessor &PP = S.getPreprocessor();
  976. TokenValue Tokens[] = {
  977. tok::l_square, tok::l_square, PP.getIdentifierInfo("clang"),
  978. tok::coloncolon, PP.getIdentifierInfo("fallthrough"),
  979. tok::r_square, tok::r_square
  980. };
  981. StringRef AnnotationSpelling = "[[clang::fallthrough]]";
  982. StringRef MacroName = PP.getLastMacroWithSpelling(L, Tokens);
  983. if (!MacroName.empty())
  984. AnnotationSpelling = MacroName;
  985. SmallString<64> TextToInsert(AnnotationSpelling);
  986. TextToInsert += "; ";
  987. S.Diag(L, diag::note_insert_fallthrough_fixit) <<
  988. AnnotationSpelling <<
  989. FixItHint::CreateInsertion(L, TextToInsert);
  990. }
  991. }
  992. S.Diag(L, diag::note_insert_break_fixit) <<
  993. FixItHint::CreateInsertion(L, "break; ");
  994. }
  995. }
  996. for (const auto *F : FM.getFallthroughStmts())
  997. S.Diag(F->getLocStart(), diag::warn_fallthrough_attr_invalid_placement);
  998. }
  999. static bool isInLoop(const ASTContext &Ctx, const ParentMap &PM,
  1000. const Stmt *S) {
  1001. assert(S);
  1002. do {
  1003. switch (S->getStmtClass()) {
  1004. case Stmt::ForStmtClass:
  1005. case Stmt::WhileStmtClass:
  1006. case Stmt::CXXForRangeStmtClass:
  1007. case Stmt::ObjCForCollectionStmtClass:
  1008. return true;
  1009. case Stmt::DoStmtClass: {
  1010. const Expr *Cond = cast<DoStmt>(S)->getCond();
  1011. llvm::APSInt Val;
  1012. if (!Cond->EvaluateAsInt(Val, Ctx))
  1013. return true;
  1014. return Val.getBoolValue();
  1015. }
  1016. default:
  1017. break;
  1018. }
  1019. } while ((S = PM.getParent(S)));
  1020. return false;
  1021. }
  1022. static void diagnoseRepeatedUseOfWeak(Sema &S,
  1023. const sema::FunctionScopeInfo *CurFn,
  1024. const Decl *D,
  1025. const ParentMap &PM) {
  1026. typedef sema::FunctionScopeInfo::WeakObjectProfileTy WeakObjectProfileTy;
  1027. typedef sema::FunctionScopeInfo::WeakObjectUseMap WeakObjectUseMap;
  1028. typedef sema::FunctionScopeInfo::WeakUseVector WeakUseVector;
  1029. typedef std::pair<const Stmt *, WeakObjectUseMap::const_iterator>
  1030. StmtUsesPair;
  1031. ASTContext &Ctx = S.getASTContext();
  1032. const WeakObjectUseMap &WeakMap = CurFn->getWeakObjectUses();
  1033. // Extract all weak objects that are referenced more than once.
  1034. SmallVector<StmtUsesPair, 8> UsesByStmt;
  1035. for (WeakObjectUseMap::const_iterator I = WeakMap.begin(), E = WeakMap.end();
  1036. I != E; ++I) {
  1037. const WeakUseVector &Uses = I->second;
  1038. // Find the first read of the weak object.
  1039. WeakUseVector::const_iterator UI = Uses.begin(), UE = Uses.end();
  1040. for ( ; UI != UE; ++UI) {
  1041. if (UI->isUnsafe())
  1042. break;
  1043. }
  1044. // If there were only writes to this object, don't warn.
  1045. if (UI == UE)
  1046. continue;
  1047. // If there was only one read, followed by any number of writes, and the
  1048. // read is not within a loop, don't warn. Additionally, don't warn in a
  1049. // loop if the base object is a local variable -- local variables are often
  1050. // changed in loops.
  1051. if (UI == Uses.begin()) {
  1052. WeakUseVector::const_iterator UI2 = UI;
  1053. for (++UI2; UI2 != UE; ++UI2)
  1054. if (UI2->isUnsafe())
  1055. break;
  1056. if (UI2 == UE) {
  1057. if (!isInLoop(Ctx, PM, UI->getUseExpr()))
  1058. continue;
  1059. const WeakObjectProfileTy &Profile = I->first;
  1060. if (!Profile.isExactProfile())
  1061. continue;
  1062. const NamedDecl *Base = Profile.getBase();
  1063. if (!Base)
  1064. Base = Profile.getProperty();
  1065. assert(Base && "A profile always has a base or property.");
  1066. if (const VarDecl *BaseVar = dyn_cast<VarDecl>(Base))
  1067. if (BaseVar->hasLocalStorage() && !isa<ParmVarDecl>(Base))
  1068. continue;
  1069. }
  1070. }
  1071. UsesByStmt.push_back(StmtUsesPair(UI->getUseExpr(), I));
  1072. }
  1073. if (UsesByStmt.empty())
  1074. return;
  1075. // Sort by first use so that we emit the warnings in a deterministic order.
  1076. SourceManager &SM = S.getSourceManager();
  1077. std::sort(UsesByStmt.begin(), UsesByStmt.end(),
  1078. [&SM](const StmtUsesPair &LHS, const StmtUsesPair &RHS) {
  1079. return SM.isBeforeInTranslationUnit(LHS.first->getLocStart(),
  1080. RHS.first->getLocStart());
  1081. });
  1082. // Classify the current code body for better warning text.
  1083. // This enum should stay in sync with the cases in
  1084. // warn_arc_repeated_use_of_weak and warn_arc_possible_repeated_use_of_weak.
  1085. // FIXME: Should we use a common classification enum and the same set of
  1086. // possibilities all throughout Sema?
  1087. enum {
  1088. Function,
  1089. Method,
  1090. Block,
  1091. Lambda
  1092. } FunctionKind;
  1093. if (isa<sema::BlockScopeInfo>(CurFn))
  1094. FunctionKind = Block;
  1095. else if (isa<sema::LambdaScopeInfo>(CurFn))
  1096. FunctionKind = Lambda;
  1097. else if (isa<ObjCMethodDecl>(D))
  1098. FunctionKind = Method;
  1099. else
  1100. FunctionKind = Function;
  1101. // Iterate through the sorted problems and emit warnings for each.
  1102. for (const auto &P : UsesByStmt) {
  1103. const Stmt *FirstRead = P.first;
  1104. const WeakObjectProfileTy &Key = P.second->first;
  1105. const WeakUseVector &Uses = P.second->second;
  1106. // For complicated expressions like 'a.b.c' and 'x.b.c', WeakObjectProfileTy
  1107. // may not contain enough information to determine that these are different
  1108. // properties. We can only be 100% sure of a repeated use in certain cases,
  1109. // and we adjust the diagnostic kind accordingly so that the less certain
  1110. // case can be turned off if it is too noisy.
  1111. unsigned DiagKind;
  1112. if (Key.isExactProfile())
  1113. DiagKind = diag::warn_arc_repeated_use_of_weak;
  1114. else
  1115. DiagKind = diag::warn_arc_possible_repeated_use_of_weak;
  1116. // Classify the weak object being accessed for better warning text.
  1117. // This enum should stay in sync with the cases in
  1118. // warn_arc_repeated_use_of_weak and warn_arc_possible_repeated_use_of_weak.
  1119. enum {
  1120. Variable,
  1121. Property,
  1122. ImplicitProperty,
  1123. Ivar
  1124. } ObjectKind;
  1125. const NamedDecl *D = Key.getProperty();
  1126. if (isa<VarDecl>(D))
  1127. ObjectKind = Variable;
  1128. else if (isa<ObjCPropertyDecl>(D))
  1129. ObjectKind = Property;
  1130. else if (isa<ObjCMethodDecl>(D))
  1131. ObjectKind = ImplicitProperty;
  1132. else if (isa<ObjCIvarDecl>(D))
  1133. ObjectKind = Ivar;
  1134. else
  1135. llvm_unreachable("Unexpected weak object kind!");
  1136. // Show the first time the object was read.
  1137. S.Diag(FirstRead->getLocStart(), DiagKind)
  1138. << int(ObjectKind) << D << int(FunctionKind)
  1139. << FirstRead->getSourceRange();
  1140. // Print all the other accesses as notes.
  1141. for (const auto &Use : Uses) {
  1142. if (Use.getUseExpr() == FirstRead)
  1143. continue;
  1144. S.Diag(Use.getUseExpr()->getLocStart(),
  1145. diag::note_arc_weak_also_accessed_here)
  1146. << Use.getUseExpr()->getSourceRange();
  1147. }
  1148. }
  1149. }
  1150. namespace {
  1151. class UninitValsDiagReporter : public UninitVariablesHandler {
  1152. Sema &S;
  1153. typedef SmallVector<UninitUse, 2> UsesVec;
  1154. typedef llvm::PointerIntPair<UsesVec *, 1, bool> MappedType;
  1155. // Prefer using MapVector to DenseMap, so that iteration order will be
  1156. // the same as insertion order. This is needed to obtain a deterministic
  1157. // order of diagnostics when calling flushDiagnostics().
  1158. typedef llvm::MapVector<const VarDecl *, MappedType> UsesMap;
  1159. UsesMap *uses;
  1160. public:
  1161. UninitValsDiagReporter(Sema &S) : S(S), uses(nullptr) {}
  1162. ~UninitValsDiagReporter() override { flushDiagnostics(); }
  1163. MappedType &getUses(const VarDecl *vd) {
  1164. if (!uses)
  1165. uses = new UsesMap();
  1166. MappedType &V = (*uses)[vd];
  1167. if (!V.getPointer())
  1168. V.setPointer(new UsesVec());
  1169. return V;
  1170. }
  1171. void handleUseOfUninitVariable(const VarDecl *vd,
  1172. const UninitUse &use) override {
  1173. getUses(vd).getPointer()->push_back(use);
  1174. }
  1175. void handleSelfInit(const VarDecl *vd) override {
  1176. getUses(vd).setInt(true);
  1177. }
  1178. void flushDiagnostics() {
  1179. if (!uses)
  1180. return;
  1181. for (const auto &P : *uses) {
  1182. const VarDecl *vd = P.first;
  1183. const MappedType &V = P.second;
  1184. UsesVec *vec = V.getPointer();
  1185. bool hasSelfInit = V.getInt();
  1186. // Specially handle the case where we have uses of an uninitialized
  1187. // variable, but the root cause is an idiomatic self-init. We want
  1188. // to report the diagnostic at the self-init since that is the root cause.
  1189. if (!vec->empty() && hasSelfInit && hasAlwaysUninitializedUse(vec))
  1190. DiagnoseUninitializedUse(S, vd,
  1191. UninitUse(vd->getInit()->IgnoreParenCasts(),
  1192. /* isAlwaysUninit */ true),
  1193. /* alwaysReportSelfInit */ true);
  1194. else {
  1195. // Sort the uses by their SourceLocations. While not strictly
  1196. // guaranteed to produce them in line/column order, this will provide
  1197. // a stable ordering.
  1198. std::sort(vec->begin(), vec->end(),
  1199. [](const UninitUse &a, const UninitUse &b) {
  1200. // Prefer a more confident report over a less confident one.
  1201. if (a.getKind() != b.getKind())
  1202. return a.getKind() > b.getKind();
  1203. return a.getUser()->getLocStart() < b.getUser()->getLocStart();
  1204. });
  1205. for (const auto &U : *vec) {
  1206. // If we have self-init, downgrade all uses to 'may be uninitialized'.
  1207. UninitUse Use = hasSelfInit ? UninitUse(U.getUser(), false) : U;
  1208. if (DiagnoseUninitializedUse(S, vd, Use))
  1209. // Skip further diagnostics for this variable. We try to warn only
  1210. // on the first point at which a variable is used uninitialized.
  1211. break;
  1212. }
  1213. }
  1214. // Release the uses vector.
  1215. delete vec;
  1216. }
  1217. delete uses;
  1218. }
  1219. private:
  1220. static bool hasAlwaysUninitializedUse(const UsesVec* vec) {
  1221. return std::any_of(vec->begin(), vec->end(), [](const UninitUse &U) {
  1222. return U.getKind() == UninitUse::Always ||
  1223. U.getKind() == UninitUse::AfterCall ||
  1224. U.getKind() == UninitUse::AfterDecl;
  1225. });
  1226. }
  1227. };
  1228. }
  1229. namespace clang {
  1230. namespace {
  1231. typedef SmallVector<PartialDiagnosticAt, 1> OptionalNotes;
  1232. typedef std::pair<PartialDiagnosticAt, OptionalNotes> DelayedDiag;
  1233. typedef std::list<DelayedDiag> DiagList;
  1234. struct SortDiagBySourceLocation {
  1235. SourceManager &SM;
  1236. SortDiagBySourceLocation(SourceManager &SM) : SM(SM) {}
  1237. bool operator()(const DelayedDiag &left, const DelayedDiag &right) {
  1238. // Although this call will be slow, this is only called when outputting
  1239. // multiple warnings.
  1240. return SM.isBeforeInTranslationUnit(left.first.first, right.first.first);
  1241. }
  1242. };
  1243. }}
  1244. //===----------------------------------------------------------------------===//
  1245. // -Wthread-safety
  1246. //===----------------------------------------------------------------------===//
  1247. namespace clang {
  1248. namespace threadSafety {
  1249. namespace {
  1250. class ThreadSafetyReporter : public clang::threadSafety::ThreadSafetyHandler {
  1251. Sema &S;
  1252. DiagList Warnings;
  1253. SourceLocation FunLocation, FunEndLocation;
  1254. const FunctionDecl *CurrentFunction;
  1255. bool Verbose;
  1256. OptionalNotes getNotes() const {
  1257. if (Verbose && CurrentFunction) {
  1258. PartialDiagnosticAt FNote(CurrentFunction->getBody()->getLocStart(),
  1259. S.PDiag(diag::note_thread_warning_in_fun)
  1260. << CurrentFunction->getNameAsString());
  1261. return OptionalNotes(1, FNote);
  1262. }
  1263. return OptionalNotes();
  1264. }
  1265. OptionalNotes getNotes(const PartialDiagnosticAt &Note) const {
  1266. OptionalNotes ONS(1, Note);
  1267. if (Verbose && CurrentFunction) {
  1268. PartialDiagnosticAt FNote(CurrentFunction->getBody()->getLocStart(),
  1269. S.PDiag(diag::note_thread_warning_in_fun)
  1270. << CurrentFunction->getNameAsString());
  1271. ONS.push_back(std::move(FNote));
  1272. }
  1273. return ONS;
  1274. }
  1275. OptionalNotes getNotes(const PartialDiagnosticAt &Note1,
  1276. const PartialDiagnosticAt &Note2) const {
  1277. OptionalNotes ONS;
  1278. ONS.push_back(Note1);
  1279. ONS.push_back(Note2);
  1280. if (Verbose && CurrentFunction) {
  1281. PartialDiagnosticAt FNote(CurrentFunction->getBody()->getLocStart(),
  1282. S.PDiag(diag::note_thread_warning_in_fun)
  1283. << CurrentFunction->getNameAsString());
  1284. ONS.push_back(std::move(FNote));
  1285. }
  1286. return ONS;
  1287. }
  1288. // Helper functions
  1289. void warnLockMismatch(unsigned DiagID, StringRef Kind, Name LockName,
  1290. SourceLocation Loc) {
  1291. // Gracefully handle rare cases when the analysis can't get a more
  1292. // precise source location.
  1293. if (!Loc.isValid())
  1294. Loc = FunLocation;
  1295. PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID) << Kind << LockName);
  1296. Warnings.emplace_back(std::move(Warning), getNotes());
  1297. }
  1298. public:
  1299. ThreadSafetyReporter(Sema &S, SourceLocation FL, SourceLocation FEL)
  1300. : S(S), FunLocation(FL), FunEndLocation(FEL),
  1301. CurrentFunction(nullptr), Verbose(false) {}
  1302. void setVerbose(bool b) { Verbose = b; }
  1303. /// \brief Emit all buffered diagnostics in order of sourcelocation.
  1304. /// We need to output diagnostics produced while iterating through
  1305. /// the lockset in deterministic order, so this function orders diagnostics
  1306. /// and outputs them.
  1307. void emitDiagnostics() {
  1308. Warnings.sort(SortDiagBySourceLocation(S.getSourceManager()));
  1309. for (const auto &Diag : Warnings) {
  1310. S.Diag(Diag.first.first, Diag.first.second);
  1311. for (const auto &Note : Diag.second)
  1312. S.Diag(Note.first, Note.second);
  1313. }
  1314. }
  1315. void handleInvalidLockExp(StringRef Kind, SourceLocation Loc) override {
  1316. PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_cannot_resolve_lock)
  1317. << Loc);
  1318. Warnings.emplace_back(std::move(Warning), getNotes());
  1319. }
  1320. void handleUnmatchedUnlock(StringRef Kind, Name LockName,
  1321. SourceLocation Loc) override {
  1322. warnLockMismatch(diag::warn_unlock_but_no_lock, Kind, LockName, Loc);
  1323. }
  1324. void handleIncorrectUnlockKind(StringRef Kind, Name LockName,
  1325. LockKind Expected, LockKind Received,
  1326. SourceLocation Loc) override {
  1327. if (Loc.isInvalid())
  1328. Loc = FunLocation;
  1329. PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_unlock_kind_mismatch)
  1330. << Kind << LockName << Received
  1331. << Expected);
  1332. Warnings.emplace_back(std::move(Warning), getNotes());
  1333. }
  1334. void handleDoubleLock(StringRef Kind, Name LockName, SourceLocation Loc) override {
  1335. warnLockMismatch(diag::warn_double_lock, Kind, LockName, Loc);
  1336. }
  1337. void handleMutexHeldEndOfScope(StringRef Kind, Name LockName,
  1338. SourceLocation LocLocked,
  1339. SourceLocation LocEndOfScope,
  1340. LockErrorKind LEK) override {
  1341. unsigned DiagID = 0;
  1342. switch (LEK) {
  1343. case LEK_LockedSomePredecessors:
  1344. DiagID = diag::warn_lock_some_predecessors;
  1345. break;
  1346. case LEK_LockedSomeLoopIterations:
  1347. DiagID = diag::warn_expecting_lock_held_on_loop;
  1348. break;
  1349. case LEK_LockedAtEndOfFunction:
  1350. DiagID = diag::warn_no_unlock;
  1351. break;
  1352. case LEK_NotLockedAtEndOfFunction:
  1353. DiagID = diag::warn_expecting_locked;
  1354. break;
  1355. }
  1356. if (LocEndOfScope.isInvalid())
  1357. LocEndOfScope = FunEndLocation;
  1358. PartialDiagnosticAt Warning(LocEndOfScope, S.PDiag(DiagID) << Kind
  1359. << LockName);
  1360. if (LocLocked.isValid()) {
  1361. PartialDiagnosticAt Note(LocLocked, S.PDiag(diag::note_locked_here)
  1362. << Kind);
  1363. Warnings.emplace_back(std::move(Warning), getNotes(Note));
  1364. return;
  1365. }
  1366. Warnings.emplace_back(std::move(Warning), getNotes());
  1367. }
  1368. void handleExclusiveAndShared(StringRef Kind, Name LockName,
  1369. SourceLocation Loc1,
  1370. SourceLocation Loc2) override {
  1371. PartialDiagnosticAt Warning(Loc1,
  1372. S.PDiag(diag::warn_lock_exclusive_and_shared)
  1373. << Kind << LockName);
  1374. PartialDiagnosticAt Note(Loc2, S.PDiag(diag::note_lock_exclusive_and_shared)
  1375. << Kind << LockName);
  1376. Warnings.emplace_back(std::move(Warning), getNotes(Note));
  1377. }
  1378. void handleNoMutexHeld(StringRef Kind, const NamedDecl *D,
  1379. ProtectedOperationKind POK, AccessKind AK,
  1380. SourceLocation Loc) override {
  1381. assert((POK == POK_VarAccess || POK == POK_VarDereference) &&
  1382. "Only works for variables");
  1383. unsigned DiagID = POK == POK_VarAccess?
  1384. diag::warn_variable_requires_any_lock:
  1385. diag::warn_var_deref_requires_any_lock;
  1386. PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID)
  1387. << D->getNameAsString() << getLockKindFromAccessKind(AK));
  1388. Warnings.emplace_back(std::move(Warning), getNotes());
  1389. }
  1390. void handleMutexNotHeld(StringRef Kind, const NamedDecl *D,
  1391. ProtectedOperationKind POK, Name LockName,
  1392. LockKind LK, SourceLocation Loc,
  1393. Name *PossibleMatch) override {
  1394. unsigned DiagID = 0;
  1395. if (PossibleMatch) {
  1396. switch (POK) {
  1397. case POK_VarAccess:
  1398. DiagID = diag::warn_variable_requires_lock_precise;
  1399. break;
  1400. case POK_VarDereference:
  1401. DiagID = diag::warn_var_deref_requires_lock_precise;
  1402. break;
  1403. case POK_FunctionCall:
  1404. DiagID = diag::warn_fun_requires_lock_precise;
  1405. break;
  1406. case POK_PassByRef:
  1407. DiagID = diag::warn_guarded_pass_by_reference;
  1408. break;
  1409. case POK_PtPassByRef:
  1410. DiagID = diag::warn_pt_guarded_pass_by_reference;
  1411. break;
  1412. }
  1413. PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID) << Kind
  1414. << D->getNameAsString()
  1415. << LockName << LK);
  1416. PartialDiagnosticAt Note(Loc, S.PDiag(diag::note_found_mutex_near_match)
  1417. << *PossibleMatch);
  1418. if (Verbose && POK == POK_VarAccess) {
  1419. PartialDiagnosticAt VNote(D->getLocation(),
  1420. S.PDiag(diag::note_guarded_by_declared_here)
  1421. << D->getNameAsString());
  1422. Warnings.emplace_back(std::move(Warning), getNotes(Note, VNote));
  1423. } else
  1424. Warnings.emplace_back(std::move(Warning), getNotes(Note));
  1425. } else {
  1426. switch (POK) {
  1427. case POK_VarAccess:
  1428. DiagID = diag::warn_variable_requires_lock;
  1429. break;
  1430. case POK_VarDereference:
  1431. DiagID = diag::warn_var_deref_requires_lock;
  1432. break;
  1433. case POK_FunctionCall:
  1434. DiagID = diag::warn_fun_requires_lock;
  1435. break;
  1436. case POK_PassByRef:
  1437. DiagID = diag::warn_guarded_pass_by_reference;
  1438. break;
  1439. case POK_PtPassByRef:
  1440. DiagID = diag::warn_pt_guarded_pass_by_reference;
  1441. break;
  1442. }
  1443. PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID) << Kind
  1444. << D->getNameAsString()
  1445. << LockName << LK);
  1446. if (Verbose && POK == POK_VarAccess) {
  1447. PartialDiagnosticAt Note(D->getLocation(),
  1448. S.PDiag(diag::note_guarded_by_declared_here)
  1449. << D->getNameAsString());
  1450. Warnings.emplace_back(std::move(Warning), getNotes(Note));
  1451. } else
  1452. Warnings.emplace_back(std::move(Warning), getNotes());
  1453. }
  1454. }
  1455. void handleNegativeNotHeld(StringRef Kind, Name LockName, Name Neg,
  1456. SourceLocation Loc) override {
  1457. PartialDiagnosticAt Warning(Loc,
  1458. S.PDiag(diag::warn_acquire_requires_negative_cap)
  1459. << Kind << LockName << Neg);
  1460. Warnings.emplace_back(std::move(Warning), getNotes());
  1461. }
  1462. void handleFunExcludesLock(StringRef Kind, Name FunName, Name LockName,
  1463. SourceLocation Loc) override {
  1464. PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_fun_excludes_mutex)
  1465. << Kind << FunName << LockName);
  1466. Warnings.emplace_back(std::move(Warning), getNotes());
  1467. }
  1468. void handleLockAcquiredBefore(StringRef Kind, Name L1Name, Name L2Name,
  1469. SourceLocation Loc) override {
  1470. PartialDiagnosticAt Warning(Loc,
  1471. S.PDiag(diag::warn_acquired_before) << Kind << L1Name << L2Name);
  1472. Warnings.emplace_back(std::move(Warning), getNotes());
  1473. }
  1474. void handleBeforeAfterCycle(Name L1Name, SourceLocation Loc) override {
  1475. PartialDiagnosticAt Warning(Loc,
  1476. S.PDiag(diag::warn_acquired_before_after_cycle) << L1Name);
  1477. Warnings.emplace_back(std::move(Warning), getNotes());
  1478. }
  1479. void enterFunction(const FunctionDecl* FD) override {
  1480. CurrentFunction = FD;
  1481. }
  1482. void leaveFunction(const FunctionDecl* FD) override {
  1483. CurrentFunction = 0;
  1484. }
  1485. };
  1486. } // namespace
  1487. } // namespace threadSafety
  1488. } // namespace clang
  1489. //===----------------------------------------------------------------------===//
  1490. // -Wconsumed
  1491. //===----------------------------------------------------------------------===//
  1492. namespace clang {
  1493. namespace consumed {
  1494. namespace {
  1495. class ConsumedWarningsHandler : public ConsumedWarningsHandlerBase {
  1496. Sema &S;
  1497. DiagList Warnings;
  1498. public:
  1499. ConsumedWarningsHandler(Sema &S) : S(S) {}
  1500. void emitDiagnostics() override {
  1501. Warnings.sort(SortDiagBySourceLocation(S.getSourceManager()));
  1502. for (const auto &Diag : Warnings) {
  1503. S.Diag(Diag.first.first, Diag.first.second);
  1504. for (const auto &Note : Diag.second)
  1505. S.Diag(Note.first, Note.second);
  1506. }
  1507. }
  1508. void warnLoopStateMismatch(SourceLocation Loc,
  1509. StringRef VariableName) override {
  1510. PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_loop_state_mismatch) <<
  1511. VariableName);
  1512. Warnings.emplace_back(std::move(Warning), OptionalNotes());
  1513. }
  1514. void warnParamReturnTypestateMismatch(SourceLocation Loc,
  1515. StringRef VariableName,
  1516. StringRef ExpectedState,
  1517. StringRef ObservedState) override {
  1518. PartialDiagnosticAt Warning(Loc, S.PDiag(
  1519. diag::warn_param_return_typestate_mismatch) << VariableName <<
  1520. ExpectedState << ObservedState);
  1521. Warnings.emplace_back(std::move(Warning), OptionalNotes());
  1522. }
  1523. void warnParamTypestateMismatch(SourceLocation Loc, StringRef ExpectedState,
  1524. StringRef ObservedState) override {
  1525. PartialDiagnosticAt Warning(Loc, S.PDiag(
  1526. diag::warn_param_typestate_mismatch) << ExpectedState << ObservedState);
  1527. Warnings.emplace_back(std::move(Warning), OptionalNotes());
  1528. }
  1529. void warnReturnTypestateForUnconsumableType(SourceLocation Loc,
  1530. StringRef TypeName) override {
  1531. PartialDiagnosticAt Warning(Loc, S.PDiag(
  1532. diag::warn_return_typestate_for_unconsumable_type) << TypeName);
  1533. Warnings.emplace_back(std::move(Warning), OptionalNotes());
  1534. }
  1535. void warnReturnTypestateMismatch(SourceLocation Loc, StringRef ExpectedState,
  1536. StringRef ObservedState) override {
  1537. PartialDiagnosticAt Warning(Loc, S.PDiag(
  1538. diag::warn_return_typestate_mismatch) << ExpectedState << ObservedState);
  1539. Warnings.emplace_back(std::move(Warning), OptionalNotes());
  1540. }
  1541. void warnUseOfTempInInvalidState(StringRef MethodName, StringRef State,
  1542. SourceLocation Loc) override {
  1543. PartialDiagnosticAt Warning(Loc, S.PDiag(
  1544. diag::warn_use_of_temp_in_invalid_state) << MethodName << State);
  1545. Warnings.emplace_back(std::move(Warning), OptionalNotes());
  1546. }
  1547. void warnUseInInvalidState(StringRef MethodName, StringRef VariableName,
  1548. StringRef State, SourceLocation Loc) override {
  1549. PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_use_in_invalid_state) <<
  1550. MethodName << VariableName << State);
  1551. Warnings.emplace_back(std::move(Warning), OptionalNotes());
  1552. }
  1553. };
  1554. }}}
  1555. //===----------------------------------------------------------------------===//
  1556. // AnalysisBasedWarnings - Worker object used by Sema to execute analysis-based
  1557. // warnings on a function, method, or block.
  1558. //===----------------------------------------------------------------------===//
  1559. clang::sema::AnalysisBasedWarnings::Policy::Policy() {
  1560. enableCheckFallThrough = 1;
  1561. enableCheckUnreachable = 0;
  1562. enableThreadSafetyAnalysis = 0;
  1563. enableConsumedAnalysis = 0;
  1564. }
  1565. static unsigned isEnabled(DiagnosticsEngine &D, unsigned diag) {
  1566. return (unsigned)!D.isIgnored(diag, SourceLocation());
  1567. }
  1568. clang::sema::AnalysisBasedWarnings::AnalysisBasedWarnings(Sema &s)
  1569. : S(s),
  1570. NumFunctionsAnalyzed(0),
  1571. NumFunctionsWithBadCFGs(0),
  1572. NumCFGBlocks(0),
  1573. MaxCFGBlocksPerFunction(0),
  1574. NumUninitAnalysisFunctions(0),
  1575. NumUninitAnalysisVariables(0),
  1576. MaxUninitAnalysisVariablesPerFunction(0),
  1577. NumUninitAnalysisBlockVisits(0),
  1578. MaxUninitAnalysisBlockVisitsPerFunction(0) {
  1579. using namespace diag;
  1580. DiagnosticsEngine &D = S.getDiagnostics();
  1581. DefaultPolicy.enableCheckUnreachable =
  1582. isEnabled(D, warn_unreachable) ||
  1583. isEnabled(D, warn_unreachable_break) ||
  1584. isEnabled(D, warn_unreachable_return) ||
  1585. isEnabled(D, warn_unreachable_loop_increment);
  1586. DefaultPolicy.enableThreadSafetyAnalysis =
  1587. isEnabled(D, warn_double_lock);
  1588. DefaultPolicy.enableConsumedAnalysis =
  1589. isEnabled(D, warn_use_in_invalid_state);
  1590. }
  1591. static void flushDiagnostics(Sema &S, const sema::FunctionScopeInfo *fscope) {
  1592. for (const auto &D : fscope->PossiblyUnreachableDiags)
  1593. S.Diag(D.Loc, D.PD);
  1594. }
  1595. void clang::sema::
  1596. AnalysisBasedWarnings::IssueWarnings(sema::AnalysisBasedWarnings::Policy P,
  1597. sema::FunctionScopeInfo *fscope,
  1598. const Decl *D, const BlockExpr *blkExpr) {
  1599. // We avoid doing analysis-based warnings when there are errors for
  1600. // two reasons:
  1601. // (1) The CFGs often can't be constructed (if the body is invalid), so
  1602. // don't bother trying.
  1603. // (2) The code already has problems; running the analysis just takes more
  1604. // time.
  1605. DiagnosticsEngine &Diags = S.getDiagnostics();
  1606. // Do not do any analysis for declarations in system headers if we are
  1607. // going to just ignore them.
  1608. if (Diags.getSuppressSystemWarnings() &&
  1609. S.SourceMgr.isInSystemHeader(D->getLocation()))
  1610. return;
  1611. // For code in dependent contexts, we'll do this at instantiation time.
  1612. if (cast<DeclContext>(D)->isDependentContext())
  1613. return;
  1614. if (Diags.hasUncompilableErrorOccurred() || Diags.hasFatalErrorOccurred()) {
  1615. // Flush out any possibly unreachable diagnostics.
  1616. flushDiagnostics(S, fscope);
  1617. return;
  1618. }
  1619. const Stmt *Body = D->getBody();
  1620. assert(Body);
  1621. // Construct the analysis context with the specified CFG build options.
  1622. AnalysisDeclContext AC(/* AnalysisDeclContextManager */ nullptr, D);
  1623. // Don't generate EH edges for CallExprs as we'd like to avoid the n^2
  1624. // explosion for destructors that can result and the compile time hit.
  1625. AC.getCFGBuildOptions().PruneTriviallyFalseEdges = true;
  1626. AC.getCFGBuildOptions().AddEHEdges = false;
  1627. AC.getCFGBuildOptions().AddInitializers = true;
  1628. AC.getCFGBuildOptions().AddImplicitDtors = true;
  1629. AC.getCFGBuildOptions().AddTemporaryDtors = true;
  1630. AC.getCFGBuildOptions().AddCXXNewAllocator = false;
  1631. AC.getCFGBuildOptions().AddCXXDefaultInitExprInCtors = true;
  1632. // Force that certain expressions appear as CFGElements in the CFG. This
  1633. // is used to speed up various analyses.
  1634. // FIXME: This isn't the right factoring. This is here for initial
  1635. // prototyping, but we need a way for analyses to say what expressions they
  1636. // expect to always be CFGElements and then fill in the BuildOptions
  1637. // appropriately. This is essentially a layering violation.
  1638. if (P.enableCheckUnreachable || P.enableThreadSafetyAnalysis ||
  1639. P.enableConsumedAnalysis) {
  1640. // Unreachable code analysis and thread safety require a linearized CFG.
  1641. AC.getCFGBuildOptions().setAllAlwaysAdd();
  1642. }
  1643. else {
  1644. AC.getCFGBuildOptions()
  1645. .setAlwaysAdd(Stmt::BinaryOperatorClass)
  1646. .setAlwaysAdd(Stmt::CompoundAssignOperatorClass)
  1647. .setAlwaysAdd(Stmt::BlockExprClass)
  1648. .setAlwaysAdd(Stmt::CStyleCastExprClass)
  1649. .setAlwaysAdd(Stmt::DeclRefExprClass)
  1650. .setAlwaysAdd(Stmt::ImplicitCastExprClass)
  1651. .setAlwaysAdd(Stmt::UnaryOperatorClass)
  1652. .setAlwaysAdd(Stmt::AttributedStmtClass);
  1653. }
  1654. // Install the logical handler for -Wtautological-overlap-compare
  1655. std::unique_ptr<LogicalErrorHandler> LEH;
  1656. if (!Diags.isIgnored(diag::warn_tautological_overlap_comparison,
  1657. D->getLocStart())) {
  1658. LEH.reset(new LogicalErrorHandler(S));
  1659. AC.getCFGBuildOptions().Observer = LEH.get();
  1660. }
  1661. // Emit delayed diagnostics.
  1662. if (!fscope->PossiblyUnreachableDiags.empty()) {
  1663. bool analyzed = false;
  1664. // Register the expressions with the CFGBuilder.
  1665. for (const auto &D : fscope->PossiblyUnreachableDiags) {
  1666. if (D.stmt)
  1667. AC.registerForcedBlockExpression(D.stmt);
  1668. }
  1669. if (AC.getCFG()) {
  1670. analyzed = true;
  1671. for (const auto &D : fscope->PossiblyUnreachableDiags) {
  1672. bool processed = false;
  1673. if (D.stmt) {
  1674. const CFGBlock *block = AC.getBlockForRegisteredExpression(D.stmt);
  1675. CFGReverseBlockReachabilityAnalysis *cra =
  1676. AC.getCFGReachablityAnalysis();
  1677. // FIXME: We should be able to assert that block is non-null, but
  1678. // the CFG analysis can skip potentially-evaluated expressions in
  1679. // edge cases; see test/Sema/vla-2.c.
  1680. if (block && cra) {
  1681. // Can this block be reached from the entrance?
  1682. if (cra->isReachable(&AC.getCFG()->getEntry(), block))
  1683. S.Diag(D.Loc, D.PD);
  1684. processed = true;
  1685. }
  1686. }
  1687. if (!processed) {
  1688. // Emit the warning anyway if we cannot map to a basic block.
  1689. S.Diag(D.Loc, D.PD);
  1690. }
  1691. }
  1692. }
  1693. if (!analyzed)
  1694. flushDiagnostics(S, fscope);
  1695. }
  1696. // Warning: check missing 'return'
  1697. if (P.enableCheckFallThrough) {
  1698. const CheckFallThroughDiagnostics &CD =
  1699. (isa<BlockDecl>(D) ? CheckFallThroughDiagnostics::MakeForBlock()
  1700. : (isa<CXXMethodDecl>(D) &&
  1701. cast<CXXMethodDecl>(D)->getOverloadedOperator() == OO_Call &&
  1702. cast<CXXMethodDecl>(D)->getParent()->isLambda())
  1703. ? CheckFallThroughDiagnostics::MakeForLambda()
  1704. : CheckFallThroughDiagnostics::MakeForFunction(D));
  1705. CheckFallThroughForBody(S, D, Body, blkExpr, CD, AC);
  1706. }
  1707. // Warning: check for unreachable code
  1708. if (P.enableCheckUnreachable) {
  1709. // Only check for unreachable code on non-template instantiations.
  1710. // Different template instantiations can effectively change the control-flow
  1711. // and it is very difficult to prove that a snippet of code in a template
  1712. // is unreachable for all instantiations.
  1713. bool isTemplateInstantiation = false;
  1714. if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
  1715. isTemplateInstantiation = Function->isTemplateInstantiation();
  1716. if (!isTemplateInstantiation)
  1717. CheckUnreachable(S, AC);
  1718. }
  1719. // Check for thread safety violations
  1720. if (P.enableThreadSafetyAnalysis) {
  1721. SourceLocation FL = AC.getDecl()->getLocation();
  1722. SourceLocation FEL = AC.getDecl()->getLocEnd();
  1723. threadSafety::ThreadSafetyReporter Reporter(S, FL, FEL);
  1724. if (!Diags.isIgnored(diag::warn_thread_safety_beta, D->getLocStart()))
  1725. Reporter.setIssueBetaWarnings(true);
  1726. if (!Diags.isIgnored(diag::warn_thread_safety_verbose, D->getLocStart()))
  1727. Reporter.setVerbose(true);
  1728. threadSafety::runThreadSafetyAnalysis(AC, Reporter,
  1729. &S.ThreadSafetyDeclCache);
  1730. Reporter.emitDiagnostics();
  1731. }
  1732. // Check for violations of consumed properties.
  1733. if (P.enableConsumedAnalysis) {
  1734. consumed::ConsumedWarningsHandler WarningHandler(S);
  1735. consumed::ConsumedAnalyzer Analyzer(WarningHandler);
  1736. Analyzer.run(AC);
  1737. }
  1738. if (!Diags.isIgnored(diag::warn_uninit_var, D->getLocStart()) ||
  1739. !Diags.isIgnored(diag::warn_sometimes_uninit_var, D->getLocStart()) ||
  1740. !Diags.isIgnored(diag::warn_maybe_uninit_var, D->getLocStart())) {
  1741. if (CFG *cfg = AC.getCFG()) {
  1742. UninitValsDiagReporter reporter(S);
  1743. UninitVariablesAnalysisStats stats;
  1744. std::memset(&stats, 0, sizeof(UninitVariablesAnalysisStats));
  1745. runUninitializedVariablesAnalysis(*cast<DeclContext>(D), *cfg, AC,
  1746. reporter, stats);
  1747. if (S.CollectStats && stats.NumVariablesAnalyzed > 0) {
  1748. ++NumUninitAnalysisFunctions;
  1749. NumUninitAnalysisVariables += stats.NumVariablesAnalyzed;
  1750. NumUninitAnalysisBlockVisits += stats.NumBlockVisits;
  1751. MaxUninitAnalysisVariablesPerFunction =
  1752. std::max(MaxUninitAnalysisVariablesPerFunction,
  1753. stats.NumVariablesAnalyzed);
  1754. MaxUninitAnalysisBlockVisitsPerFunction =
  1755. std::max(MaxUninitAnalysisBlockVisitsPerFunction,
  1756. stats.NumBlockVisits);
  1757. }
  1758. }
  1759. }
  1760. bool FallThroughDiagFull =
  1761. !Diags.isIgnored(diag::warn_unannotated_fallthrough, D->getLocStart());
  1762. bool FallThroughDiagPerFunction = !Diags.isIgnored(
  1763. diag::warn_unannotated_fallthrough_per_function, D->getLocStart());
  1764. if (FallThroughDiagFull || FallThroughDiagPerFunction) {
  1765. DiagnoseSwitchLabelsFallthrough(S, AC, !FallThroughDiagFull);
  1766. }
  1767. if (S.getLangOpts().ObjCARCWeak &&
  1768. !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, D->getLocStart()))
  1769. diagnoseRepeatedUseOfWeak(S, fscope, D, AC.getParentMap());
  1770. // Check for infinite self-recursion in functions
  1771. if (!Diags.isIgnored(diag::warn_infinite_recursive_function,
  1772. D->getLocStart())) {
  1773. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  1774. checkRecursiveFunction(S, FD, Body, AC);
  1775. }
  1776. }
  1777. // If none of the previous checks caused a CFG build, trigger one here
  1778. // for -Wtautological-overlap-compare
  1779. if (!Diags.isIgnored(diag::warn_tautological_overlap_comparison,
  1780. D->getLocStart())) {
  1781. AC.getCFG();
  1782. }
  1783. // Collect statistics about the CFG if it was built.
  1784. if (S.CollectStats && AC.isCFGBuilt()) {
  1785. ++NumFunctionsAnalyzed;
  1786. if (CFG *cfg = AC.getCFG()) {
  1787. // If we successfully built a CFG for this context, record some more
  1788. // detail information about it.
  1789. NumCFGBlocks += cfg->getNumBlockIDs();
  1790. MaxCFGBlocksPerFunction = std::max(MaxCFGBlocksPerFunction,
  1791. cfg->getNumBlockIDs());
  1792. } else {
  1793. ++NumFunctionsWithBadCFGs;
  1794. }
  1795. }
  1796. }
  1797. void clang::sema::AnalysisBasedWarnings::PrintStats() const {
  1798. llvm::errs() << "\n*** Analysis Based Warnings Stats:\n";
  1799. unsigned NumCFGsBuilt = NumFunctionsAnalyzed - NumFunctionsWithBadCFGs;
  1800. unsigned AvgCFGBlocksPerFunction =
  1801. !NumCFGsBuilt ? 0 : NumCFGBlocks/NumCFGsBuilt;
  1802. llvm::errs() << NumFunctionsAnalyzed << " functions analyzed ("
  1803. << NumFunctionsWithBadCFGs << " w/o CFGs).\n"
  1804. << " " << NumCFGBlocks << " CFG blocks built.\n"
  1805. << " " << AvgCFGBlocksPerFunction
  1806. << " average CFG blocks per function.\n"
  1807. << " " << MaxCFGBlocksPerFunction
  1808. << " max CFG blocks per function.\n";
  1809. unsigned AvgUninitVariablesPerFunction = !NumUninitAnalysisFunctions ? 0
  1810. : NumUninitAnalysisVariables/NumUninitAnalysisFunctions;
  1811. unsigned AvgUninitBlockVisitsPerFunction = !NumUninitAnalysisFunctions ? 0
  1812. : NumUninitAnalysisBlockVisits/NumUninitAnalysisFunctions;
  1813. llvm::errs() << NumUninitAnalysisFunctions
  1814. << " functions analyzed for uninitialiazed variables\n"
  1815. << " " << NumUninitAnalysisVariables << " variables analyzed.\n"
  1816. << " " << AvgUninitVariablesPerFunction
  1817. << " average variables per function.\n"
  1818. << " " << MaxUninitAnalysisVariablesPerFunction
  1819. << " max variables per function.\n"
  1820. << " " << NumUninitAnalysisBlockVisits << " block visits.\n"
  1821. << " " << AvgUninitBlockVisitsPerFunction
  1822. << " average block visits per function.\n"
  1823. << " " << MaxUninitAnalysisBlockVisitsPerFunction
  1824. << " max block visits per function.\n";
  1825. }