AnalysisBasedWarnings.cpp 89 KB

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