SemaStmt.cpp 162 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365
  1. //===--- SemaStmt.cpp - Semantic Analysis for Statements ------------------===//
  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 implements semantic analysis for statements.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "clang/Sema/SemaInternal.h"
  13. #include "clang/AST/ASTContext.h"
  14. #include "clang/AST/ASTDiagnostic.h"
  15. #include "clang/AST/ASTLambda.h"
  16. #include "clang/AST/CharUnits.h"
  17. #include "clang/AST/CXXInheritance.h"
  18. #include "clang/AST/DeclObjC.h"
  19. #include "clang/AST/EvaluatedExprVisitor.h"
  20. #include "clang/AST/ExprCXX.h"
  21. #include "clang/AST/ExprObjC.h"
  22. #include "clang/AST/RecursiveASTVisitor.h"
  23. #include "clang/AST/StmtCXX.h"
  24. #include "clang/AST/StmtObjC.h"
  25. #include "clang/AST/TypeLoc.h"
  26. #include "clang/AST/TypeOrdering.h"
  27. #include "clang/Basic/TargetInfo.h"
  28. #include "clang/Lex/Preprocessor.h"
  29. #include "clang/Sema/Initialization.h"
  30. #include "clang/Sema/Lookup.h"
  31. #include "clang/Sema/Scope.h"
  32. #include "clang/Sema/ScopeInfo.h"
  33. #include "llvm/ADT/ArrayRef.h"
  34. #include "llvm/ADT/DenseMap.h"
  35. #include "llvm/ADT/STLExtras.h"
  36. #include "llvm/ADT/SmallPtrSet.h"
  37. #include "llvm/ADT/SmallString.h"
  38. #include "llvm/ADT/SmallVector.h"
  39. using namespace clang;
  40. using namespace sema;
  41. StmtResult Sema::ActOnExprStmt(ExprResult FE, bool DiscardedValue) {
  42. if (FE.isInvalid())
  43. return StmtError();
  44. FE = ActOnFinishFullExpr(FE.get(), FE.get()->getExprLoc(), DiscardedValue);
  45. if (FE.isInvalid())
  46. return StmtError();
  47. // C99 6.8.3p2: The expression in an expression statement is evaluated as a
  48. // void expression for its side effects. Conversion to void allows any
  49. // operand, even incomplete types.
  50. // Same thing in for stmt first clause (when expr) and third clause.
  51. return StmtResult(FE.getAs<Stmt>());
  52. }
  53. StmtResult Sema::ActOnExprStmtError() {
  54. DiscardCleanupsInEvaluationContext();
  55. return StmtError();
  56. }
  57. StmtResult Sema::ActOnNullStmt(SourceLocation SemiLoc,
  58. bool HasLeadingEmptyMacro) {
  59. return new (Context) NullStmt(SemiLoc, HasLeadingEmptyMacro);
  60. }
  61. StmtResult Sema::ActOnDeclStmt(DeclGroupPtrTy dg, SourceLocation StartLoc,
  62. SourceLocation EndLoc) {
  63. DeclGroupRef DG = dg.get();
  64. // If we have an invalid decl, just return an error.
  65. if (DG.isNull()) return StmtError();
  66. return new (Context) DeclStmt(DG, StartLoc, EndLoc);
  67. }
  68. void Sema::ActOnForEachDeclStmt(DeclGroupPtrTy dg) {
  69. DeclGroupRef DG = dg.get();
  70. // If we don't have a declaration, or we have an invalid declaration,
  71. // just return.
  72. if (DG.isNull() || !DG.isSingleDecl())
  73. return;
  74. Decl *decl = DG.getSingleDecl();
  75. if (!decl || decl->isInvalidDecl())
  76. return;
  77. // Only variable declarations are permitted.
  78. VarDecl *var = dyn_cast<VarDecl>(decl);
  79. if (!var) {
  80. Diag(decl->getLocation(), diag::err_non_variable_decl_in_for);
  81. decl->setInvalidDecl();
  82. return;
  83. }
  84. // foreach variables are never actually initialized in the way that
  85. // the parser came up with.
  86. var->setInit(nullptr);
  87. // In ARC, we don't need to retain the iteration variable of a fast
  88. // enumeration loop. Rather than actually trying to catch that
  89. // during declaration processing, we remove the consequences here.
  90. if (getLangOpts().ObjCAutoRefCount) {
  91. QualType type = var->getType();
  92. // Only do this if we inferred the lifetime. Inferred lifetime
  93. // will show up as a local qualifier because explicit lifetime
  94. // should have shown up as an AttributedType instead.
  95. if (type.getLocalQualifiers().getObjCLifetime() == Qualifiers::OCL_Strong) {
  96. // Add 'const' and mark the variable as pseudo-strong.
  97. var->setType(type.withConst());
  98. var->setARCPseudoStrong(true);
  99. }
  100. }
  101. }
  102. /// Diagnose unused comparisons, both builtin and overloaded operators.
  103. /// For '==' and '!=', suggest fixits for '=' or '|='.
  104. ///
  105. /// Adding a cast to void (or other expression wrappers) will prevent the
  106. /// warning from firing.
  107. static bool DiagnoseUnusedComparison(Sema &S, const Expr *E) {
  108. SourceLocation Loc;
  109. bool CanAssign;
  110. enum { Equality, Inequality, Relational, ThreeWay } Kind;
  111. if (const BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
  112. if (!Op->isComparisonOp())
  113. return false;
  114. if (Op->getOpcode() == BO_EQ)
  115. Kind = Equality;
  116. else if (Op->getOpcode() == BO_NE)
  117. Kind = Inequality;
  118. else if (Op->getOpcode() == BO_Cmp)
  119. Kind = ThreeWay;
  120. else {
  121. assert(Op->isRelationalOp());
  122. Kind = Relational;
  123. }
  124. Loc = Op->getOperatorLoc();
  125. CanAssign = Op->getLHS()->IgnoreParenImpCasts()->isLValue();
  126. } else if (const CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
  127. switch (Op->getOperator()) {
  128. case OO_EqualEqual:
  129. Kind = Equality;
  130. break;
  131. case OO_ExclaimEqual:
  132. Kind = Inequality;
  133. break;
  134. case OO_Less:
  135. case OO_Greater:
  136. case OO_GreaterEqual:
  137. case OO_LessEqual:
  138. Kind = Relational;
  139. break;
  140. case OO_Spaceship:
  141. Kind = ThreeWay;
  142. break;
  143. default:
  144. return false;
  145. }
  146. Loc = Op->getOperatorLoc();
  147. CanAssign = Op->getArg(0)->IgnoreParenImpCasts()->isLValue();
  148. } else {
  149. // Not a typo-prone comparison.
  150. return false;
  151. }
  152. // Suppress warnings when the operator, suspicious as it may be, comes from
  153. // a macro expansion.
  154. if (S.SourceMgr.isMacroBodyExpansion(Loc))
  155. return false;
  156. S.Diag(Loc, diag::warn_unused_comparison)
  157. << (unsigned)Kind << E->getSourceRange();
  158. // If the LHS is a plausible entity to assign to, provide a fixit hint to
  159. // correct common typos.
  160. if (CanAssign) {
  161. if (Kind == Inequality)
  162. S.Diag(Loc, diag::note_inequality_comparison_to_or_assign)
  163. << FixItHint::CreateReplacement(Loc, "|=");
  164. else if (Kind == Equality)
  165. S.Diag(Loc, diag::note_equality_comparison_to_assign)
  166. << FixItHint::CreateReplacement(Loc, "=");
  167. }
  168. return true;
  169. }
  170. void Sema::DiagnoseUnusedExprResult(const Stmt *S) {
  171. if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
  172. return DiagnoseUnusedExprResult(Label->getSubStmt());
  173. const Expr *E = dyn_cast_or_null<Expr>(S);
  174. if (!E)
  175. return;
  176. // If we are in an unevaluated expression context, then there can be no unused
  177. // results because the results aren't expected to be used in the first place.
  178. if (isUnevaluatedContext())
  179. return;
  180. SourceLocation ExprLoc = E->IgnoreParenImpCasts()->getExprLoc();
  181. // In most cases, we don't want to warn if the expression is written in a
  182. // macro body, or if the macro comes from a system header. If the offending
  183. // expression is a call to a function with the warn_unused_result attribute,
  184. // we warn no matter the location. Because of the order in which the various
  185. // checks need to happen, we factor out the macro-related test here.
  186. bool ShouldSuppress =
  187. SourceMgr.isMacroBodyExpansion(ExprLoc) ||
  188. SourceMgr.isInSystemMacro(ExprLoc);
  189. const Expr *WarnExpr;
  190. SourceLocation Loc;
  191. SourceRange R1, R2;
  192. if (!E->isUnusedResultAWarning(WarnExpr, Loc, R1, R2, Context))
  193. return;
  194. // If this is a GNU statement expression expanded from a macro, it is probably
  195. // unused because it is a function-like macro that can be used as either an
  196. // expression or statement. Don't warn, because it is almost certainly a
  197. // false positive.
  198. if (isa<StmtExpr>(E) && Loc.isMacroID())
  199. return;
  200. // Check if this is the UNREFERENCED_PARAMETER from the Microsoft headers.
  201. // That macro is frequently used to suppress "unused parameter" warnings,
  202. // but its implementation makes clang's -Wunused-value fire. Prevent this.
  203. if (isa<ParenExpr>(E->IgnoreImpCasts()) && Loc.isMacroID()) {
  204. SourceLocation SpellLoc = Loc;
  205. if (findMacroSpelling(SpellLoc, "UNREFERENCED_PARAMETER"))
  206. return;
  207. }
  208. // Okay, we have an unused result. Depending on what the base expression is,
  209. // we might want to make a more specific diagnostic. Check for one of these
  210. // cases now.
  211. unsigned DiagID = diag::warn_unused_expr;
  212. if (const FullExpr *Temps = dyn_cast<FullExpr>(E))
  213. E = Temps->getSubExpr();
  214. if (const CXXBindTemporaryExpr *TempExpr = dyn_cast<CXXBindTemporaryExpr>(E))
  215. E = TempExpr->getSubExpr();
  216. if (DiagnoseUnusedComparison(*this, E))
  217. return;
  218. E = WarnExpr;
  219. if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
  220. if (E->getType()->isVoidType())
  221. return;
  222. if (const Attr *A = CE->getUnusedResultAttr(Context)) {
  223. Diag(Loc, diag::warn_unused_result) << A << R1 << R2;
  224. return;
  225. }
  226. // If the callee has attribute pure, const, or warn_unused_result, warn with
  227. // a more specific message to make it clear what is happening. If the call
  228. // is written in a macro body, only warn if it has the warn_unused_result
  229. // attribute.
  230. if (const Decl *FD = CE->getCalleeDecl()) {
  231. if (ShouldSuppress)
  232. return;
  233. if (FD->hasAttr<PureAttr>()) {
  234. Diag(Loc, diag::warn_unused_call) << R1 << R2 << "pure";
  235. return;
  236. }
  237. if (FD->hasAttr<ConstAttr>()) {
  238. Diag(Loc, diag::warn_unused_call) << R1 << R2 << "const";
  239. return;
  240. }
  241. }
  242. } else if (ShouldSuppress)
  243. return;
  244. if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(E)) {
  245. if (getLangOpts().ObjCAutoRefCount && ME->isDelegateInitCall()) {
  246. Diag(Loc, diag::err_arc_unused_init_message) << R1;
  247. return;
  248. }
  249. const ObjCMethodDecl *MD = ME->getMethodDecl();
  250. if (MD) {
  251. if (const auto *A = MD->getAttr<WarnUnusedResultAttr>()) {
  252. Diag(Loc, diag::warn_unused_result) << A << R1 << R2;
  253. return;
  254. }
  255. }
  256. } else if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
  257. const Expr *Source = POE->getSyntacticForm();
  258. if (isa<ObjCSubscriptRefExpr>(Source))
  259. DiagID = diag::warn_unused_container_subscript_expr;
  260. else
  261. DiagID = diag::warn_unused_property_expr;
  262. } else if (const CXXFunctionalCastExpr *FC
  263. = dyn_cast<CXXFunctionalCastExpr>(E)) {
  264. const Expr *E = FC->getSubExpr();
  265. if (const CXXBindTemporaryExpr *TE = dyn_cast<CXXBindTemporaryExpr>(E))
  266. E = TE->getSubExpr();
  267. if (isa<CXXTemporaryObjectExpr>(E))
  268. return;
  269. if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(E))
  270. if (const CXXRecordDecl *RD = CE->getType()->getAsCXXRecordDecl())
  271. if (!RD->getAttr<WarnUnusedAttr>())
  272. return;
  273. }
  274. // Diagnose "(void*) blah" as a typo for "(void) blah".
  275. else if (const CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(E)) {
  276. TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
  277. QualType T = TI->getType();
  278. // We really do want to use the non-canonical type here.
  279. if (T == Context.VoidPtrTy) {
  280. PointerTypeLoc TL = TI->getTypeLoc().castAs<PointerTypeLoc>();
  281. Diag(Loc, diag::warn_unused_voidptr)
  282. << FixItHint::CreateRemoval(TL.getStarLoc());
  283. return;
  284. }
  285. }
  286. if (E->isGLValue() && E->getType().isVolatileQualified()) {
  287. Diag(Loc, diag::warn_unused_volatile) << R1 << R2;
  288. return;
  289. }
  290. DiagRuntimeBehavior(Loc, nullptr, PDiag(DiagID) << R1 << R2);
  291. }
  292. void Sema::ActOnStartOfCompoundStmt(bool IsStmtExpr) {
  293. PushCompoundScope(IsStmtExpr);
  294. }
  295. void Sema::ActOnFinishOfCompoundStmt() {
  296. PopCompoundScope();
  297. }
  298. sema::CompoundScopeInfo &Sema::getCurCompoundScope() const {
  299. return getCurFunction()->CompoundScopes.back();
  300. }
  301. StmtResult Sema::ActOnCompoundStmt(SourceLocation L, SourceLocation R,
  302. ArrayRef<Stmt *> Elts, bool isStmtExpr) {
  303. const unsigned NumElts = Elts.size();
  304. // If we're in C89 mode, check that we don't have any decls after stmts. If
  305. // so, emit an extension diagnostic.
  306. if (!getLangOpts().C99 && !getLangOpts().CPlusPlus) {
  307. // Note that __extension__ can be around a decl.
  308. unsigned i = 0;
  309. // Skip over all declarations.
  310. for (; i != NumElts && isa<DeclStmt>(Elts[i]); ++i)
  311. /*empty*/;
  312. // We found the end of the list or a statement. Scan for another declstmt.
  313. for (; i != NumElts && !isa<DeclStmt>(Elts[i]); ++i)
  314. /*empty*/;
  315. if (i != NumElts) {
  316. Decl *D = *cast<DeclStmt>(Elts[i])->decl_begin();
  317. Diag(D->getLocation(), diag::ext_mixed_decls_code);
  318. }
  319. }
  320. // Check for suspicious empty body (null statement) in `for' and `while'
  321. // statements. Don't do anything for template instantiations, this just adds
  322. // noise.
  323. if (NumElts != 0 && !CurrentInstantiationScope &&
  324. getCurCompoundScope().HasEmptyLoopBodies) {
  325. for (unsigned i = 0; i != NumElts - 1; ++i)
  326. DiagnoseEmptyLoopBody(Elts[i], Elts[i + 1]);
  327. }
  328. return CompoundStmt::Create(Context, Elts, L, R);
  329. }
  330. ExprResult
  331. Sema::ActOnCaseExpr(SourceLocation CaseLoc, ExprResult Val) {
  332. if (!Val.get())
  333. return Val;
  334. if (DiagnoseUnexpandedParameterPack(Val.get()))
  335. return ExprError();
  336. // If we're not inside a switch, let the 'case' statement handling diagnose
  337. // this. Just clean up after the expression as best we can.
  338. if (!getCurFunction()->SwitchStack.empty()) {
  339. Expr *CondExpr =
  340. getCurFunction()->SwitchStack.back().getPointer()->getCond();
  341. if (!CondExpr)
  342. return ExprError();
  343. QualType CondType = CondExpr->getType();
  344. auto CheckAndFinish = [&](Expr *E) {
  345. if (CondType->isDependentType() || E->isTypeDependent())
  346. return ExprResult(E);
  347. if (getLangOpts().CPlusPlus11) {
  348. // C++11 [stmt.switch]p2: the constant-expression shall be a converted
  349. // constant expression of the promoted type of the switch condition.
  350. llvm::APSInt TempVal;
  351. return CheckConvertedConstantExpression(E, CondType, TempVal,
  352. CCEK_CaseValue);
  353. }
  354. ExprResult ER = E;
  355. if (!E->isValueDependent())
  356. ER = VerifyIntegerConstantExpression(E);
  357. if (!ER.isInvalid())
  358. ER = DefaultLvalueConversion(ER.get());
  359. if (!ER.isInvalid())
  360. ER = ImpCastExprToType(ER.get(), CondType, CK_IntegralCast);
  361. return ER;
  362. };
  363. ExprResult Converted = CorrectDelayedTyposInExpr(Val, CheckAndFinish);
  364. if (Converted.get() == Val.get())
  365. Converted = CheckAndFinish(Val.get());
  366. if (Converted.isInvalid())
  367. return ExprError();
  368. Val = Converted;
  369. }
  370. return ActOnFinishFullExpr(Val.get(), Val.get()->getExprLoc(), false,
  371. getLangOpts().CPlusPlus11);
  372. }
  373. StmtResult
  374. Sema::ActOnCaseStmt(SourceLocation CaseLoc, ExprResult LHSVal,
  375. SourceLocation DotDotDotLoc, ExprResult RHSVal,
  376. SourceLocation ColonLoc) {
  377. assert((LHSVal.isInvalid() || LHSVal.get()) && "missing LHS value");
  378. assert((DotDotDotLoc.isInvalid() ? RHSVal.isUnset()
  379. : RHSVal.isInvalid() || RHSVal.get()) &&
  380. "missing RHS value");
  381. if (getCurFunction()->SwitchStack.empty()) {
  382. Diag(CaseLoc, diag::err_case_not_in_switch);
  383. return StmtError();
  384. }
  385. if (LHSVal.isInvalid() || RHSVal.isInvalid()) {
  386. getCurFunction()->SwitchStack.back().setInt(true);
  387. return StmtError();
  388. }
  389. auto *CS = CaseStmt::Create(Context, LHSVal.get(), RHSVal.get(),
  390. CaseLoc, DotDotDotLoc, ColonLoc);
  391. getCurFunction()->SwitchStack.back().getPointer()->addSwitchCase(CS);
  392. return CS;
  393. }
  394. /// ActOnCaseStmtBody - This installs a statement as the body of a case.
  395. void Sema::ActOnCaseStmtBody(Stmt *S, Stmt *SubStmt) {
  396. cast<CaseStmt>(S)->setSubStmt(SubStmt);
  397. }
  398. StmtResult
  399. Sema::ActOnDefaultStmt(SourceLocation DefaultLoc, SourceLocation ColonLoc,
  400. Stmt *SubStmt, Scope *CurScope) {
  401. if (getCurFunction()->SwitchStack.empty()) {
  402. Diag(DefaultLoc, diag::err_default_not_in_switch);
  403. return SubStmt;
  404. }
  405. DefaultStmt *DS = new (Context) DefaultStmt(DefaultLoc, ColonLoc, SubStmt);
  406. getCurFunction()->SwitchStack.back().getPointer()->addSwitchCase(DS);
  407. return DS;
  408. }
  409. StmtResult
  410. Sema::ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl,
  411. SourceLocation ColonLoc, Stmt *SubStmt) {
  412. // If the label was multiply defined, reject it now.
  413. if (TheDecl->getStmt()) {
  414. Diag(IdentLoc, diag::err_redefinition_of_label) << TheDecl->getDeclName();
  415. Diag(TheDecl->getLocation(), diag::note_previous_definition);
  416. return SubStmt;
  417. }
  418. // Otherwise, things are good. Fill in the declaration and return it.
  419. LabelStmt *LS = new (Context) LabelStmt(IdentLoc, TheDecl, SubStmt);
  420. TheDecl->setStmt(LS);
  421. if (!TheDecl->isGnuLocal()) {
  422. TheDecl->setLocStart(IdentLoc);
  423. if (!TheDecl->isMSAsmLabel()) {
  424. // Don't update the location of MS ASM labels. These will result in
  425. // a diagnostic, and changing the location here will mess that up.
  426. TheDecl->setLocation(IdentLoc);
  427. }
  428. }
  429. return LS;
  430. }
  431. StmtResult Sema::ActOnAttributedStmt(SourceLocation AttrLoc,
  432. ArrayRef<const Attr*> Attrs,
  433. Stmt *SubStmt) {
  434. // Fill in the declaration and return it.
  435. AttributedStmt *LS = AttributedStmt::Create(Context, AttrLoc, Attrs, SubStmt);
  436. return LS;
  437. }
  438. namespace {
  439. class CommaVisitor : public EvaluatedExprVisitor<CommaVisitor> {
  440. typedef EvaluatedExprVisitor<CommaVisitor> Inherited;
  441. Sema &SemaRef;
  442. public:
  443. CommaVisitor(Sema &SemaRef) : Inherited(SemaRef.Context), SemaRef(SemaRef) {}
  444. void VisitBinaryOperator(BinaryOperator *E) {
  445. if (E->getOpcode() == BO_Comma)
  446. SemaRef.DiagnoseCommaOperator(E->getLHS(), E->getExprLoc());
  447. EvaluatedExprVisitor<CommaVisitor>::VisitBinaryOperator(E);
  448. }
  449. };
  450. }
  451. StmtResult
  452. Sema::ActOnIfStmt(SourceLocation IfLoc, bool IsConstexpr, Stmt *InitStmt,
  453. ConditionResult Cond,
  454. Stmt *thenStmt, SourceLocation ElseLoc,
  455. Stmt *elseStmt) {
  456. if (Cond.isInvalid())
  457. Cond = ConditionResult(
  458. *this, nullptr,
  459. MakeFullExpr(new (Context) OpaqueValueExpr(SourceLocation(),
  460. Context.BoolTy, VK_RValue),
  461. IfLoc),
  462. false);
  463. Expr *CondExpr = Cond.get().second;
  464. // Only call the CommaVisitor when not C89 due to differences in scope flags.
  465. if ((getLangOpts().C99 || getLangOpts().CPlusPlus) &&
  466. !Diags.isIgnored(diag::warn_comma_operator, CondExpr->getExprLoc()))
  467. CommaVisitor(*this).Visit(CondExpr);
  468. if (!elseStmt)
  469. DiagnoseEmptyStmtBody(CondExpr->getEndLoc(), thenStmt,
  470. diag::warn_empty_if_body);
  471. return BuildIfStmt(IfLoc, IsConstexpr, InitStmt, Cond, thenStmt, ElseLoc,
  472. elseStmt);
  473. }
  474. StmtResult Sema::BuildIfStmt(SourceLocation IfLoc, bool IsConstexpr,
  475. Stmt *InitStmt, ConditionResult Cond,
  476. Stmt *thenStmt, SourceLocation ElseLoc,
  477. Stmt *elseStmt) {
  478. if (Cond.isInvalid())
  479. return StmtError();
  480. if (IsConstexpr || isa<ObjCAvailabilityCheckExpr>(Cond.get().second))
  481. setFunctionHasBranchProtectedScope();
  482. return IfStmt::Create(Context, IfLoc, IsConstexpr, InitStmt, Cond.get().first,
  483. Cond.get().second, thenStmt, ElseLoc, elseStmt);
  484. }
  485. namespace {
  486. struct CaseCompareFunctor {
  487. bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
  488. const llvm::APSInt &RHS) {
  489. return LHS.first < RHS;
  490. }
  491. bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
  492. const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
  493. return LHS.first < RHS.first;
  494. }
  495. bool operator()(const llvm::APSInt &LHS,
  496. const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
  497. return LHS < RHS.first;
  498. }
  499. };
  500. }
  501. /// CmpCaseVals - Comparison predicate for sorting case values.
  502. ///
  503. static bool CmpCaseVals(const std::pair<llvm::APSInt, CaseStmt*>& lhs,
  504. const std::pair<llvm::APSInt, CaseStmt*>& rhs) {
  505. if (lhs.first < rhs.first)
  506. return true;
  507. if (lhs.first == rhs.first &&
  508. lhs.second->getCaseLoc().getRawEncoding()
  509. < rhs.second->getCaseLoc().getRawEncoding())
  510. return true;
  511. return false;
  512. }
  513. /// CmpEnumVals - Comparison predicate for sorting enumeration values.
  514. ///
  515. static bool CmpEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
  516. const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
  517. {
  518. return lhs.first < rhs.first;
  519. }
  520. /// EqEnumVals - Comparison preficate for uniqing enumeration values.
  521. ///
  522. static bool EqEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
  523. const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
  524. {
  525. return lhs.first == rhs.first;
  526. }
  527. /// GetTypeBeforeIntegralPromotion - Returns the pre-promotion type of
  528. /// potentially integral-promoted expression @p expr.
  529. static QualType GetTypeBeforeIntegralPromotion(const Expr *&E) {
  530. if (const auto *FE = dyn_cast<FullExpr>(E))
  531. E = FE->getSubExpr();
  532. while (const auto *ImpCast = dyn_cast<ImplicitCastExpr>(E)) {
  533. if (ImpCast->getCastKind() != CK_IntegralCast) break;
  534. E = ImpCast->getSubExpr();
  535. }
  536. return E->getType();
  537. }
  538. ExprResult Sema::CheckSwitchCondition(SourceLocation SwitchLoc, Expr *Cond) {
  539. class SwitchConvertDiagnoser : public ICEConvertDiagnoser {
  540. Expr *Cond;
  541. public:
  542. SwitchConvertDiagnoser(Expr *Cond)
  543. : ICEConvertDiagnoser(/*AllowScopedEnumerations*/true, false, true),
  544. Cond(Cond) {}
  545. SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
  546. QualType T) override {
  547. return S.Diag(Loc, diag::err_typecheck_statement_requires_integer) << T;
  548. }
  549. SemaDiagnosticBuilder diagnoseIncomplete(
  550. Sema &S, SourceLocation Loc, QualType T) override {
  551. return S.Diag(Loc, diag::err_switch_incomplete_class_type)
  552. << T << Cond->getSourceRange();
  553. }
  554. SemaDiagnosticBuilder diagnoseExplicitConv(
  555. Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
  556. return S.Diag(Loc, diag::err_switch_explicit_conversion) << T << ConvTy;
  557. }
  558. SemaDiagnosticBuilder noteExplicitConv(
  559. Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
  560. return S.Diag(Conv->getLocation(), diag::note_switch_conversion)
  561. << ConvTy->isEnumeralType() << ConvTy;
  562. }
  563. SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
  564. QualType T) override {
  565. return S.Diag(Loc, diag::err_switch_multiple_conversions) << T;
  566. }
  567. SemaDiagnosticBuilder noteAmbiguous(
  568. Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
  569. return S.Diag(Conv->getLocation(), diag::note_switch_conversion)
  570. << ConvTy->isEnumeralType() << ConvTy;
  571. }
  572. SemaDiagnosticBuilder diagnoseConversion(
  573. Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
  574. llvm_unreachable("conversion functions are permitted");
  575. }
  576. } SwitchDiagnoser(Cond);
  577. ExprResult CondResult =
  578. PerformContextualImplicitConversion(SwitchLoc, Cond, SwitchDiagnoser);
  579. if (CondResult.isInvalid())
  580. return ExprError();
  581. // FIXME: PerformContextualImplicitConversion doesn't always tell us if it
  582. // failed and produced a diagnostic.
  583. Cond = CondResult.get();
  584. if (!Cond->isTypeDependent() &&
  585. !Cond->getType()->isIntegralOrEnumerationType())
  586. return ExprError();
  587. // C99 6.8.4.2p5 - Integer promotions are performed on the controlling expr.
  588. return UsualUnaryConversions(Cond);
  589. }
  590. StmtResult Sema::ActOnStartOfSwitchStmt(SourceLocation SwitchLoc,
  591. Stmt *InitStmt, ConditionResult Cond) {
  592. Expr *CondExpr = Cond.get().second;
  593. assert((Cond.isInvalid() || CondExpr) && "switch with no condition");
  594. if (CondExpr && !CondExpr->isTypeDependent()) {
  595. // We have already converted the expression to an integral or enumeration
  596. // type, when we parsed the switch condition. If we don't have an
  597. // appropriate type now, enter the switch scope but remember that it's
  598. // invalid.
  599. assert(CondExpr->getType()->isIntegralOrEnumerationType() &&
  600. "invalid condition type");
  601. if (CondExpr->isKnownToHaveBooleanValue()) {
  602. // switch(bool_expr) {...} is often a programmer error, e.g.
  603. // switch(n && mask) { ... } // Doh - should be "n & mask".
  604. // One can always use an if statement instead of switch(bool_expr).
  605. Diag(SwitchLoc, diag::warn_bool_switch_condition)
  606. << CondExpr->getSourceRange();
  607. }
  608. }
  609. setFunctionHasBranchIntoScope();
  610. auto *SS = SwitchStmt::Create(Context, InitStmt, Cond.get().first, CondExpr);
  611. getCurFunction()->SwitchStack.push_back(
  612. FunctionScopeInfo::SwitchInfo(SS, false));
  613. return SS;
  614. }
  615. static void AdjustAPSInt(llvm::APSInt &Val, unsigned BitWidth, bool IsSigned) {
  616. Val = Val.extOrTrunc(BitWidth);
  617. Val.setIsSigned(IsSigned);
  618. }
  619. /// Check the specified case value is in range for the given unpromoted switch
  620. /// type.
  621. static void checkCaseValue(Sema &S, SourceLocation Loc, const llvm::APSInt &Val,
  622. unsigned UnpromotedWidth, bool UnpromotedSign) {
  623. // In C++11 onwards, this is checked by the language rules.
  624. if (S.getLangOpts().CPlusPlus11)
  625. return;
  626. // If the case value was signed and negative and the switch expression is
  627. // unsigned, don't bother to warn: this is implementation-defined behavior.
  628. // FIXME: Introduce a second, default-ignored warning for this case?
  629. if (UnpromotedWidth < Val.getBitWidth()) {
  630. llvm::APSInt ConvVal(Val);
  631. AdjustAPSInt(ConvVal, UnpromotedWidth, UnpromotedSign);
  632. AdjustAPSInt(ConvVal, Val.getBitWidth(), Val.isSigned());
  633. // FIXME: Use different diagnostics for overflow in conversion to promoted
  634. // type versus "switch expression cannot have this value". Use proper
  635. // IntRange checking rather than just looking at the unpromoted type here.
  636. if (ConvVal != Val)
  637. S.Diag(Loc, diag::warn_case_value_overflow) << Val.toString(10)
  638. << ConvVal.toString(10);
  639. }
  640. }
  641. typedef SmallVector<std::pair<llvm::APSInt, EnumConstantDecl*>, 64> EnumValsTy;
  642. /// Returns true if we should emit a diagnostic about this case expression not
  643. /// being a part of the enum used in the switch controlling expression.
  644. static bool ShouldDiagnoseSwitchCaseNotInEnum(const Sema &S,
  645. const EnumDecl *ED,
  646. const Expr *CaseExpr,
  647. EnumValsTy::iterator &EI,
  648. EnumValsTy::iterator &EIEnd,
  649. const llvm::APSInt &Val) {
  650. if (!ED->isClosed())
  651. return false;
  652. if (const DeclRefExpr *DRE =
  653. dyn_cast<DeclRefExpr>(CaseExpr->IgnoreParenImpCasts())) {
  654. if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
  655. QualType VarType = VD->getType();
  656. QualType EnumType = S.Context.getTypeDeclType(ED);
  657. if (VD->hasGlobalStorage() && VarType.isConstQualified() &&
  658. S.Context.hasSameUnqualifiedType(EnumType, VarType))
  659. return false;
  660. }
  661. }
  662. if (ED->hasAttr<FlagEnumAttr>())
  663. return !S.IsValueInFlagEnum(ED, Val, false);
  664. while (EI != EIEnd && EI->first < Val)
  665. EI++;
  666. if (EI != EIEnd && EI->first == Val)
  667. return false;
  668. return true;
  669. }
  670. static void checkEnumTypesInSwitchStmt(Sema &S, const Expr *Cond,
  671. const Expr *Case) {
  672. QualType CondType = Cond->getType();
  673. QualType CaseType = Case->getType();
  674. const EnumType *CondEnumType = CondType->getAs<EnumType>();
  675. const EnumType *CaseEnumType = CaseType->getAs<EnumType>();
  676. if (!CondEnumType || !CaseEnumType)
  677. return;
  678. // Ignore anonymous enums.
  679. if (!CondEnumType->getDecl()->getIdentifier() &&
  680. !CondEnumType->getDecl()->getTypedefNameForAnonDecl())
  681. return;
  682. if (!CaseEnumType->getDecl()->getIdentifier() &&
  683. !CaseEnumType->getDecl()->getTypedefNameForAnonDecl())
  684. return;
  685. if (S.Context.hasSameUnqualifiedType(CondType, CaseType))
  686. return;
  687. S.Diag(Case->getExprLoc(), diag::warn_comparison_of_mixed_enum_types_switch)
  688. << CondType << CaseType << Cond->getSourceRange()
  689. << Case->getSourceRange();
  690. }
  691. StmtResult
  692. Sema::ActOnFinishSwitchStmt(SourceLocation SwitchLoc, Stmt *Switch,
  693. Stmt *BodyStmt) {
  694. SwitchStmt *SS = cast<SwitchStmt>(Switch);
  695. bool CaseListIsIncomplete = getCurFunction()->SwitchStack.back().getInt();
  696. assert(SS == getCurFunction()->SwitchStack.back().getPointer() &&
  697. "switch stack missing push/pop!");
  698. getCurFunction()->SwitchStack.pop_back();
  699. if (!BodyStmt) return StmtError();
  700. SS->setBody(BodyStmt, SwitchLoc);
  701. Expr *CondExpr = SS->getCond();
  702. if (!CondExpr) return StmtError();
  703. QualType CondType = CondExpr->getType();
  704. // C++ 6.4.2.p2:
  705. // Integral promotions are performed (on the switch condition).
  706. //
  707. // A case value unrepresentable by the original switch condition
  708. // type (before the promotion) doesn't make sense, even when it can
  709. // be represented by the promoted type. Therefore we need to find
  710. // the pre-promotion type of the switch condition.
  711. const Expr *CondExprBeforePromotion = CondExpr;
  712. QualType CondTypeBeforePromotion =
  713. GetTypeBeforeIntegralPromotion(CondExprBeforePromotion);
  714. // Get the bitwidth of the switched-on value after promotions. We must
  715. // convert the integer case values to this width before comparison.
  716. bool HasDependentValue
  717. = CondExpr->isTypeDependent() || CondExpr->isValueDependent();
  718. unsigned CondWidth = HasDependentValue ? 0 : Context.getIntWidth(CondType);
  719. bool CondIsSigned = CondType->isSignedIntegerOrEnumerationType();
  720. // Get the width and signedness that the condition might actually have, for
  721. // warning purposes.
  722. // FIXME: Grab an IntRange for the condition rather than using the unpromoted
  723. // type.
  724. unsigned CondWidthBeforePromotion
  725. = HasDependentValue ? 0 : Context.getIntWidth(CondTypeBeforePromotion);
  726. bool CondIsSignedBeforePromotion
  727. = CondTypeBeforePromotion->isSignedIntegerOrEnumerationType();
  728. // Accumulate all of the case values in a vector so that we can sort them
  729. // and detect duplicates. This vector contains the APInt for the case after
  730. // it has been converted to the condition type.
  731. typedef SmallVector<std::pair<llvm::APSInt, CaseStmt*>, 64> CaseValsTy;
  732. CaseValsTy CaseVals;
  733. // Keep track of any GNU case ranges we see. The APSInt is the low value.
  734. typedef std::vector<std::pair<llvm::APSInt, CaseStmt*> > CaseRangesTy;
  735. CaseRangesTy CaseRanges;
  736. DefaultStmt *TheDefaultStmt = nullptr;
  737. bool CaseListIsErroneous = false;
  738. for (SwitchCase *SC = SS->getSwitchCaseList(); SC && !HasDependentValue;
  739. SC = SC->getNextSwitchCase()) {
  740. if (DefaultStmt *DS = dyn_cast<DefaultStmt>(SC)) {
  741. if (TheDefaultStmt) {
  742. Diag(DS->getDefaultLoc(), diag::err_multiple_default_labels_defined);
  743. Diag(TheDefaultStmt->getDefaultLoc(), diag::note_duplicate_case_prev);
  744. // FIXME: Remove the default statement from the switch block so that
  745. // we'll return a valid AST. This requires recursing down the AST and
  746. // finding it, not something we are set up to do right now. For now,
  747. // just lop the entire switch stmt out of the AST.
  748. CaseListIsErroneous = true;
  749. }
  750. TheDefaultStmt = DS;
  751. } else {
  752. CaseStmt *CS = cast<CaseStmt>(SC);
  753. Expr *Lo = CS->getLHS();
  754. if (Lo->isValueDependent()) {
  755. HasDependentValue = true;
  756. break;
  757. }
  758. // We already verified that the expression has a constant value;
  759. // get that value (prior to conversions).
  760. const Expr *LoBeforePromotion = Lo;
  761. GetTypeBeforeIntegralPromotion(LoBeforePromotion);
  762. llvm::APSInt LoVal = LoBeforePromotion->EvaluateKnownConstInt(Context);
  763. // Check the unconverted value is within the range of possible values of
  764. // the switch expression.
  765. checkCaseValue(*this, Lo->getBeginLoc(), LoVal, CondWidthBeforePromotion,
  766. CondIsSignedBeforePromotion);
  767. // FIXME: This duplicates the check performed for warn_not_in_enum below.
  768. checkEnumTypesInSwitchStmt(*this, CondExprBeforePromotion,
  769. LoBeforePromotion);
  770. // Convert the value to the same width/sign as the condition.
  771. AdjustAPSInt(LoVal, CondWidth, CondIsSigned);
  772. // If this is a case range, remember it in CaseRanges, otherwise CaseVals.
  773. if (CS->getRHS()) {
  774. if (CS->getRHS()->isValueDependent()) {
  775. HasDependentValue = true;
  776. break;
  777. }
  778. CaseRanges.push_back(std::make_pair(LoVal, CS));
  779. } else
  780. CaseVals.push_back(std::make_pair(LoVal, CS));
  781. }
  782. }
  783. if (!HasDependentValue) {
  784. // If we don't have a default statement, check whether the
  785. // condition is constant.
  786. llvm::APSInt ConstantCondValue;
  787. bool HasConstantCond = false;
  788. if (!HasDependentValue && !TheDefaultStmt) {
  789. Expr::EvalResult Result;
  790. HasConstantCond = CondExpr->EvaluateAsInt(Result, Context,
  791. Expr::SE_AllowSideEffects);
  792. if (Result.Val.isInt())
  793. ConstantCondValue = Result.Val.getInt();
  794. assert(!HasConstantCond ||
  795. (ConstantCondValue.getBitWidth() == CondWidth &&
  796. ConstantCondValue.isSigned() == CondIsSigned));
  797. }
  798. bool ShouldCheckConstantCond = HasConstantCond;
  799. // Sort all the scalar case values so we can easily detect duplicates.
  800. llvm::stable_sort(CaseVals, CmpCaseVals);
  801. if (!CaseVals.empty()) {
  802. for (unsigned i = 0, e = CaseVals.size(); i != e; ++i) {
  803. if (ShouldCheckConstantCond &&
  804. CaseVals[i].first == ConstantCondValue)
  805. ShouldCheckConstantCond = false;
  806. if (i != 0 && CaseVals[i].first == CaseVals[i-1].first) {
  807. // If we have a duplicate, report it.
  808. // First, determine if either case value has a name
  809. StringRef PrevString, CurrString;
  810. Expr *PrevCase = CaseVals[i-1].second->getLHS()->IgnoreParenCasts();
  811. Expr *CurrCase = CaseVals[i].second->getLHS()->IgnoreParenCasts();
  812. if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(PrevCase)) {
  813. PrevString = DeclRef->getDecl()->getName();
  814. }
  815. if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(CurrCase)) {
  816. CurrString = DeclRef->getDecl()->getName();
  817. }
  818. SmallString<16> CaseValStr;
  819. CaseVals[i-1].first.toString(CaseValStr);
  820. if (PrevString == CurrString)
  821. Diag(CaseVals[i].second->getLHS()->getBeginLoc(),
  822. diag::err_duplicate_case)
  823. << (PrevString.empty() ? StringRef(CaseValStr) : PrevString);
  824. else
  825. Diag(CaseVals[i].second->getLHS()->getBeginLoc(),
  826. diag::err_duplicate_case_differing_expr)
  827. << (PrevString.empty() ? StringRef(CaseValStr) : PrevString)
  828. << (CurrString.empty() ? StringRef(CaseValStr) : CurrString)
  829. << CaseValStr;
  830. Diag(CaseVals[i - 1].second->getLHS()->getBeginLoc(),
  831. diag::note_duplicate_case_prev);
  832. // FIXME: We really want to remove the bogus case stmt from the
  833. // substmt, but we have no way to do this right now.
  834. CaseListIsErroneous = true;
  835. }
  836. }
  837. }
  838. // Detect duplicate case ranges, which usually don't exist at all in
  839. // the first place.
  840. if (!CaseRanges.empty()) {
  841. // Sort all the case ranges by their low value so we can easily detect
  842. // overlaps between ranges.
  843. llvm::stable_sort(CaseRanges);
  844. // Scan the ranges, computing the high values and removing empty ranges.
  845. std::vector<llvm::APSInt> HiVals;
  846. for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
  847. llvm::APSInt &LoVal = CaseRanges[i].first;
  848. CaseStmt *CR = CaseRanges[i].second;
  849. Expr *Hi = CR->getRHS();
  850. const Expr *HiBeforePromotion = Hi;
  851. GetTypeBeforeIntegralPromotion(HiBeforePromotion);
  852. llvm::APSInt HiVal = HiBeforePromotion->EvaluateKnownConstInt(Context);
  853. // Check the unconverted value is within the range of possible values of
  854. // the switch expression.
  855. checkCaseValue(*this, Hi->getBeginLoc(), HiVal,
  856. CondWidthBeforePromotion, CondIsSignedBeforePromotion);
  857. // Convert the value to the same width/sign as the condition.
  858. AdjustAPSInt(HiVal, CondWidth, CondIsSigned);
  859. // If the low value is bigger than the high value, the case is empty.
  860. if (LoVal > HiVal) {
  861. Diag(CR->getLHS()->getBeginLoc(), diag::warn_case_empty_range)
  862. << SourceRange(CR->getLHS()->getBeginLoc(), Hi->getEndLoc());
  863. CaseRanges.erase(CaseRanges.begin()+i);
  864. --i;
  865. --e;
  866. continue;
  867. }
  868. if (ShouldCheckConstantCond &&
  869. LoVal <= ConstantCondValue &&
  870. ConstantCondValue <= HiVal)
  871. ShouldCheckConstantCond = false;
  872. HiVals.push_back(HiVal);
  873. }
  874. // Rescan the ranges, looking for overlap with singleton values and other
  875. // ranges. Since the range list is sorted, we only need to compare case
  876. // ranges with their neighbors.
  877. for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
  878. llvm::APSInt &CRLo = CaseRanges[i].first;
  879. llvm::APSInt &CRHi = HiVals[i];
  880. CaseStmt *CR = CaseRanges[i].second;
  881. // Check to see whether the case range overlaps with any
  882. // singleton cases.
  883. CaseStmt *OverlapStmt = nullptr;
  884. llvm::APSInt OverlapVal(32);
  885. // Find the smallest value >= the lower bound. If I is in the
  886. // case range, then we have overlap.
  887. CaseValsTy::iterator I = std::lower_bound(CaseVals.begin(),
  888. CaseVals.end(), CRLo,
  889. CaseCompareFunctor());
  890. if (I != CaseVals.end() && I->first < CRHi) {
  891. OverlapVal = I->first; // Found overlap with scalar.
  892. OverlapStmt = I->second;
  893. }
  894. // Find the smallest value bigger than the upper bound.
  895. I = std::upper_bound(I, CaseVals.end(), CRHi, CaseCompareFunctor());
  896. if (I != CaseVals.begin() && (I-1)->first >= CRLo) {
  897. OverlapVal = (I-1)->first; // Found overlap with scalar.
  898. OverlapStmt = (I-1)->second;
  899. }
  900. // Check to see if this case stmt overlaps with the subsequent
  901. // case range.
  902. if (i && CRLo <= HiVals[i-1]) {
  903. OverlapVal = HiVals[i-1]; // Found overlap with range.
  904. OverlapStmt = CaseRanges[i-1].second;
  905. }
  906. if (OverlapStmt) {
  907. // If we have a duplicate, report it.
  908. Diag(CR->getLHS()->getBeginLoc(), diag::err_duplicate_case)
  909. << OverlapVal.toString(10);
  910. Diag(OverlapStmt->getLHS()->getBeginLoc(),
  911. diag::note_duplicate_case_prev);
  912. // FIXME: We really want to remove the bogus case stmt from the
  913. // substmt, but we have no way to do this right now.
  914. CaseListIsErroneous = true;
  915. }
  916. }
  917. }
  918. // Complain if we have a constant condition and we didn't find a match.
  919. if (!CaseListIsErroneous && !CaseListIsIncomplete &&
  920. ShouldCheckConstantCond) {
  921. // TODO: it would be nice if we printed enums as enums, chars as
  922. // chars, etc.
  923. Diag(CondExpr->getExprLoc(), diag::warn_missing_case_for_condition)
  924. << ConstantCondValue.toString(10)
  925. << CondExpr->getSourceRange();
  926. }
  927. // Check to see if switch is over an Enum and handles all of its
  928. // values. We only issue a warning if there is not 'default:', but
  929. // we still do the analysis to preserve this information in the AST
  930. // (which can be used by flow-based analyes).
  931. //
  932. const EnumType *ET = CondTypeBeforePromotion->getAs<EnumType>();
  933. // If switch has default case, then ignore it.
  934. if (!CaseListIsErroneous && !CaseListIsIncomplete && !HasConstantCond &&
  935. ET && ET->getDecl()->isCompleteDefinition()) {
  936. const EnumDecl *ED = ET->getDecl();
  937. EnumValsTy EnumVals;
  938. // Gather all enum values, set their type and sort them,
  939. // allowing easier comparison with CaseVals.
  940. for (auto *EDI : ED->enumerators()) {
  941. llvm::APSInt Val = EDI->getInitVal();
  942. AdjustAPSInt(Val, CondWidth, CondIsSigned);
  943. EnumVals.push_back(std::make_pair(Val, EDI));
  944. }
  945. llvm::stable_sort(EnumVals, CmpEnumVals);
  946. auto EI = EnumVals.begin(), EIEnd =
  947. std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals);
  948. // See which case values aren't in enum.
  949. for (CaseValsTy::const_iterator CI = CaseVals.begin();
  950. CI != CaseVals.end(); CI++) {
  951. Expr *CaseExpr = CI->second->getLHS();
  952. if (ShouldDiagnoseSwitchCaseNotInEnum(*this, ED, CaseExpr, EI, EIEnd,
  953. CI->first))
  954. Diag(CaseExpr->getExprLoc(), diag::warn_not_in_enum)
  955. << CondTypeBeforePromotion;
  956. }
  957. // See which of case ranges aren't in enum
  958. EI = EnumVals.begin();
  959. for (CaseRangesTy::const_iterator RI = CaseRanges.begin();
  960. RI != CaseRanges.end(); RI++) {
  961. Expr *CaseExpr = RI->second->getLHS();
  962. if (ShouldDiagnoseSwitchCaseNotInEnum(*this, ED, CaseExpr, EI, EIEnd,
  963. RI->first))
  964. Diag(CaseExpr->getExprLoc(), diag::warn_not_in_enum)
  965. << CondTypeBeforePromotion;
  966. llvm::APSInt Hi =
  967. RI->second->getRHS()->EvaluateKnownConstInt(Context);
  968. AdjustAPSInt(Hi, CondWidth, CondIsSigned);
  969. CaseExpr = RI->second->getRHS();
  970. if (ShouldDiagnoseSwitchCaseNotInEnum(*this, ED, CaseExpr, EI, EIEnd,
  971. Hi))
  972. Diag(CaseExpr->getExprLoc(), diag::warn_not_in_enum)
  973. << CondTypeBeforePromotion;
  974. }
  975. // Check which enum vals aren't in switch
  976. auto CI = CaseVals.begin();
  977. auto RI = CaseRanges.begin();
  978. bool hasCasesNotInSwitch = false;
  979. SmallVector<DeclarationName,8> UnhandledNames;
  980. for (EI = EnumVals.begin(); EI != EIEnd; EI++) {
  981. // Don't warn about omitted unavailable EnumConstantDecls.
  982. switch (EI->second->getAvailability()) {
  983. case AR_Deprecated:
  984. // Omitting a deprecated constant is ok; it should never materialize.
  985. case AR_Unavailable:
  986. continue;
  987. case AR_NotYetIntroduced:
  988. // Partially available enum constants should be present. Note that we
  989. // suppress -Wunguarded-availability diagnostics for such uses.
  990. case AR_Available:
  991. break;
  992. }
  993. // Drop unneeded case values
  994. while (CI != CaseVals.end() && CI->first < EI->first)
  995. CI++;
  996. if (CI != CaseVals.end() && CI->first == EI->first)
  997. continue;
  998. // Drop unneeded case ranges
  999. for (; RI != CaseRanges.end(); RI++) {
  1000. llvm::APSInt Hi =
  1001. RI->second->getRHS()->EvaluateKnownConstInt(Context);
  1002. AdjustAPSInt(Hi, CondWidth, CondIsSigned);
  1003. if (EI->first <= Hi)
  1004. break;
  1005. }
  1006. if (RI == CaseRanges.end() || EI->first < RI->first) {
  1007. hasCasesNotInSwitch = true;
  1008. UnhandledNames.push_back(EI->second->getDeclName());
  1009. }
  1010. }
  1011. if (TheDefaultStmt && UnhandledNames.empty() && ED->isClosedNonFlag())
  1012. Diag(TheDefaultStmt->getDefaultLoc(), diag::warn_unreachable_default);
  1013. // Produce a nice diagnostic if multiple values aren't handled.
  1014. if (!UnhandledNames.empty()) {
  1015. DiagnosticBuilder DB = Diag(CondExpr->getExprLoc(),
  1016. TheDefaultStmt ? diag::warn_def_missing_case
  1017. : diag::warn_missing_case)
  1018. << (int)UnhandledNames.size();
  1019. for (size_t I = 0, E = std::min(UnhandledNames.size(), (size_t)3);
  1020. I != E; ++I)
  1021. DB << UnhandledNames[I];
  1022. }
  1023. if (!hasCasesNotInSwitch)
  1024. SS->setAllEnumCasesCovered();
  1025. }
  1026. }
  1027. if (BodyStmt)
  1028. DiagnoseEmptyStmtBody(CondExpr->getEndLoc(), BodyStmt,
  1029. diag::warn_empty_switch_body);
  1030. // FIXME: If the case list was broken is some way, we don't have a good system
  1031. // to patch it up. Instead, just return the whole substmt as broken.
  1032. if (CaseListIsErroneous)
  1033. return StmtError();
  1034. return SS;
  1035. }
  1036. void
  1037. Sema::DiagnoseAssignmentEnum(QualType DstType, QualType SrcType,
  1038. Expr *SrcExpr) {
  1039. if (Diags.isIgnored(diag::warn_not_in_enum_assignment, SrcExpr->getExprLoc()))
  1040. return;
  1041. if (const EnumType *ET = DstType->getAs<EnumType>())
  1042. if (!Context.hasSameUnqualifiedType(SrcType, DstType) &&
  1043. SrcType->isIntegerType()) {
  1044. if (!SrcExpr->isTypeDependent() && !SrcExpr->isValueDependent() &&
  1045. SrcExpr->isIntegerConstantExpr(Context)) {
  1046. // Get the bitwidth of the enum value before promotions.
  1047. unsigned DstWidth = Context.getIntWidth(DstType);
  1048. bool DstIsSigned = DstType->isSignedIntegerOrEnumerationType();
  1049. llvm::APSInt RhsVal = SrcExpr->EvaluateKnownConstInt(Context);
  1050. AdjustAPSInt(RhsVal, DstWidth, DstIsSigned);
  1051. const EnumDecl *ED = ET->getDecl();
  1052. if (!ED->isClosed())
  1053. return;
  1054. if (ED->hasAttr<FlagEnumAttr>()) {
  1055. if (!IsValueInFlagEnum(ED, RhsVal, true))
  1056. Diag(SrcExpr->getExprLoc(), diag::warn_not_in_enum_assignment)
  1057. << DstType.getUnqualifiedType();
  1058. } else {
  1059. typedef SmallVector<std::pair<llvm::APSInt, EnumConstantDecl *>, 64>
  1060. EnumValsTy;
  1061. EnumValsTy EnumVals;
  1062. // Gather all enum values, set their type and sort them,
  1063. // allowing easier comparison with rhs constant.
  1064. for (auto *EDI : ED->enumerators()) {
  1065. llvm::APSInt Val = EDI->getInitVal();
  1066. AdjustAPSInt(Val, DstWidth, DstIsSigned);
  1067. EnumVals.push_back(std::make_pair(Val, EDI));
  1068. }
  1069. if (EnumVals.empty())
  1070. return;
  1071. llvm::stable_sort(EnumVals, CmpEnumVals);
  1072. EnumValsTy::iterator EIend =
  1073. std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals);
  1074. // See which values aren't in the enum.
  1075. EnumValsTy::const_iterator EI = EnumVals.begin();
  1076. while (EI != EIend && EI->first < RhsVal)
  1077. EI++;
  1078. if (EI == EIend || EI->first != RhsVal) {
  1079. Diag(SrcExpr->getExprLoc(), diag::warn_not_in_enum_assignment)
  1080. << DstType.getUnqualifiedType();
  1081. }
  1082. }
  1083. }
  1084. }
  1085. }
  1086. StmtResult Sema::ActOnWhileStmt(SourceLocation WhileLoc, ConditionResult Cond,
  1087. Stmt *Body) {
  1088. if (Cond.isInvalid())
  1089. return StmtError();
  1090. auto CondVal = Cond.get();
  1091. CheckBreakContinueBinding(CondVal.second);
  1092. if (CondVal.second &&
  1093. !Diags.isIgnored(diag::warn_comma_operator, CondVal.second->getExprLoc()))
  1094. CommaVisitor(*this).Visit(CondVal.second);
  1095. if (isa<NullStmt>(Body))
  1096. getCurCompoundScope().setHasEmptyLoopBodies();
  1097. return WhileStmt::Create(Context, CondVal.first, CondVal.second, Body,
  1098. WhileLoc);
  1099. }
  1100. StmtResult
  1101. Sema::ActOnDoStmt(SourceLocation DoLoc, Stmt *Body,
  1102. SourceLocation WhileLoc, SourceLocation CondLParen,
  1103. Expr *Cond, SourceLocation CondRParen) {
  1104. assert(Cond && "ActOnDoStmt(): missing expression");
  1105. CheckBreakContinueBinding(Cond);
  1106. ExprResult CondResult = CheckBooleanCondition(DoLoc, Cond);
  1107. if (CondResult.isInvalid())
  1108. return StmtError();
  1109. Cond = CondResult.get();
  1110. CondResult = ActOnFinishFullExpr(Cond, DoLoc, /*DiscardedValue*/ false);
  1111. if (CondResult.isInvalid())
  1112. return StmtError();
  1113. Cond = CondResult.get();
  1114. // Only call the CommaVisitor for C89 due to differences in scope flags.
  1115. if (Cond && !getLangOpts().C99 && !getLangOpts().CPlusPlus &&
  1116. !Diags.isIgnored(diag::warn_comma_operator, Cond->getExprLoc()))
  1117. CommaVisitor(*this).Visit(Cond);
  1118. return new (Context) DoStmt(Body, Cond, DoLoc, WhileLoc, CondRParen);
  1119. }
  1120. namespace {
  1121. // Use SetVector since the diagnostic cares about the ordering of the Decl's.
  1122. using DeclSetVector =
  1123. llvm::SetVector<VarDecl *, llvm::SmallVector<VarDecl *, 8>,
  1124. llvm::SmallPtrSet<VarDecl *, 8>>;
  1125. // This visitor will traverse a conditional statement and store all
  1126. // the evaluated decls into a vector. Simple is set to true if none
  1127. // of the excluded constructs are used.
  1128. class DeclExtractor : public EvaluatedExprVisitor<DeclExtractor> {
  1129. DeclSetVector &Decls;
  1130. SmallVectorImpl<SourceRange> &Ranges;
  1131. bool Simple;
  1132. public:
  1133. typedef EvaluatedExprVisitor<DeclExtractor> Inherited;
  1134. DeclExtractor(Sema &S, DeclSetVector &Decls,
  1135. SmallVectorImpl<SourceRange> &Ranges) :
  1136. Inherited(S.Context),
  1137. Decls(Decls),
  1138. Ranges(Ranges),
  1139. Simple(true) {}
  1140. bool isSimple() { return Simple; }
  1141. // Replaces the method in EvaluatedExprVisitor.
  1142. void VisitMemberExpr(MemberExpr* E) {
  1143. Simple = false;
  1144. }
  1145. // Any Stmt not whitelisted will cause the condition to be marked complex.
  1146. void VisitStmt(Stmt *S) {
  1147. Simple = false;
  1148. }
  1149. void VisitBinaryOperator(BinaryOperator *E) {
  1150. Visit(E->getLHS());
  1151. Visit(E->getRHS());
  1152. }
  1153. void VisitCastExpr(CastExpr *E) {
  1154. Visit(E->getSubExpr());
  1155. }
  1156. void VisitUnaryOperator(UnaryOperator *E) {
  1157. // Skip checking conditionals with derefernces.
  1158. if (E->getOpcode() == UO_Deref)
  1159. Simple = false;
  1160. else
  1161. Visit(E->getSubExpr());
  1162. }
  1163. void VisitConditionalOperator(ConditionalOperator *E) {
  1164. Visit(E->getCond());
  1165. Visit(E->getTrueExpr());
  1166. Visit(E->getFalseExpr());
  1167. }
  1168. void VisitParenExpr(ParenExpr *E) {
  1169. Visit(E->getSubExpr());
  1170. }
  1171. void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
  1172. Visit(E->getOpaqueValue()->getSourceExpr());
  1173. Visit(E->getFalseExpr());
  1174. }
  1175. void VisitIntegerLiteral(IntegerLiteral *E) { }
  1176. void VisitFloatingLiteral(FloatingLiteral *E) { }
  1177. void VisitCXXBoolLiteralExpr(CXXBoolLiteralExpr *E) { }
  1178. void VisitCharacterLiteral(CharacterLiteral *E) { }
  1179. void VisitGNUNullExpr(GNUNullExpr *E) { }
  1180. void VisitImaginaryLiteral(ImaginaryLiteral *E) { }
  1181. void VisitDeclRefExpr(DeclRefExpr *E) {
  1182. VarDecl *VD = dyn_cast<VarDecl>(E->getDecl());
  1183. if (!VD) {
  1184. // Don't allow unhandled Decl types.
  1185. Simple = false;
  1186. return;
  1187. }
  1188. Ranges.push_back(E->getSourceRange());
  1189. Decls.insert(VD);
  1190. }
  1191. }; // end class DeclExtractor
  1192. // DeclMatcher checks to see if the decls are used in a non-evaluated
  1193. // context.
  1194. class DeclMatcher : public EvaluatedExprVisitor<DeclMatcher> {
  1195. DeclSetVector &Decls;
  1196. bool FoundDecl;
  1197. public:
  1198. typedef EvaluatedExprVisitor<DeclMatcher> Inherited;
  1199. DeclMatcher(Sema &S, DeclSetVector &Decls, Stmt *Statement) :
  1200. Inherited(S.Context), Decls(Decls), FoundDecl(false) {
  1201. if (!Statement) return;
  1202. Visit(Statement);
  1203. }
  1204. void VisitReturnStmt(ReturnStmt *S) {
  1205. FoundDecl = true;
  1206. }
  1207. void VisitBreakStmt(BreakStmt *S) {
  1208. FoundDecl = true;
  1209. }
  1210. void VisitGotoStmt(GotoStmt *S) {
  1211. FoundDecl = true;
  1212. }
  1213. void VisitCastExpr(CastExpr *E) {
  1214. if (E->getCastKind() == CK_LValueToRValue)
  1215. CheckLValueToRValueCast(E->getSubExpr());
  1216. else
  1217. Visit(E->getSubExpr());
  1218. }
  1219. void CheckLValueToRValueCast(Expr *E) {
  1220. E = E->IgnoreParenImpCasts();
  1221. if (isa<DeclRefExpr>(E)) {
  1222. return;
  1223. }
  1224. if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
  1225. Visit(CO->getCond());
  1226. CheckLValueToRValueCast(CO->getTrueExpr());
  1227. CheckLValueToRValueCast(CO->getFalseExpr());
  1228. return;
  1229. }
  1230. if (BinaryConditionalOperator *BCO =
  1231. dyn_cast<BinaryConditionalOperator>(E)) {
  1232. CheckLValueToRValueCast(BCO->getOpaqueValue()->getSourceExpr());
  1233. CheckLValueToRValueCast(BCO->getFalseExpr());
  1234. return;
  1235. }
  1236. Visit(E);
  1237. }
  1238. void VisitDeclRefExpr(DeclRefExpr *E) {
  1239. if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
  1240. if (Decls.count(VD))
  1241. FoundDecl = true;
  1242. }
  1243. void VisitPseudoObjectExpr(PseudoObjectExpr *POE) {
  1244. // Only need to visit the semantics for POE.
  1245. // SyntaticForm doesn't really use the Decal.
  1246. for (auto *S : POE->semantics()) {
  1247. if (auto *OVE = dyn_cast<OpaqueValueExpr>(S))
  1248. // Look past the OVE into the expression it binds.
  1249. Visit(OVE->getSourceExpr());
  1250. else
  1251. Visit(S);
  1252. }
  1253. }
  1254. bool FoundDeclInUse() { return FoundDecl; }
  1255. }; // end class DeclMatcher
  1256. void CheckForLoopConditionalStatement(Sema &S, Expr *Second,
  1257. Expr *Third, Stmt *Body) {
  1258. // Condition is empty
  1259. if (!Second) return;
  1260. if (S.Diags.isIgnored(diag::warn_variables_not_in_loop_body,
  1261. Second->getBeginLoc()))
  1262. return;
  1263. PartialDiagnostic PDiag = S.PDiag(diag::warn_variables_not_in_loop_body);
  1264. DeclSetVector Decls;
  1265. SmallVector<SourceRange, 10> Ranges;
  1266. DeclExtractor DE(S, Decls, Ranges);
  1267. DE.Visit(Second);
  1268. // Don't analyze complex conditionals.
  1269. if (!DE.isSimple()) return;
  1270. // No decls found.
  1271. if (Decls.size() == 0) return;
  1272. // Don't warn on volatile, static, or global variables.
  1273. for (auto *VD : Decls)
  1274. if (VD->getType().isVolatileQualified() || VD->hasGlobalStorage())
  1275. return;
  1276. if (DeclMatcher(S, Decls, Second).FoundDeclInUse() ||
  1277. DeclMatcher(S, Decls, Third).FoundDeclInUse() ||
  1278. DeclMatcher(S, Decls, Body).FoundDeclInUse())
  1279. return;
  1280. // Load decl names into diagnostic.
  1281. if (Decls.size() > 4) {
  1282. PDiag << 0;
  1283. } else {
  1284. PDiag << (unsigned)Decls.size();
  1285. for (auto *VD : Decls)
  1286. PDiag << VD->getDeclName();
  1287. }
  1288. for (auto Range : Ranges)
  1289. PDiag << Range;
  1290. S.Diag(Ranges.begin()->getBegin(), PDiag);
  1291. }
  1292. // If Statement is an incemement or decrement, return true and sets the
  1293. // variables Increment and DRE.
  1294. bool ProcessIterationStmt(Sema &S, Stmt* Statement, bool &Increment,
  1295. DeclRefExpr *&DRE) {
  1296. if (auto Cleanups = dyn_cast<ExprWithCleanups>(Statement))
  1297. if (!Cleanups->cleanupsHaveSideEffects())
  1298. Statement = Cleanups->getSubExpr();
  1299. if (UnaryOperator *UO = dyn_cast<UnaryOperator>(Statement)) {
  1300. switch (UO->getOpcode()) {
  1301. default: return false;
  1302. case UO_PostInc:
  1303. case UO_PreInc:
  1304. Increment = true;
  1305. break;
  1306. case UO_PostDec:
  1307. case UO_PreDec:
  1308. Increment = false;
  1309. break;
  1310. }
  1311. DRE = dyn_cast<DeclRefExpr>(UO->getSubExpr());
  1312. return DRE;
  1313. }
  1314. if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(Statement)) {
  1315. FunctionDecl *FD = Call->getDirectCallee();
  1316. if (!FD || !FD->isOverloadedOperator()) return false;
  1317. switch (FD->getOverloadedOperator()) {
  1318. default: return false;
  1319. case OO_PlusPlus:
  1320. Increment = true;
  1321. break;
  1322. case OO_MinusMinus:
  1323. Increment = false;
  1324. break;
  1325. }
  1326. DRE = dyn_cast<DeclRefExpr>(Call->getArg(0));
  1327. return DRE;
  1328. }
  1329. return false;
  1330. }
  1331. // A visitor to determine if a continue or break statement is a
  1332. // subexpression.
  1333. class BreakContinueFinder : public ConstEvaluatedExprVisitor<BreakContinueFinder> {
  1334. SourceLocation BreakLoc;
  1335. SourceLocation ContinueLoc;
  1336. bool InSwitch = false;
  1337. public:
  1338. BreakContinueFinder(Sema &S, const Stmt* Body) :
  1339. Inherited(S.Context) {
  1340. Visit(Body);
  1341. }
  1342. typedef ConstEvaluatedExprVisitor<BreakContinueFinder> Inherited;
  1343. void VisitContinueStmt(const ContinueStmt* E) {
  1344. ContinueLoc = E->getContinueLoc();
  1345. }
  1346. void VisitBreakStmt(const BreakStmt* E) {
  1347. if (!InSwitch)
  1348. BreakLoc = E->getBreakLoc();
  1349. }
  1350. void VisitSwitchStmt(const SwitchStmt* S) {
  1351. if (const Stmt *Init = S->getInit())
  1352. Visit(Init);
  1353. if (const Stmt *CondVar = S->getConditionVariableDeclStmt())
  1354. Visit(CondVar);
  1355. if (const Stmt *Cond = S->getCond())
  1356. Visit(Cond);
  1357. // Don't return break statements from the body of a switch.
  1358. InSwitch = true;
  1359. if (const Stmt *Body = S->getBody())
  1360. Visit(Body);
  1361. InSwitch = false;
  1362. }
  1363. void VisitForStmt(const ForStmt *S) {
  1364. // Only visit the init statement of a for loop; the body
  1365. // has a different break/continue scope.
  1366. if (const Stmt *Init = S->getInit())
  1367. Visit(Init);
  1368. }
  1369. void VisitWhileStmt(const WhileStmt *) {
  1370. // Do nothing; the children of a while loop have a different
  1371. // break/continue scope.
  1372. }
  1373. void VisitDoStmt(const DoStmt *) {
  1374. // Do nothing; the children of a while loop have a different
  1375. // break/continue scope.
  1376. }
  1377. void VisitCXXForRangeStmt(const CXXForRangeStmt *S) {
  1378. // Only visit the initialization of a for loop; the body
  1379. // has a different break/continue scope.
  1380. if (const Stmt *Init = S->getInit())
  1381. Visit(Init);
  1382. if (const Stmt *Range = S->getRangeStmt())
  1383. Visit(Range);
  1384. if (const Stmt *Begin = S->getBeginStmt())
  1385. Visit(Begin);
  1386. if (const Stmt *End = S->getEndStmt())
  1387. Visit(End);
  1388. }
  1389. void VisitObjCForCollectionStmt(const ObjCForCollectionStmt *S) {
  1390. // Only visit the initialization of a for loop; the body
  1391. // has a different break/continue scope.
  1392. if (const Stmt *Element = S->getElement())
  1393. Visit(Element);
  1394. if (const Stmt *Collection = S->getCollection())
  1395. Visit(Collection);
  1396. }
  1397. bool ContinueFound() { return ContinueLoc.isValid(); }
  1398. bool BreakFound() { return BreakLoc.isValid(); }
  1399. SourceLocation GetContinueLoc() { return ContinueLoc; }
  1400. SourceLocation GetBreakLoc() { return BreakLoc; }
  1401. }; // end class BreakContinueFinder
  1402. // Emit a warning when a loop increment/decrement appears twice per loop
  1403. // iteration. The conditions which trigger this warning are:
  1404. // 1) The last statement in the loop body and the third expression in the
  1405. // for loop are both increment or both decrement of the same variable
  1406. // 2) No continue statements in the loop body.
  1407. void CheckForRedundantIteration(Sema &S, Expr *Third, Stmt *Body) {
  1408. // Return when there is nothing to check.
  1409. if (!Body || !Third) return;
  1410. if (S.Diags.isIgnored(diag::warn_redundant_loop_iteration,
  1411. Third->getBeginLoc()))
  1412. return;
  1413. // Get the last statement from the loop body.
  1414. CompoundStmt *CS = dyn_cast<CompoundStmt>(Body);
  1415. if (!CS || CS->body_empty()) return;
  1416. Stmt *LastStmt = CS->body_back();
  1417. if (!LastStmt) return;
  1418. bool LoopIncrement, LastIncrement;
  1419. DeclRefExpr *LoopDRE, *LastDRE;
  1420. if (!ProcessIterationStmt(S, Third, LoopIncrement, LoopDRE)) return;
  1421. if (!ProcessIterationStmt(S, LastStmt, LastIncrement, LastDRE)) return;
  1422. // Check that the two statements are both increments or both decrements
  1423. // on the same variable.
  1424. if (LoopIncrement != LastIncrement ||
  1425. LoopDRE->getDecl() != LastDRE->getDecl()) return;
  1426. if (BreakContinueFinder(S, Body).ContinueFound()) return;
  1427. S.Diag(LastDRE->getLocation(), diag::warn_redundant_loop_iteration)
  1428. << LastDRE->getDecl() << LastIncrement;
  1429. S.Diag(LoopDRE->getLocation(), diag::note_loop_iteration_here)
  1430. << LoopIncrement;
  1431. }
  1432. } // end namespace
  1433. void Sema::CheckBreakContinueBinding(Expr *E) {
  1434. if (!E || getLangOpts().CPlusPlus)
  1435. return;
  1436. BreakContinueFinder BCFinder(*this, E);
  1437. Scope *BreakParent = CurScope->getBreakParent();
  1438. if (BCFinder.BreakFound() && BreakParent) {
  1439. if (BreakParent->getFlags() & Scope::SwitchScope) {
  1440. Diag(BCFinder.GetBreakLoc(), diag::warn_break_binds_to_switch);
  1441. } else {
  1442. Diag(BCFinder.GetBreakLoc(), diag::warn_loop_ctrl_binds_to_inner)
  1443. << "break";
  1444. }
  1445. } else if (BCFinder.ContinueFound() && CurScope->getContinueParent()) {
  1446. Diag(BCFinder.GetContinueLoc(), diag::warn_loop_ctrl_binds_to_inner)
  1447. << "continue";
  1448. }
  1449. }
  1450. StmtResult Sema::ActOnForStmt(SourceLocation ForLoc, SourceLocation LParenLoc,
  1451. Stmt *First, ConditionResult Second,
  1452. FullExprArg third, SourceLocation RParenLoc,
  1453. Stmt *Body) {
  1454. if (Second.isInvalid())
  1455. return StmtError();
  1456. if (!getLangOpts().CPlusPlus) {
  1457. if (DeclStmt *DS = dyn_cast_or_null<DeclStmt>(First)) {
  1458. // C99 6.8.5p3: The declaration part of a 'for' statement shall only
  1459. // declare identifiers for objects having storage class 'auto' or
  1460. // 'register'.
  1461. for (auto *DI : DS->decls()) {
  1462. VarDecl *VD = dyn_cast<VarDecl>(DI);
  1463. if (VD && VD->isLocalVarDecl() && !VD->hasLocalStorage())
  1464. VD = nullptr;
  1465. if (!VD) {
  1466. Diag(DI->getLocation(), diag::err_non_local_variable_decl_in_for);
  1467. DI->setInvalidDecl();
  1468. }
  1469. }
  1470. }
  1471. }
  1472. CheckBreakContinueBinding(Second.get().second);
  1473. CheckBreakContinueBinding(third.get());
  1474. if (!Second.get().first)
  1475. CheckForLoopConditionalStatement(*this, Second.get().second, third.get(),
  1476. Body);
  1477. CheckForRedundantIteration(*this, third.get(), Body);
  1478. if (Second.get().second &&
  1479. !Diags.isIgnored(diag::warn_comma_operator,
  1480. Second.get().second->getExprLoc()))
  1481. CommaVisitor(*this).Visit(Second.get().second);
  1482. Expr *Third = third.release().getAs<Expr>();
  1483. if (isa<NullStmt>(Body))
  1484. getCurCompoundScope().setHasEmptyLoopBodies();
  1485. return new (Context)
  1486. ForStmt(Context, First, Second.get().second, Second.get().first, Third,
  1487. Body, ForLoc, LParenLoc, RParenLoc);
  1488. }
  1489. /// In an Objective C collection iteration statement:
  1490. /// for (x in y)
  1491. /// x can be an arbitrary l-value expression. Bind it up as a
  1492. /// full-expression.
  1493. StmtResult Sema::ActOnForEachLValueExpr(Expr *E) {
  1494. // Reduce placeholder expressions here. Note that this rejects the
  1495. // use of pseudo-object l-values in this position.
  1496. ExprResult result = CheckPlaceholderExpr(E);
  1497. if (result.isInvalid()) return StmtError();
  1498. E = result.get();
  1499. ExprResult FullExpr = ActOnFinishFullExpr(E, /*DiscardedValue*/ false);
  1500. if (FullExpr.isInvalid())
  1501. return StmtError();
  1502. return StmtResult(static_cast<Stmt*>(FullExpr.get()));
  1503. }
  1504. ExprResult
  1505. Sema::CheckObjCForCollectionOperand(SourceLocation forLoc, Expr *collection) {
  1506. if (!collection)
  1507. return ExprError();
  1508. ExprResult result = CorrectDelayedTyposInExpr(collection);
  1509. if (!result.isUsable())
  1510. return ExprError();
  1511. collection = result.get();
  1512. // Bail out early if we've got a type-dependent expression.
  1513. if (collection->isTypeDependent()) return collection;
  1514. // Perform normal l-value conversion.
  1515. result = DefaultFunctionArrayLvalueConversion(collection);
  1516. if (result.isInvalid())
  1517. return ExprError();
  1518. collection = result.get();
  1519. // The operand needs to have object-pointer type.
  1520. // TODO: should we do a contextual conversion?
  1521. const ObjCObjectPointerType *pointerType =
  1522. collection->getType()->getAs<ObjCObjectPointerType>();
  1523. if (!pointerType)
  1524. return Diag(forLoc, diag::err_collection_expr_type)
  1525. << collection->getType() << collection->getSourceRange();
  1526. // Check that the operand provides
  1527. // - countByEnumeratingWithState:objects:count:
  1528. const ObjCObjectType *objectType = pointerType->getObjectType();
  1529. ObjCInterfaceDecl *iface = objectType->getInterface();
  1530. // If we have a forward-declared type, we can't do this check.
  1531. // Under ARC, it is an error not to have a forward-declared class.
  1532. if (iface &&
  1533. (getLangOpts().ObjCAutoRefCount
  1534. ? RequireCompleteType(forLoc, QualType(objectType, 0),
  1535. diag::err_arc_collection_forward, collection)
  1536. : !isCompleteType(forLoc, QualType(objectType, 0)))) {
  1537. // Otherwise, if we have any useful type information, check that
  1538. // the type declares the appropriate method.
  1539. } else if (iface || !objectType->qual_empty()) {
  1540. IdentifierInfo *selectorIdents[] = {
  1541. &Context.Idents.get("countByEnumeratingWithState"),
  1542. &Context.Idents.get("objects"),
  1543. &Context.Idents.get("count")
  1544. };
  1545. Selector selector = Context.Selectors.getSelector(3, &selectorIdents[0]);
  1546. ObjCMethodDecl *method = nullptr;
  1547. // If there's an interface, look in both the public and private APIs.
  1548. if (iface) {
  1549. method = iface->lookupInstanceMethod(selector);
  1550. if (!method) method = iface->lookupPrivateMethod(selector);
  1551. }
  1552. // Also check protocol qualifiers.
  1553. if (!method)
  1554. method = LookupMethodInQualifiedType(selector, pointerType,
  1555. /*instance*/ true);
  1556. // If we didn't find it anywhere, give up.
  1557. if (!method) {
  1558. Diag(forLoc, diag::warn_collection_expr_type)
  1559. << collection->getType() << selector << collection->getSourceRange();
  1560. }
  1561. // TODO: check for an incompatible signature?
  1562. }
  1563. // Wrap up any cleanups in the expression.
  1564. return collection;
  1565. }
  1566. StmtResult
  1567. Sema::ActOnObjCForCollectionStmt(SourceLocation ForLoc,
  1568. Stmt *First, Expr *collection,
  1569. SourceLocation RParenLoc) {
  1570. setFunctionHasBranchProtectedScope();
  1571. ExprResult CollectionExprResult =
  1572. CheckObjCForCollectionOperand(ForLoc, collection);
  1573. if (First) {
  1574. QualType FirstType;
  1575. if (DeclStmt *DS = dyn_cast<DeclStmt>(First)) {
  1576. if (!DS->isSingleDecl())
  1577. return StmtError(Diag((*DS->decl_begin())->getLocation(),
  1578. diag::err_toomany_element_decls));
  1579. VarDecl *D = dyn_cast<VarDecl>(DS->getSingleDecl());
  1580. if (!D || D->isInvalidDecl())
  1581. return StmtError();
  1582. FirstType = D->getType();
  1583. // C99 6.8.5p3: The declaration part of a 'for' statement shall only
  1584. // declare identifiers for objects having storage class 'auto' or
  1585. // 'register'.
  1586. if (!D->hasLocalStorage())
  1587. return StmtError(Diag(D->getLocation(),
  1588. diag::err_non_local_variable_decl_in_for));
  1589. // If the type contained 'auto', deduce the 'auto' to 'id'.
  1590. if (FirstType->getContainedAutoType()) {
  1591. OpaqueValueExpr OpaqueId(D->getLocation(), Context.getObjCIdType(),
  1592. VK_RValue);
  1593. Expr *DeducedInit = &OpaqueId;
  1594. if (DeduceAutoType(D->getTypeSourceInfo(), DeducedInit, FirstType) ==
  1595. DAR_Failed)
  1596. DiagnoseAutoDeductionFailure(D, DeducedInit);
  1597. if (FirstType.isNull()) {
  1598. D->setInvalidDecl();
  1599. return StmtError();
  1600. }
  1601. D->setType(FirstType);
  1602. if (!inTemplateInstantiation()) {
  1603. SourceLocation Loc =
  1604. D->getTypeSourceInfo()->getTypeLoc().getBeginLoc();
  1605. Diag(Loc, diag::warn_auto_var_is_id)
  1606. << D->getDeclName();
  1607. }
  1608. }
  1609. } else {
  1610. Expr *FirstE = cast<Expr>(First);
  1611. if (!FirstE->isTypeDependent() && !FirstE->isLValue())
  1612. return StmtError(
  1613. Diag(First->getBeginLoc(), diag::err_selector_element_not_lvalue)
  1614. << First->getSourceRange());
  1615. FirstType = static_cast<Expr*>(First)->getType();
  1616. if (FirstType.isConstQualified())
  1617. Diag(ForLoc, diag::err_selector_element_const_type)
  1618. << FirstType << First->getSourceRange();
  1619. }
  1620. if (!FirstType->isDependentType() &&
  1621. !FirstType->isObjCObjectPointerType() &&
  1622. !FirstType->isBlockPointerType())
  1623. return StmtError(Diag(ForLoc, diag::err_selector_element_type)
  1624. << FirstType << First->getSourceRange());
  1625. }
  1626. if (CollectionExprResult.isInvalid())
  1627. return StmtError();
  1628. CollectionExprResult =
  1629. ActOnFinishFullExpr(CollectionExprResult.get(), /*DiscardedValue*/ false);
  1630. if (CollectionExprResult.isInvalid())
  1631. return StmtError();
  1632. return new (Context) ObjCForCollectionStmt(First, CollectionExprResult.get(),
  1633. nullptr, ForLoc, RParenLoc);
  1634. }
  1635. /// Finish building a variable declaration for a for-range statement.
  1636. /// \return true if an error occurs.
  1637. static bool FinishForRangeVarDecl(Sema &SemaRef, VarDecl *Decl, Expr *Init,
  1638. SourceLocation Loc, int DiagID) {
  1639. if (Decl->getType()->isUndeducedType()) {
  1640. ExprResult Res = SemaRef.CorrectDelayedTyposInExpr(Init);
  1641. if (!Res.isUsable()) {
  1642. Decl->setInvalidDecl();
  1643. return true;
  1644. }
  1645. Init = Res.get();
  1646. }
  1647. // Deduce the type for the iterator variable now rather than leaving it to
  1648. // AddInitializerToDecl, so we can produce a more suitable diagnostic.
  1649. QualType InitType;
  1650. if ((!isa<InitListExpr>(Init) && Init->getType()->isVoidType()) ||
  1651. SemaRef.DeduceAutoType(Decl->getTypeSourceInfo(), Init, InitType) ==
  1652. Sema::DAR_Failed)
  1653. SemaRef.Diag(Loc, DiagID) << Init->getType();
  1654. if (InitType.isNull()) {
  1655. Decl->setInvalidDecl();
  1656. return true;
  1657. }
  1658. Decl->setType(InitType);
  1659. // In ARC, infer lifetime.
  1660. // FIXME: ARC may want to turn this into 'const __unsafe_unretained' if
  1661. // we're doing the equivalent of fast iteration.
  1662. if (SemaRef.getLangOpts().ObjCAutoRefCount &&
  1663. SemaRef.inferObjCARCLifetime(Decl))
  1664. Decl->setInvalidDecl();
  1665. SemaRef.AddInitializerToDecl(Decl, Init, /*DirectInit=*/false);
  1666. SemaRef.FinalizeDeclaration(Decl);
  1667. SemaRef.CurContext->addHiddenDecl(Decl);
  1668. return false;
  1669. }
  1670. namespace {
  1671. // An enum to represent whether something is dealing with a call to begin()
  1672. // or a call to end() in a range-based for loop.
  1673. enum BeginEndFunction {
  1674. BEF_begin,
  1675. BEF_end
  1676. };
  1677. /// Produce a note indicating which begin/end function was implicitly called
  1678. /// by a C++11 for-range statement. This is often not obvious from the code,
  1679. /// nor from the diagnostics produced when analysing the implicit expressions
  1680. /// required in a for-range statement.
  1681. void NoteForRangeBeginEndFunction(Sema &SemaRef, Expr *E,
  1682. BeginEndFunction BEF) {
  1683. CallExpr *CE = dyn_cast<CallExpr>(E);
  1684. if (!CE)
  1685. return;
  1686. FunctionDecl *D = dyn_cast<FunctionDecl>(CE->getCalleeDecl());
  1687. if (!D)
  1688. return;
  1689. SourceLocation Loc = D->getLocation();
  1690. std::string Description;
  1691. bool IsTemplate = false;
  1692. if (FunctionTemplateDecl *FunTmpl = D->getPrimaryTemplate()) {
  1693. Description = SemaRef.getTemplateArgumentBindingsText(
  1694. FunTmpl->getTemplateParameters(), *D->getTemplateSpecializationArgs());
  1695. IsTemplate = true;
  1696. }
  1697. SemaRef.Diag(Loc, diag::note_for_range_begin_end)
  1698. << BEF << IsTemplate << Description << E->getType();
  1699. }
  1700. /// Build a variable declaration for a for-range statement.
  1701. VarDecl *BuildForRangeVarDecl(Sema &SemaRef, SourceLocation Loc,
  1702. QualType Type, StringRef Name) {
  1703. DeclContext *DC = SemaRef.CurContext;
  1704. IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
  1705. TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
  1706. VarDecl *Decl = VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type,
  1707. TInfo, SC_None);
  1708. Decl->setImplicit();
  1709. return Decl;
  1710. }
  1711. }
  1712. static bool ObjCEnumerationCollection(Expr *Collection) {
  1713. return !Collection->isTypeDependent()
  1714. && Collection->getType()->getAs<ObjCObjectPointerType>() != nullptr;
  1715. }
  1716. /// ActOnCXXForRangeStmt - Check and build a C++11 for-range statement.
  1717. ///
  1718. /// C++11 [stmt.ranged]:
  1719. /// A range-based for statement is equivalent to
  1720. ///
  1721. /// {
  1722. /// auto && __range = range-init;
  1723. /// for ( auto __begin = begin-expr,
  1724. /// __end = end-expr;
  1725. /// __begin != __end;
  1726. /// ++__begin ) {
  1727. /// for-range-declaration = *__begin;
  1728. /// statement
  1729. /// }
  1730. /// }
  1731. ///
  1732. /// The body of the loop is not available yet, since it cannot be analysed until
  1733. /// we have determined the type of the for-range-declaration.
  1734. StmtResult Sema::ActOnCXXForRangeStmt(Scope *S, SourceLocation ForLoc,
  1735. SourceLocation CoawaitLoc, Stmt *InitStmt,
  1736. Stmt *First, SourceLocation ColonLoc,
  1737. Expr *Range, SourceLocation RParenLoc,
  1738. BuildForRangeKind Kind) {
  1739. if (!First)
  1740. return StmtError();
  1741. if (Range && ObjCEnumerationCollection(Range)) {
  1742. // FIXME: Support init-statements in Objective-C++20 ranged for statement.
  1743. if (InitStmt)
  1744. return Diag(InitStmt->getBeginLoc(), diag::err_objc_for_range_init_stmt)
  1745. << InitStmt->getSourceRange();
  1746. return ActOnObjCForCollectionStmt(ForLoc, First, Range, RParenLoc);
  1747. }
  1748. DeclStmt *DS = dyn_cast<DeclStmt>(First);
  1749. assert(DS && "first part of for range not a decl stmt");
  1750. if (!DS->isSingleDecl()) {
  1751. Diag(DS->getBeginLoc(), diag::err_type_defined_in_for_range);
  1752. return StmtError();
  1753. }
  1754. Decl *LoopVar = DS->getSingleDecl();
  1755. if (LoopVar->isInvalidDecl() || !Range ||
  1756. DiagnoseUnexpandedParameterPack(Range, UPPC_Expression)) {
  1757. LoopVar->setInvalidDecl();
  1758. return StmtError();
  1759. }
  1760. // Build the coroutine state immediately and not later during template
  1761. // instantiation
  1762. if (!CoawaitLoc.isInvalid()) {
  1763. if (!ActOnCoroutineBodyStart(S, CoawaitLoc, "co_await"))
  1764. return StmtError();
  1765. }
  1766. // Build auto && __range = range-init
  1767. // Divide by 2, since the variables are in the inner scope (loop body).
  1768. const auto DepthStr = std::to_string(S->getDepth() / 2);
  1769. SourceLocation RangeLoc = Range->getBeginLoc();
  1770. VarDecl *RangeVar = BuildForRangeVarDecl(*this, RangeLoc,
  1771. Context.getAutoRRefDeductType(),
  1772. std::string("__range") + DepthStr);
  1773. if (FinishForRangeVarDecl(*this, RangeVar, Range, RangeLoc,
  1774. diag::err_for_range_deduction_failure)) {
  1775. LoopVar->setInvalidDecl();
  1776. return StmtError();
  1777. }
  1778. // Claim the type doesn't contain auto: we've already done the checking.
  1779. DeclGroupPtrTy RangeGroup =
  1780. BuildDeclaratorGroup(MutableArrayRef<Decl *>((Decl **)&RangeVar, 1));
  1781. StmtResult RangeDecl = ActOnDeclStmt(RangeGroup, RangeLoc, RangeLoc);
  1782. if (RangeDecl.isInvalid()) {
  1783. LoopVar->setInvalidDecl();
  1784. return StmtError();
  1785. }
  1786. return BuildCXXForRangeStmt(
  1787. ForLoc, CoawaitLoc, InitStmt, ColonLoc, RangeDecl.get(),
  1788. /*BeginStmt=*/nullptr, /*EndStmt=*/nullptr,
  1789. /*Cond=*/nullptr, /*Inc=*/nullptr, DS, RParenLoc, Kind);
  1790. }
  1791. /// Create the initialization, compare, and increment steps for
  1792. /// the range-based for loop expression.
  1793. /// This function does not handle array-based for loops,
  1794. /// which are created in Sema::BuildCXXForRangeStmt.
  1795. ///
  1796. /// \returns a ForRangeStatus indicating success or what kind of error occurred.
  1797. /// BeginExpr and EndExpr are set and FRS_Success is returned on success;
  1798. /// CandidateSet and BEF are set and some non-success value is returned on
  1799. /// failure.
  1800. static Sema::ForRangeStatus
  1801. BuildNonArrayForRange(Sema &SemaRef, Expr *BeginRange, Expr *EndRange,
  1802. QualType RangeType, VarDecl *BeginVar, VarDecl *EndVar,
  1803. SourceLocation ColonLoc, SourceLocation CoawaitLoc,
  1804. OverloadCandidateSet *CandidateSet, ExprResult *BeginExpr,
  1805. ExprResult *EndExpr, BeginEndFunction *BEF) {
  1806. DeclarationNameInfo BeginNameInfo(
  1807. &SemaRef.PP.getIdentifierTable().get("begin"), ColonLoc);
  1808. DeclarationNameInfo EndNameInfo(&SemaRef.PP.getIdentifierTable().get("end"),
  1809. ColonLoc);
  1810. LookupResult BeginMemberLookup(SemaRef, BeginNameInfo,
  1811. Sema::LookupMemberName);
  1812. LookupResult EndMemberLookup(SemaRef, EndNameInfo, Sema::LookupMemberName);
  1813. auto BuildBegin = [&] {
  1814. *BEF = BEF_begin;
  1815. Sema::ForRangeStatus RangeStatus =
  1816. SemaRef.BuildForRangeBeginEndCall(ColonLoc, ColonLoc, BeginNameInfo,
  1817. BeginMemberLookup, CandidateSet,
  1818. BeginRange, BeginExpr);
  1819. if (RangeStatus != Sema::FRS_Success) {
  1820. if (RangeStatus == Sema::FRS_DiagnosticIssued)
  1821. SemaRef.Diag(BeginRange->getBeginLoc(), diag::note_in_for_range)
  1822. << ColonLoc << BEF_begin << BeginRange->getType();
  1823. return RangeStatus;
  1824. }
  1825. if (!CoawaitLoc.isInvalid()) {
  1826. // FIXME: getCurScope() should not be used during template instantiation.
  1827. // We should pick up the set of unqualified lookup results for operator
  1828. // co_await during the initial parse.
  1829. *BeginExpr = SemaRef.ActOnCoawaitExpr(SemaRef.getCurScope(), ColonLoc,
  1830. BeginExpr->get());
  1831. if (BeginExpr->isInvalid())
  1832. return Sema::FRS_DiagnosticIssued;
  1833. }
  1834. if (FinishForRangeVarDecl(SemaRef, BeginVar, BeginExpr->get(), ColonLoc,
  1835. diag::err_for_range_iter_deduction_failure)) {
  1836. NoteForRangeBeginEndFunction(SemaRef, BeginExpr->get(), *BEF);
  1837. return Sema::FRS_DiagnosticIssued;
  1838. }
  1839. return Sema::FRS_Success;
  1840. };
  1841. auto BuildEnd = [&] {
  1842. *BEF = BEF_end;
  1843. Sema::ForRangeStatus RangeStatus =
  1844. SemaRef.BuildForRangeBeginEndCall(ColonLoc, ColonLoc, EndNameInfo,
  1845. EndMemberLookup, CandidateSet,
  1846. EndRange, EndExpr);
  1847. if (RangeStatus != Sema::FRS_Success) {
  1848. if (RangeStatus == Sema::FRS_DiagnosticIssued)
  1849. SemaRef.Diag(EndRange->getBeginLoc(), diag::note_in_for_range)
  1850. << ColonLoc << BEF_end << EndRange->getType();
  1851. return RangeStatus;
  1852. }
  1853. if (FinishForRangeVarDecl(SemaRef, EndVar, EndExpr->get(), ColonLoc,
  1854. diag::err_for_range_iter_deduction_failure)) {
  1855. NoteForRangeBeginEndFunction(SemaRef, EndExpr->get(), *BEF);
  1856. return Sema::FRS_DiagnosticIssued;
  1857. }
  1858. return Sema::FRS_Success;
  1859. };
  1860. if (CXXRecordDecl *D = RangeType->getAsCXXRecordDecl()) {
  1861. // - if _RangeT is a class type, the unqualified-ids begin and end are
  1862. // looked up in the scope of class _RangeT as if by class member access
  1863. // lookup (3.4.5), and if either (or both) finds at least one
  1864. // declaration, begin-expr and end-expr are __range.begin() and
  1865. // __range.end(), respectively;
  1866. SemaRef.LookupQualifiedName(BeginMemberLookup, D);
  1867. if (BeginMemberLookup.isAmbiguous())
  1868. return Sema::FRS_DiagnosticIssued;
  1869. SemaRef.LookupQualifiedName(EndMemberLookup, D);
  1870. if (EndMemberLookup.isAmbiguous())
  1871. return Sema::FRS_DiagnosticIssued;
  1872. if (BeginMemberLookup.empty() != EndMemberLookup.empty()) {
  1873. // Look up the non-member form of the member we didn't find, first.
  1874. // This way we prefer a "no viable 'end'" diagnostic over a "i found
  1875. // a 'begin' but ignored it because there was no member 'end'"
  1876. // diagnostic.
  1877. auto BuildNonmember = [&](
  1878. BeginEndFunction BEFFound, LookupResult &Found,
  1879. llvm::function_ref<Sema::ForRangeStatus()> BuildFound,
  1880. llvm::function_ref<Sema::ForRangeStatus()> BuildNotFound) {
  1881. LookupResult OldFound = std::move(Found);
  1882. Found.clear();
  1883. if (Sema::ForRangeStatus Result = BuildNotFound())
  1884. return Result;
  1885. switch (BuildFound()) {
  1886. case Sema::FRS_Success:
  1887. return Sema::FRS_Success;
  1888. case Sema::FRS_NoViableFunction:
  1889. SemaRef.Diag(BeginRange->getBeginLoc(), diag::err_for_range_invalid)
  1890. << BeginRange->getType() << BEFFound;
  1891. CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, BeginRange);
  1892. LLVM_FALLTHROUGH;
  1893. case Sema::FRS_DiagnosticIssued:
  1894. for (NamedDecl *D : OldFound) {
  1895. SemaRef.Diag(D->getLocation(),
  1896. diag::note_for_range_member_begin_end_ignored)
  1897. << BeginRange->getType() << BEFFound;
  1898. }
  1899. return Sema::FRS_DiagnosticIssued;
  1900. }
  1901. llvm_unreachable("unexpected ForRangeStatus");
  1902. };
  1903. if (BeginMemberLookup.empty())
  1904. return BuildNonmember(BEF_end, EndMemberLookup, BuildEnd, BuildBegin);
  1905. return BuildNonmember(BEF_begin, BeginMemberLookup, BuildBegin, BuildEnd);
  1906. }
  1907. } else {
  1908. // - otherwise, begin-expr and end-expr are begin(__range) and
  1909. // end(__range), respectively, where begin and end are looked up with
  1910. // argument-dependent lookup (3.4.2). For the purposes of this name
  1911. // lookup, namespace std is an associated namespace.
  1912. }
  1913. if (Sema::ForRangeStatus Result = BuildBegin())
  1914. return Result;
  1915. return BuildEnd();
  1916. }
  1917. /// Speculatively attempt to dereference an invalid range expression.
  1918. /// If the attempt fails, this function will return a valid, null StmtResult
  1919. /// and emit no diagnostics.
  1920. static StmtResult RebuildForRangeWithDereference(Sema &SemaRef, Scope *S,
  1921. SourceLocation ForLoc,
  1922. SourceLocation CoawaitLoc,
  1923. Stmt *InitStmt,
  1924. Stmt *LoopVarDecl,
  1925. SourceLocation ColonLoc,
  1926. Expr *Range,
  1927. SourceLocation RangeLoc,
  1928. SourceLocation RParenLoc) {
  1929. // Determine whether we can rebuild the for-range statement with a
  1930. // dereferenced range expression.
  1931. ExprResult AdjustedRange;
  1932. {
  1933. Sema::SFINAETrap Trap(SemaRef);
  1934. AdjustedRange = SemaRef.BuildUnaryOp(S, RangeLoc, UO_Deref, Range);
  1935. if (AdjustedRange.isInvalid())
  1936. return StmtResult();
  1937. StmtResult SR = SemaRef.ActOnCXXForRangeStmt(
  1938. S, ForLoc, CoawaitLoc, InitStmt, LoopVarDecl, ColonLoc,
  1939. AdjustedRange.get(), RParenLoc, Sema::BFRK_Check);
  1940. if (SR.isInvalid())
  1941. return StmtResult();
  1942. }
  1943. // The attempt to dereference worked well enough that it could produce a valid
  1944. // loop. Produce a fixit, and rebuild the loop with diagnostics enabled, in
  1945. // case there are any other (non-fatal) problems with it.
  1946. SemaRef.Diag(RangeLoc, diag::err_for_range_dereference)
  1947. << Range->getType() << FixItHint::CreateInsertion(RangeLoc, "*");
  1948. return SemaRef.ActOnCXXForRangeStmt(
  1949. S, ForLoc, CoawaitLoc, InitStmt, LoopVarDecl, ColonLoc,
  1950. AdjustedRange.get(), RParenLoc, Sema::BFRK_Rebuild);
  1951. }
  1952. namespace {
  1953. /// RAII object to automatically invalidate a declaration if an error occurs.
  1954. struct InvalidateOnErrorScope {
  1955. InvalidateOnErrorScope(Sema &SemaRef, Decl *D, bool Enabled)
  1956. : Trap(SemaRef.Diags), D(D), Enabled(Enabled) {}
  1957. ~InvalidateOnErrorScope() {
  1958. if (Enabled && Trap.hasErrorOccurred())
  1959. D->setInvalidDecl();
  1960. }
  1961. DiagnosticErrorTrap Trap;
  1962. Decl *D;
  1963. bool Enabled;
  1964. };
  1965. }
  1966. /// BuildCXXForRangeStmt - Build or instantiate a C++11 for-range statement.
  1967. StmtResult Sema::BuildCXXForRangeStmt(SourceLocation ForLoc,
  1968. SourceLocation CoawaitLoc, Stmt *InitStmt,
  1969. SourceLocation ColonLoc, Stmt *RangeDecl,
  1970. Stmt *Begin, Stmt *End, Expr *Cond,
  1971. Expr *Inc, Stmt *LoopVarDecl,
  1972. SourceLocation RParenLoc,
  1973. BuildForRangeKind Kind) {
  1974. // FIXME: This should not be used during template instantiation. We should
  1975. // pick up the set of unqualified lookup results for the != and + operators
  1976. // in the initial parse.
  1977. //
  1978. // Testcase (accepts-invalid):
  1979. // template<typename T> void f() { for (auto x : T()) {} }
  1980. // namespace N { struct X { X begin(); X end(); int operator*(); }; }
  1981. // bool operator!=(N::X, N::X); void operator++(N::X);
  1982. // void g() { f<N::X>(); }
  1983. Scope *S = getCurScope();
  1984. DeclStmt *RangeDS = cast<DeclStmt>(RangeDecl);
  1985. VarDecl *RangeVar = cast<VarDecl>(RangeDS->getSingleDecl());
  1986. QualType RangeVarType = RangeVar->getType();
  1987. DeclStmt *LoopVarDS = cast<DeclStmt>(LoopVarDecl);
  1988. VarDecl *LoopVar = cast<VarDecl>(LoopVarDS->getSingleDecl());
  1989. // If we hit any errors, mark the loop variable as invalid if its type
  1990. // contains 'auto'.
  1991. InvalidateOnErrorScope Invalidate(*this, LoopVar,
  1992. LoopVar->getType()->isUndeducedType());
  1993. StmtResult BeginDeclStmt = Begin;
  1994. StmtResult EndDeclStmt = End;
  1995. ExprResult NotEqExpr = Cond, IncrExpr = Inc;
  1996. if (RangeVarType->isDependentType()) {
  1997. // The range is implicitly used as a placeholder when it is dependent.
  1998. RangeVar->markUsed(Context);
  1999. // Deduce any 'auto's in the loop variable as 'DependentTy'. We'll fill
  2000. // them in properly when we instantiate the loop.
  2001. if (!LoopVar->isInvalidDecl() && Kind != BFRK_Check) {
  2002. if (auto *DD = dyn_cast<DecompositionDecl>(LoopVar))
  2003. for (auto *Binding : DD->bindings())
  2004. Binding->setType(Context.DependentTy);
  2005. LoopVar->setType(SubstAutoType(LoopVar->getType(), Context.DependentTy));
  2006. }
  2007. } else if (!BeginDeclStmt.get()) {
  2008. SourceLocation RangeLoc = RangeVar->getLocation();
  2009. const QualType RangeVarNonRefType = RangeVarType.getNonReferenceType();
  2010. ExprResult BeginRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType,
  2011. VK_LValue, ColonLoc);
  2012. if (BeginRangeRef.isInvalid())
  2013. return StmtError();
  2014. ExprResult EndRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType,
  2015. VK_LValue, ColonLoc);
  2016. if (EndRangeRef.isInvalid())
  2017. return StmtError();
  2018. QualType AutoType = Context.getAutoDeductType();
  2019. Expr *Range = RangeVar->getInit();
  2020. if (!Range)
  2021. return StmtError();
  2022. QualType RangeType = Range->getType();
  2023. if (RequireCompleteType(RangeLoc, RangeType,
  2024. diag::err_for_range_incomplete_type))
  2025. return StmtError();
  2026. // Build auto __begin = begin-expr, __end = end-expr.
  2027. // Divide by 2, since the variables are in the inner scope (loop body).
  2028. const auto DepthStr = std::to_string(S->getDepth() / 2);
  2029. VarDecl *BeginVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType,
  2030. std::string("__begin") + DepthStr);
  2031. VarDecl *EndVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType,
  2032. std::string("__end") + DepthStr);
  2033. // Build begin-expr and end-expr and attach to __begin and __end variables.
  2034. ExprResult BeginExpr, EndExpr;
  2035. if (const ArrayType *UnqAT = RangeType->getAsArrayTypeUnsafe()) {
  2036. // - if _RangeT is an array type, begin-expr and end-expr are __range and
  2037. // __range + __bound, respectively, where __bound is the array bound. If
  2038. // _RangeT is an array of unknown size or an array of incomplete type,
  2039. // the program is ill-formed;
  2040. // begin-expr is __range.
  2041. BeginExpr = BeginRangeRef;
  2042. if (!CoawaitLoc.isInvalid()) {
  2043. BeginExpr = ActOnCoawaitExpr(S, ColonLoc, BeginExpr.get());
  2044. if (BeginExpr.isInvalid())
  2045. return StmtError();
  2046. }
  2047. if (FinishForRangeVarDecl(*this, BeginVar, BeginRangeRef.get(), ColonLoc,
  2048. diag::err_for_range_iter_deduction_failure)) {
  2049. NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
  2050. return StmtError();
  2051. }
  2052. // Find the array bound.
  2053. ExprResult BoundExpr;
  2054. if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(UnqAT))
  2055. BoundExpr = IntegerLiteral::Create(
  2056. Context, CAT->getSize(), Context.getPointerDiffType(), RangeLoc);
  2057. else if (const VariableArrayType *VAT =
  2058. dyn_cast<VariableArrayType>(UnqAT)) {
  2059. // For a variably modified type we can't just use the expression within
  2060. // the array bounds, since we don't want that to be re-evaluated here.
  2061. // Rather, we need to determine what it was when the array was first
  2062. // created - so we resort to using sizeof(vla)/sizeof(element).
  2063. // For e.g.
  2064. // void f(int b) {
  2065. // int vla[b];
  2066. // b = -1; <-- This should not affect the num of iterations below
  2067. // for (int &c : vla) { .. }
  2068. // }
  2069. // FIXME: This results in codegen generating IR that recalculates the
  2070. // run-time number of elements (as opposed to just using the IR Value
  2071. // that corresponds to the run-time value of each bound that was
  2072. // generated when the array was created.) If this proves too embarrassing
  2073. // even for unoptimized IR, consider passing a magic-value/cookie to
  2074. // codegen that then knows to simply use that initial llvm::Value (that
  2075. // corresponds to the bound at time of array creation) within
  2076. // getelementptr. But be prepared to pay the price of increasing a
  2077. // customized form of coupling between the two components - which could
  2078. // be hard to maintain as the codebase evolves.
  2079. ExprResult SizeOfVLAExprR = ActOnUnaryExprOrTypeTraitExpr(
  2080. EndVar->getLocation(), UETT_SizeOf,
  2081. /*isType=*/true,
  2082. CreateParsedType(VAT->desugar(), Context.getTrivialTypeSourceInfo(
  2083. VAT->desugar(), RangeLoc))
  2084. .getAsOpaquePtr(),
  2085. EndVar->getSourceRange());
  2086. if (SizeOfVLAExprR.isInvalid())
  2087. return StmtError();
  2088. ExprResult SizeOfEachElementExprR = ActOnUnaryExprOrTypeTraitExpr(
  2089. EndVar->getLocation(), UETT_SizeOf,
  2090. /*isType=*/true,
  2091. CreateParsedType(VAT->desugar(),
  2092. Context.getTrivialTypeSourceInfo(
  2093. VAT->getElementType(), RangeLoc))
  2094. .getAsOpaquePtr(),
  2095. EndVar->getSourceRange());
  2096. if (SizeOfEachElementExprR.isInvalid())
  2097. return StmtError();
  2098. BoundExpr =
  2099. ActOnBinOp(S, EndVar->getLocation(), tok::slash,
  2100. SizeOfVLAExprR.get(), SizeOfEachElementExprR.get());
  2101. if (BoundExpr.isInvalid())
  2102. return StmtError();
  2103. } else {
  2104. // Can't be a DependentSizedArrayType or an IncompleteArrayType since
  2105. // UnqAT is not incomplete and Range is not type-dependent.
  2106. llvm_unreachable("Unexpected array type in for-range");
  2107. }
  2108. // end-expr is __range + __bound.
  2109. EndExpr = ActOnBinOp(S, ColonLoc, tok::plus, EndRangeRef.get(),
  2110. BoundExpr.get());
  2111. if (EndExpr.isInvalid())
  2112. return StmtError();
  2113. if (FinishForRangeVarDecl(*this, EndVar, EndExpr.get(), ColonLoc,
  2114. diag::err_for_range_iter_deduction_failure)) {
  2115. NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
  2116. return StmtError();
  2117. }
  2118. } else {
  2119. OverloadCandidateSet CandidateSet(RangeLoc,
  2120. OverloadCandidateSet::CSK_Normal);
  2121. BeginEndFunction BEFFailure;
  2122. ForRangeStatus RangeStatus = BuildNonArrayForRange(
  2123. *this, BeginRangeRef.get(), EndRangeRef.get(), RangeType, BeginVar,
  2124. EndVar, ColonLoc, CoawaitLoc, &CandidateSet, &BeginExpr, &EndExpr,
  2125. &BEFFailure);
  2126. if (Kind == BFRK_Build && RangeStatus == FRS_NoViableFunction &&
  2127. BEFFailure == BEF_begin) {
  2128. // If the range is being built from an array parameter, emit a
  2129. // a diagnostic that it is being treated as a pointer.
  2130. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Range)) {
  2131. if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
  2132. QualType ArrayTy = PVD->getOriginalType();
  2133. QualType PointerTy = PVD->getType();
  2134. if (PointerTy->isPointerType() && ArrayTy->isArrayType()) {
  2135. Diag(Range->getBeginLoc(), diag::err_range_on_array_parameter)
  2136. << RangeLoc << PVD << ArrayTy << PointerTy;
  2137. Diag(PVD->getLocation(), diag::note_declared_at);
  2138. return StmtError();
  2139. }
  2140. }
  2141. }
  2142. // If building the range failed, try dereferencing the range expression
  2143. // unless a diagnostic was issued or the end function is problematic.
  2144. StmtResult SR = RebuildForRangeWithDereference(*this, S, ForLoc,
  2145. CoawaitLoc, InitStmt,
  2146. LoopVarDecl, ColonLoc,
  2147. Range, RangeLoc,
  2148. RParenLoc);
  2149. if (SR.isInvalid() || SR.isUsable())
  2150. return SR;
  2151. }
  2152. // Otherwise, emit diagnostics if we haven't already.
  2153. if (RangeStatus == FRS_NoViableFunction) {
  2154. Expr *Range = BEFFailure ? EndRangeRef.get() : BeginRangeRef.get();
  2155. Diag(Range->getBeginLoc(), diag::err_for_range_invalid)
  2156. << RangeLoc << Range->getType() << BEFFailure;
  2157. CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Range);
  2158. }
  2159. // Return an error if no fix was discovered.
  2160. if (RangeStatus != FRS_Success)
  2161. return StmtError();
  2162. }
  2163. assert(!BeginExpr.isInvalid() && !EndExpr.isInvalid() &&
  2164. "invalid range expression in for loop");
  2165. // C++11 [dcl.spec.auto]p7: BeginType and EndType must be the same.
  2166. // C++1z removes this restriction.
  2167. QualType BeginType = BeginVar->getType(), EndType = EndVar->getType();
  2168. if (!Context.hasSameType(BeginType, EndType)) {
  2169. Diag(RangeLoc, getLangOpts().CPlusPlus17
  2170. ? diag::warn_for_range_begin_end_types_differ
  2171. : diag::ext_for_range_begin_end_types_differ)
  2172. << BeginType << EndType;
  2173. NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
  2174. NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
  2175. }
  2176. BeginDeclStmt =
  2177. ActOnDeclStmt(ConvertDeclToDeclGroup(BeginVar), ColonLoc, ColonLoc);
  2178. EndDeclStmt =
  2179. ActOnDeclStmt(ConvertDeclToDeclGroup(EndVar), ColonLoc, ColonLoc);
  2180. const QualType BeginRefNonRefType = BeginType.getNonReferenceType();
  2181. ExprResult BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
  2182. VK_LValue, ColonLoc);
  2183. if (BeginRef.isInvalid())
  2184. return StmtError();
  2185. ExprResult EndRef = BuildDeclRefExpr(EndVar, EndType.getNonReferenceType(),
  2186. VK_LValue, ColonLoc);
  2187. if (EndRef.isInvalid())
  2188. return StmtError();
  2189. // Build and check __begin != __end expression.
  2190. NotEqExpr = ActOnBinOp(S, ColonLoc, tok::exclaimequal,
  2191. BeginRef.get(), EndRef.get());
  2192. if (!NotEqExpr.isInvalid())
  2193. NotEqExpr = CheckBooleanCondition(ColonLoc, NotEqExpr.get());
  2194. if (!NotEqExpr.isInvalid())
  2195. NotEqExpr =
  2196. ActOnFinishFullExpr(NotEqExpr.get(), /*DiscardedValue*/ false);
  2197. if (NotEqExpr.isInvalid()) {
  2198. Diag(RangeLoc, diag::note_for_range_invalid_iterator)
  2199. << RangeLoc << 0 << BeginRangeRef.get()->getType();
  2200. NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
  2201. if (!Context.hasSameType(BeginType, EndType))
  2202. NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
  2203. return StmtError();
  2204. }
  2205. // Build and check ++__begin expression.
  2206. BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
  2207. VK_LValue, ColonLoc);
  2208. if (BeginRef.isInvalid())
  2209. return StmtError();
  2210. IncrExpr = ActOnUnaryOp(S, ColonLoc, tok::plusplus, BeginRef.get());
  2211. if (!IncrExpr.isInvalid() && CoawaitLoc.isValid())
  2212. // FIXME: getCurScope() should not be used during template instantiation.
  2213. // We should pick up the set of unqualified lookup results for operator
  2214. // co_await during the initial parse.
  2215. IncrExpr = ActOnCoawaitExpr(S, CoawaitLoc, IncrExpr.get());
  2216. if (!IncrExpr.isInvalid())
  2217. IncrExpr = ActOnFinishFullExpr(IncrExpr.get(), /*DiscardedValue*/ false);
  2218. if (IncrExpr.isInvalid()) {
  2219. Diag(RangeLoc, diag::note_for_range_invalid_iterator)
  2220. << RangeLoc << 2 << BeginRangeRef.get()->getType() ;
  2221. NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
  2222. return StmtError();
  2223. }
  2224. // Build and check *__begin expression.
  2225. BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
  2226. VK_LValue, ColonLoc);
  2227. if (BeginRef.isInvalid())
  2228. return StmtError();
  2229. ExprResult DerefExpr = ActOnUnaryOp(S, ColonLoc, tok::star, BeginRef.get());
  2230. if (DerefExpr.isInvalid()) {
  2231. Diag(RangeLoc, diag::note_for_range_invalid_iterator)
  2232. << RangeLoc << 1 << BeginRangeRef.get()->getType();
  2233. NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
  2234. return StmtError();
  2235. }
  2236. // Attach *__begin as initializer for VD. Don't touch it if we're just
  2237. // trying to determine whether this would be a valid range.
  2238. if (!LoopVar->isInvalidDecl() && Kind != BFRK_Check) {
  2239. AddInitializerToDecl(LoopVar, DerefExpr.get(), /*DirectInit=*/false);
  2240. if (LoopVar->isInvalidDecl())
  2241. NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
  2242. }
  2243. }
  2244. // Don't bother to actually allocate the result if we're just trying to
  2245. // determine whether it would be valid.
  2246. if (Kind == BFRK_Check)
  2247. return StmtResult();
  2248. return new (Context) CXXForRangeStmt(
  2249. InitStmt, RangeDS, cast_or_null<DeclStmt>(BeginDeclStmt.get()),
  2250. cast_or_null<DeclStmt>(EndDeclStmt.get()), NotEqExpr.get(),
  2251. IncrExpr.get(), LoopVarDS, /*Body=*/nullptr, ForLoc, CoawaitLoc,
  2252. ColonLoc, RParenLoc);
  2253. }
  2254. /// FinishObjCForCollectionStmt - Attach the body to a objective-C foreach
  2255. /// statement.
  2256. StmtResult Sema::FinishObjCForCollectionStmt(Stmt *S, Stmt *B) {
  2257. if (!S || !B)
  2258. return StmtError();
  2259. ObjCForCollectionStmt * ForStmt = cast<ObjCForCollectionStmt>(S);
  2260. ForStmt->setBody(B);
  2261. return S;
  2262. }
  2263. // Warn when the loop variable is a const reference that creates a copy.
  2264. // Suggest using the non-reference type for copies. If a copy can be prevented
  2265. // suggest the const reference type that would do so.
  2266. // For instance, given "for (const &Foo : Range)", suggest
  2267. // "for (const Foo : Range)" to denote a copy is made for the loop. If
  2268. // possible, also suggest "for (const &Bar : Range)" if this type prevents
  2269. // the copy altogether.
  2270. static void DiagnoseForRangeReferenceVariableCopies(Sema &SemaRef,
  2271. const VarDecl *VD,
  2272. QualType RangeInitType) {
  2273. const Expr *InitExpr = VD->getInit();
  2274. if (!InitExpr)
  2275. return;
  2276. QualType VariableType = VD->getType();
  2277. if (auto Cleanups = dyn_cast<ExprWithCleanups>(InitExpr))
  2278. if (!Cleanups->cleanupsHaveSideEffects())
  2279. InitExpr = Cleanups->getSubExpr();
  2280. const MaterializeTemporaryExpr *MTE =
  2281. dyn_cast<MaterializeTemporaryExpr>(InitExpr);
  2282. // No copy made.
  2283. if (!MTE)
  2284. return;
  2285. const Expr *E = MTE->GetTemporaryExpr()->IgnoreImpCasts();
  2286. // Searching for either UnaryOperator for dereference of a pointer or
  2287. // CXXOperatorCallExpr for handling iterators.
  2288. while (!isa<CXXOperatorCallExpr>(E) && !isa<UnaryOperator>(E)) {
  2289. if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(E)) {
  2290. E = CCE->getArg(0);
  2291. } else if (const CXXMemberCallExpr *Call = dyn_cast<CXXMemberCallExpr>(E)) {
  2292. const MemberExpr *ME = cast<MemberExpr>(Call->getCallee());
  2293. E = ME->getBase();
  2294. } else {
  2295. const MaterializeTemporaryExpr *MTE = cast<MaterializeTemporaryExpr>(E);
  2296. E = MTE->GetTemporaryExpr();
  2297. }
  2298. E = E->IgnoreImpCasts();
  2299. }
  2300. bool ReturnsReference = false;
  2301. if (isa<UnaryOperator>(E)) {
  2302. ReturnsReference = true;
  2303. } else {
  2304. const CXXOperatorCallExpr *Call = cast<CXXOperatorCallExpr>(E);
  2305. const FunctionDecl *FD = Call->getDirectCallee();
  2306. QualType ReturnType = FD->getReturnType();
  2307. ReturnsReference = ReturnType->isReferenceType();
  2308. }
  2309. if (ReturnsReference) {
  2310. // Loop variable creates a temporary. Suggest either to go with
  2311. // non-reference loop variable to indicate a copy is made, or
  2312. // the correct time to bind a const reference.
  2313. SemaRef.Diag(VD->getLocation(), diag::warn_for_range_const_reference_copy)
  2314. << VD << VariableType << E->getType();
  2315. QualType NonReferenceType = VariableType.getNonReferenceType();
  2316. NonReferenceType.removeLocalConst();
  2317. QualType NewReferenceType =
  2318. SemaRef.Context.getLValueReferenceType(E->getType().withConst());
  2319. SemaRef.Diag(VD->getBeginLoc(), diag::note_use_type_or_non_reference)
  2320. << NonReferenceType << NewReferenceType << VD->getSourceRange();
  2321. } else {
  2322. // The range always returns a copy, so a temporary is always created.
  2323. // Suggest removing the reference from the loop variable.
  2324. SemaRef.Diag(VD->getLocation(), diag::warn_for_range_variable_always_copy)
  2325. << VD << RangeInitType;
  2326. QualType NonReferenceType = VariableType.getNonReferenceType();
  2327. NonReferenceType.removeLocalConst();
  2328. SemaRef.Diag(VD->getBeginLoc(), diag::note_use_non_reference_type)
  2329. << NonReferenceType << VD->getSourceRange();
  2330. }
  2331. }
  2332. // Warns when the loop variable can be changed to a reference type to
  2333. // prevent a copy. For instance, if given "for (const Foo x : Range)" suggest
  2334. // "for (const Foo &x : Range)" if this form does not make a copy.
  2335. static void DiagnoseForRangeConstVariableCopies(Sema &SemaRef,
  2336. const VarDecl *VD) {
  2337. const Expr *InitExpr = VD->getInit();
  2338. if (!InitExpr)
  2339. return;
  2340. QualType VariableType = VD->getType();
  2341. if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(InitExpr)) {
  2342. if (!CE->getConstructor()->isCopyConstructor())
  2343. return;
  2344. } else if (const CastExpr *CE = dyn_cast<CastExpr>(InitExpr)) {
  2345. if (CE->getCastKind() != CK_LValueToRValue)
  2346. return;
  2347. } else {
  2348. return;
  2349. }
  2350. // TODO: Determine a maximum size that a POD type can be before a diagnostic
  2351. // should be emitted. Also, only ignore POD types with trivial copy
  2352. // constructors.
  2353. if (VariableType.isPODType(SemaRef.Context))
  2354. return;
  2355. // Suggest changing from a const variable to a const reference variable
  2356. // if doing so will prevent a copy.
  2357. SemaRef.Diag(VD->getLocation(), diag::warn_for_range_copy)
  2358. << VD << VariableType << InitExpr->getType();
  2359. SemaRef.Diag(VD->getBeginLoc(), diag::note_use_reference_type)
  2360. << SemaRef.Context.getLValueReferenceType(VariableType)
  2361. << VD->getSourceRange();
  2362. }
  2363. /// DiagnoseForRangeVariableCopies - Diagnose three cases and fixes for them.
  2364. /// 1) for (const foo &x : foos) where foos only returns a copy. Suggest
  2365. /// using "const foo x" to show that a copy is made
  2366. /// 2) for (const bar &x : foos) where bar is a temporary initialized by bar.
  2367. /// Suggest either "const bar x" to keep the copying or "const foo& x" to
  2368. /// prevent the copy.
  2369. /// 3) for (const foo x : foos) where x is constructed from a reference foo.
  2370. /// Suggest "const foo &x" to prevent the copy.
  2371. static void DiagnoseForRangeVariableCopies(Sema &SemaRef,
  2372. const CXXForRangeStmt *ForStmt) {
  2373. if (SemaRef.Diags.isIgnored(diag::warn_for_range_const_reference_copy,
  2374. ForStmt->getBeginLoc()) &&
  2375. SemaRef.Diags.isIgnored(diag::warn_for_range_variable_always_copy,
  2376. ForStmt->getBeginLoc()) &&
  2377. SemaRef.Diags.isIgnored(diag::warn_for_range_copy,
  2378. ForStmt->getBeginLoc())) {
  2379. return;
  2380. }
  2381. const VarDecl *VD = ForStmt->getLoopVariable();
  2382. if (!VD)
  2383. return;
  2384. QualType VariableType = VD->getType();
  2385. if (VariableType->isIncompleteType())
  2386. return;
  2387. const Expr *InitExpr = VD->getInit();
  2388. if (!InitExpr)
  2389. return;
  2390. if (VariableType->isReferenceType()) {
  2391. DiagnoseForRangeReferenceVariableCopies(SemaRef, VD,
  2392. ForStmt->getRangeInit()->getType());
  2393. } else if (VariableType.isConstQualified()) {
  2394. DiagnoseForRangeConstVariableCopies(SemaRef, VD);
  2395. }
  2396. }
  2397. /// FinishCXXForRangeStmt - Attach the body to a C++0x for-range statement.
  2398. /// This is a separate step from ActOnCXXForRangeStmt because analysis of the
  2399. /// body cannot be performed until after the type of the range variable is
  2400. /// determined.
  2401. StmtResult Sema::FinishCXXForRangeStmt(Stmt *S, Stmt *B) {
  2402. if (!S || !B)
  2403. return StmtError();
  2404. if (isa<ObjCForCollectionStmt>(S))
  2405. return FinishObjCForCollectionStmt(S, B);
  2406. CXXForRangeStmt *ForStmt = cast<CXXForRangeStmt>(S);
  2407. ForStmt->setBody(B);
  2408. DiagnoseEmptyStmtBody(ForStmt->getRParenLoc(), B,
  2409. diag::warn_empty_range_based_for_body);
  2410. DiagnoseForRangeVariableCopies(*this, ForStmt);
  2411. return S;
  2412. }
  2413. StmtResult Sema::ActOnGotoStmt(SourceLocation GotoLoc,
  2414. SourceLocation LabelLoc,
  2415. LabelDecl *TheDecl) {
  2416. setFunctionHasBranchIntoScope();
  2417. TheDecl->markUsed(Context);
  2418. return new (Context) GotoStmt(TheDecl, GotoLoc, LabelLoc);
  2419. }
  2420. StmtResult
  2421. Sema::ActOnIndirectGotoStmt(SourceLocation GotoLoc, SourceLocation StarLoc,
  2422. Expr *E) {
  2423. // Convert operand to void*
  2424. if (!E->isTypeDependent()) {
  2425. QualType ETy = E->getType();
  2426. QualType DestTy = Context.getPointerType(Context.VoidTy.withConst());
  2427. ExprResult ExprRes = E;
  2428. AssignConvertType ConvTy =
  2429. CheckSingleAssignmentConstraints(DestTy, ExprRes);
  2430. if (ExprRes.isInvalid())
  2431. return StmtError();
  2432. E = ExprRes.get();
  2433. if (DiagnoseAssignmentResult(ConvTy, StarLoc, DestTy, ETy, E, AA_Passing))
  2434. return StmtError();
  2435. }
  2436. ExprResult ExprRes = ActOnFinishFullExpr(E, /*DiscardedValue*/ false);
  2437. if (ExprRes.isInvalid())
  2438. return StmtError();
  2439. E = ExprRes.get();
  2440. setFunctionHasIndirectGoto();
  2441. return new (Context) IndirectGotoStmt(GotoLoc, StarLoc, E);
  2442. }
  2443. static void CheckJumpOutOfSEHFinally(Sema &S, SourceLocation Loc,
  2444. const Scope &DestScope) {
  2445. if (!S.CurrentSEHFinally.empty() &&
  2446. DestScope.Contains(*S.CurrentSEHFinally.back())) {
  2447. S.Diag(Loc, diag::warn_jump_out_of_seh_finally);
  2448. }
  2449. }
  2450. StmtResult
  2451. Sema::ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope) {
  2452. Scope *S = CurScope->getContinueParent();
  2453. if (!S) {
  2454. // C99 6.8.6.2p1: A break shall appear only in or as a loop body.
  2455. return StmtError(Diag(ContinueLoc, diag::err_continue_not_in_loop));
  2456. }
  2457. CheckJumpOutOfSEHFinally(*this, ContinueLoc, *S);
  2458. return new (Context) ContinueStmt(ContinueLoc);
  2459. }
  2460. StmtResult
  2461. Sema::ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope) {
  2462. Scope *S = CurScope->getBreakParent();
  2463. if (!S) {
  2464. // C99 6.8.6.3p1: A break shall appear only in or as a switch/loop body.
  2465. return StmtError(Diag(BreakLoc, diag::err_break_not_in_loop_or_switch));
  2466. }
  2467. if (S->isOpenMPLoopScope())
  2468. return StmtError(Diag(BreakLoc, diag::err_omp_loop_cannot_use_stmt)
  2469. << "break");
  2470. CheckJumpOutOfSEHFinally(*this, BreakLoc, *S);
  2471. return new (Context) BreakStmt(BreakLoc);
  2472. }
  2473. /// Determine whether the given expression is a candidate for
  2474. /// copy elision in either a return statement or a throw expression.
  2475. ///
  2476. /// \param ReturnType If we're determining the copy elision candidate for
  2477. /// a return statement, this is the return type of the function. If we're
  2478. /// determining the copy elision candidate for a throw expression, this will
  2479. /// be a NULL type.
  2480. ///
  2481. /// \param E The expression being returned from the function or block, or
  2482. /// being thrown.
  2483. ///
  2484. /// \param CESK Whether we allow function parameters or
  2485. /// id-expressions that could be moved out of the function to be considered NRVO
  2486. /// candidates. C++ prohibits these for NRVO itself, but we re-use this logic to
  2487. /// determine whether we should try to move as part of a return or throw (which
  2488. /// does allow function parameters).
  2489. ///
  2490. /// \returns The NRVO candidate variable, if the return statement may use the
  2491. /// NRVO, or NULL if there is no such candidate.
  2492. VarDecl *Sema::getCopyElisionCandidate(QualType ReturnType, Expr *E,
  2493. CopyElisionSemanticsKind CESK) {
  2494. // - in a return statement in a function [where] ...
  2495. // ... the expression is the name of a non-volatile automatic object ...
  2496. DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E->IgnoreParens());
  2497. if (!DR || DR->refersToEnclosingVariableOrCapture())
  2498. return nullptr;
  2499. VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl());
  2500. if (!VD)
  2501. return nullptr;
  2502. if (isCopyElisionCandidate(ReturnType, VD, CESK))
  2503. return VD;
  2504. return nullptr;
  2505. }
  2506. bool Sema::isCopyElisionCandidate(QualType ReturnType, const VarDecl *VD,
  2507. CopyElisionSemanticsKind CESK) {
  2508. QualType VDType = VD->getType();
  2509. // - in a return statement in a function with ...
  2510. // ... a class return type ...
  2511. if (!ReturnType.isNull() && !ReturnType->isDependentType()) {
  2512. if (!ReturnType->isRecordType())
  2513. return false;
  2514. // ... the same cv-unqualified type as the function return type ...
  2515. // When considering moving this expression out, allow dissimilar types.
  2516. if (!(CESK & CES_AllowDifferentTypes) && !VDType->isDependentType() &&
  2517. !Context.hasSameUnqualifiedType(ReturnType, VDType))
  2518. return false;
  2519. }
  2520. // ...object (other than a function or catch-clause parameter)...
  2521. if (VD->getKind() != Decl::Var &&
  2522. !((CESK & CES_AllowParameters) && VD->getKind() == Decl::ParmVar))
  2523. return false;
  2524. if (!(CESK & CES_AllowExceptionVariables) && VD->isExceptionVariable())
  2525. return false;
  2526. // ...automatic...
  2527. if (!VD->hasLocalStorage()) return false;
  2528. // Return false if VD is a __block variable. We don't want to implicitly move
  2529. // out of a __block variable during a return because we cannot assume the
  2530. // variable will no longer be used.
  2531. if (VD->hasAttr<BlocksAttr>()) return false;
  2532. if (CESK & CES_AllowDifferentTypes)
  2533. return true;
  2534. // ...non-volatile...
  2535. if (VD->getType().isVolatileQualified()) return false;
  2536. // Variables with higher required alignment than their type's ABI
  2537. // alignment cannot use NRVO.
  2538. if (!VD->getType()->isDependentType() && VD->hasAttr<AlignedAttr>() &&
  2539. Context.getDeclAlign(VD) > Context.getTypeAlignInChars(VD->getType()))
  2540. return false;
  2541. return true;
  2542. }
  2543. /// Try to perform the initialization of a potentially-movable value,
  2544. /// which is the operand to a return or throw statement.
  2545. ///
  2546. /// This routine implements C++14 [class.copy]p32, which attempts to treat
  2547. /// returned lvalues as rvalues in certain cases (to prefer move construction),
  2548. /// then falls back to treating them as lvalues if that failed.
  2549. ///
  2550. /// \param ConvertingConstructorsOnly If true, follow [class.copy]p32 and reject
  2551. /// resolutions that find non-constructors, such as derived-to-base conversions
  2552. /// or `operator T()&&` member functions. If false, do consider such
  2553. /// conversion sequences.
  2554. ///
  2555. /// \param Res We will fill this in if move-initialization was possible.
  2556. /// If move-initialization is not possible, such that we must fall back to
  2557. /// treating the operand as an lvalue, we will leave Res in its original
  2558. /// invalid state.
  2559. static void TryMoveInitialization(Sema& S,
  2560. const InitializedEntity &Entity,
  2561. const VarDecl *NRVOCandidate,
  2562. QualType ResultType,
  2563. Expr *&Value,
  2564. bool ConvertingConstructorsOnly,
  2565. ExprResult &Res) {
  2566. ImplicitCastExpr AsRvalue(ImplicitCastExpr::OnStack, Value->getType(),
  2567. CK_NoOp, Value, VK_XValue);
  2568. Expr *InitExpr = &AsRvalue;
  2569. InitializationKind Kind = InitializationKind::CreateCopy(
  2570. Value->getBeginLoc(), Value->getBeginLoc());
  2571. InitializationSequence Seq(S, Entity, Kind, InitExpr);
  2572. if (!Seq)
  2573. return;
  2574. for (const InitializationSequence::Step &Step : Seq.steps()) {
  2575. if (Step.Kind != InitializationSequence::SK_ConstructorInitialization &&
  2576. Step.Kind != InitializationSequence::SK_UserConversion)
  2577. continue;
  2578. FunctionDecl *FD = Step.Function.Function;
  2579. if (ConvertingConstructorsOnly) {
  2580. if (isa<CXXConstructorDecl>(FD)) {
  2581. // C++14 [class.copy]p32:
  2582. // [...] If the first overload resolution fails or was not performed,
  2583. // or if the type of the first parameter of the selected constructor
  2584. // is not an rvalue reference to the object's type (possibly
  2585. // cv-qualified), overload resolution is performed again, considering
  2586. // the object as an lvalue.
  2587. const RValueReferenceType *RRefType =
  2588. FD->getParamDecl(0)->getType()->getAs<RValueReferenceType>();
  2589. if (!RRefType)
  2590. break;
  2591. if (!S.Context.hasSameUnqualifiedType(RRefType->getPointeeType(),
  2592. NRVOCandidate->getType()))
  2593. break;
  2594. } else {
  2595. continue;
  2596. }
  2597. } else {
  2598. if (isa<CXXConstructorDecl>(FD)) {
  2599. // Check that overload resolution selected a constructor taking an
  2600. // rvalue reference. If it selected an lvalue reference, then we
  2601. // didn't need to cast this thing to an rvalue in the first place.
  2602. if (!isa<RValueReferenceType>(FD->getParamDecl(0)->getType()))
  2603. break;
  2604. } else if (isa<CXXMethodDecl>(FD)) {
  2605. // Check that overload resolution selected a conversion operator
  2606. // taking an rvalue reference.
  2607. if (cast<CXXMethodDecl>(FD)->getRefQualifier() != RQ_RValue)
  2608. break;
  2609. } else {
  2610. continue;
  2611. }
  2612. }
  2613. // Promote "AsRvalue" to the heap, since we now need this
  2614. // expression node to persist.
  2615. Value = ImplicitCastExpr::Create(S.Context, Value->getType(), CK_NoOp,
  2616. Value, nullptr, VK_XValue);
  2617. // Complete type-checking the initialization of the return type
  2618. // using the constructor we found.
  2619. Res = Seq.Perform(S, Entity, Kind, Value);
  2620. }
  2621. }
  2622. /// Perform the initialization of a potentially-movable value, which
  2623. /// is the result of return value.
  2624. ///
  2625. /// This routine implements C++14 [class.copy]p32, which attempts to treat
  2626. /// returned lvalues as rvalues in certain cases (to prefer move construction),
  2627. /// then falls back to treating them as lvalues if that failed.
  2628. ExprResult
  2629. Sema::PerformMoveOrCopyInitialization(const InitializedEntity &Entity,
  2630. const VarDecl *NRVOCandidate,
  2631. QualType ResultType,
  2632. Expr *Value,
  2633. bool AllowNRVO) {
  2634. // C++14 [class.copy]p32:
  2635. // When the criteria for elision of a copy/move operation are met, but not for
  2636. // an exception-declaration, and the object to be copied is designated by an
  2637. // lvalue, or when the expression in a return statement is a (possibly
  2638. // parenthesized) id-expression that names an object with automatic storage
  2639. // duration declared in the body or parameter-declaration-clause of the
  2640. // innermost enclosing function or lambda-expression, overload resolution to
  2641. // select the constructor for the copy is first performed as if the object
  2642. // were designated by an rvalue.
  2643. ExprResult Res = ExprError();
  2644. if (AllowNRVO) {
  2645. bool AffectedByCWG1579 = false;
  2646. if (!NRVOCandidate) {
  2647. NRVOCandidate = getCopyElisionCandidate(ResultType, Value, CES_Default);
  2648. if (NRVOCandidate &&
  2649. !getDiagnostics().isIgnored(diag::warn_return_std_move_in_cxx11,
  2650. Value->getExprLoc())) {
  2651. const VarDecl *NRVOCandidateInCXX11 =
  2652. getCopyElisionCandidate(ResultType, Value, CES_FormerDefault);
  2653. AffectedByCWG1579 = (!NRVOCandidateInCXX11);
  2654. }
  2655. }
  2656. if (NRVOCandidate) {
  2657. TryMoveInitialization(*this, Entity, NRVOCandidate, ResultType, Value,
  2658. true, Res);
  2659. }
  2660. if (!Res.isInvalid() && AffectedByCWG1579) {
  2661. QualType QT = NRVOCandidate->getType();
  2662. if (QT.getNonReferenceType()
  2663. .getUnqualifiedType()
  2664. .isTriviallyCopyableType(Context)) {
  2665. // Adding 'std::move' around a trivially copyable variable is probably
  2666. // pointless. Don't suggest it.
  2667. } else {
  2668. // Common cases for this are returning unique_ptr<Derived> from a
  2669. // function of return type unique_ptr<Base>, or returning T from a
  2670. // function of return type Expected<T>. This is totally fine in a
  2671. // post-CWG1579 world, but was not fine before.
  2672. assert(!ResultType.isNull());
  2673. SmallString<32> Str;
  2674. Str += "std::move(";
  2675. Str += NRVOCandidate->getDeclName().getAsString();
  2676. Str += ")";
  2677. Diag(Value->getExprLoc(), diag::warn_return_std_move_in_cxx11)
  2678. << Value->getSourceRange()
  2679. << NRVOCandidate->getDeclName() << ResultType << QT;
  2680. Diag(Value->getExprLoc(), diag::note_add_std_move_in_cxx11)
  2681. << FixItHint::CreateReplacement(Value->getSourceRange(), Str);
  2682. }
  2683. } else if (Res.isInvalid() &&
  2684. !getDiagnostics().isIgnored(diag::warn_return_std_move,
  2685. Value->getExprLoc())) {
  2686. const VarDecl *FakeNRVOCandidate =
  2687. getCopyElisionCandidate(QualType(), Value, CES_AsIfByStdMove);
  2688. if (FakeNRVOCandidate) {
  2689. QualType QT = FakeNRVOCandidate->getType();
  2690. if (QT->isLValueReferenceType()) {
  2691. // Adding 'std::move' around an lvalue reference variable's name is
  2692. // dangerous. Don't suggest it.
  2693. } else if (QT.getNonReferenceType()
  2694. .getUnqualifiedType()
  2695. .isTriviallyCopyableType(Context)) {
  2696. // Adding 'std::move' around a trivially copyable variable is probably
  2697. // pointless. Don't suggest it.
  2698. } else {
  2699. ExprResult FakeRes = ExprError();
  2700. Expr *FakeValue = Value;
  2701. TryMoveInitialization(*this, Entity, FakeNRVOCandidate, ResultType,
  2702. FakeValue, false, FakeRes);
  2703. if (!FakeRes.isInvalid()) {
  2704. bool IsThrow =
  2705. (Entity.getKind() == InitializedEntity::EK_Exception);
  2706. SmallString<32> Str;
  2707. Str += "std::move(";
  2708. Str += FakeNRVOCandidate->getDeclName().getAsString();
  2709. Str += ")";
  2710. Diag(Value->getExprLoc(), diag::warn_return_std_move)
  2711. << Value->getSourceRange()
  2712. << FakeNRVOCandidate->getDeclName() << IsThrow;
  2713. Diag(Value->getExprLoc(), diag::note_add_std_move)
  2714. << FixItHint::CreateReplacement(Value->getSourceRange(), Str);
  2715. }
  2716. }
  2717. }
  2718. }
  2719. }
  2720. // Either we didn't meet the criteria for treating an lvalue as an rvalue,
  2721. // above, or overload resolution failed. Either way, we need to try
  2722. // (again) now with the return value expression as written.
  2723. if (Res.isInvalid())
  2724. Res = PerformCopyInitialization(Entity, SourceLocation(), Value);
  2725. return Res;
  2726. }
  2727. /// Determine whether the declared return type of the specified function
  2728. /// contains 'auto'.
  2729. static bool hasDeducedReturnType(FunctionDecl *FD) {
  2730. const FunctionProtoType *FPT =
  2731. FD->getTypeSourceInfo()->getType()->castAs<FunctionProtoType>();
  2732. return FPT->getReturnType()->isUndeducedType();
  2733. }
  2734. /// ActOnCapScopeReturnStmt - Utility routine to type-check return statements
  2735. /// for capturing scopes.
  2736. ///
  2737. StmtResult
  2738. Sema::ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
  2739. // If this is the first return we've seen, infer the return type.
  2740. // [expr.prim.lambda]p4 in C++11; block literals follow the same rules.
  2741. CapturingScopeInfo *CurCap = cast<CapturingScopeInfo>(getCurFunction());
  2742. QualType FnRetType = CurCap->ReturnType;
  2743. LambdaScopeInfo *CurLambda = dyn_cast<LambdaScopeInfo>(CurCap);
  2744. bool HasDeducedReturnType =
  2745. CurLambda && hasDeducedReturnType(CurLambda->CallOperator);
  2746. if (ExprEvalContexts.back().Context ==
  2747. ExpressionEvaluationContext::DiscardedStatement &&
  2748. (HasDeducedReturnType || CurCap->HasImplicitReturnType)) {
  2749. if (RetValExp) {
  2750. ExprResult ER =
  2751. ActOnFinishFullExpr(RetValExp, ReturnLoc, /*DiscardedValue*/ false);
  2752. if (ER.isInvalid())
  2753. return StmtError();
  2754. RetValExp = ER.get();
  2755. }
  2756. return ReturnStmt::Create(Context, ReturnLoc, RetValExp,
  2757. /* NRVOCandidate=*/nullptr);
  2758. }
  2759. if (HasDeducedReturnType) {
  2760. // In C++1y, the return type may involve 'auto'.
  2761. // FIXME: Blocks might have a return type of 'auto' explicitly specified.
  2762. FunctionDecl *FD = CurLambda->CallOperator;
  2763. if (CurCap->ReturnType.isNull())
  2764. CurCap->ReturnType = FD->getReturnType();
  2765. AutoType *AT = CurCap->ReturnType->getContainedAutoType();
  2766. assert(AT && "lost auto type from lambda return type");
  2767. if (DeduceFunctionTypeFromReturnExpr(FD, ReturnLoc, RetValExp, AT)) {
  2768. FD->setInvalidDecl();
  2769. return StmtError();
  2770. }
  2771. CurCap->ReturnType = FnRetType = FD->getReturnType();
  2772. } else if (CurCap->HasImplicitReturnType) {
  2773. // For blocks/lambdas with implicit return types, we check each return
  2774. // statement individually, and deduce the common return type when the block
  2775. // or lambda is completed.
  2776. // FIXME: Fold this into the 'auto' codepath above.
  2777. if (RetValExp && !isa<InitListExpr>(RetValExp)) {
  2778. ExprResult Result = DefaultFunctionArrayLvalueConversion(RetValExp);
  2779. if (Result.isInvalid())
  2780. return StmtError();
  2781. RetValExp = Result.get();
  2782. // DR1048: even prior to C++14, we should use the 'auto' deduction rules
  2783. // when deducing a return type for a lambda-expression (or by extension
  2784. // for a block). These rules differ from the stated C++11 rules only in
  2785. // that they remove top-level cv-qualifiers.
  2786. if (!CurContext->isDependentContext())
  2787. FnRetType = RetValExp->getType().getUnqualifiedType();
  2788. else
  2789. FnRetType = CurCap->ReturnType = Context.DependentTy;
  2790. } else {
  2791. if (RetValExp) {
  2792. // C++11 [expr.lambda.prim]p4 bans inferring the result from an
  2793. // initializer list, because it is not an expression (even
  2794. // though we represent it as one). We still deduce 'void'.
  2795. Diag(ReturnLoc, diag::err_lambda_return_init_list)
  2796. << RetValExp->getSourceRange();
  2797. }
  2798. FnRetType = Context.VoidTy;
  2799. }
  2800. // Although we'll properly infer the type of the block once it's completed,
  2801. // make sure we provide a return type now for better error recovery.
  2802. if (CurCap->ReturnType.isNull())
  2803. CurCap->ReturnType = FnRetType;
  2804. }
  2805. assert(!FnRetType.isNull());
  2806. if (BlockScopeInfo *CurBlock = dyn_cast<BlockScopeInfo>(CurCap)) {
  2807. if (CurBlock->FunctionType->getAs<FunctionType>()->getNoReturnAttr()) {
  2808. Diag(ReturnLoc, diag::err_noreturn_block_has_return_expr);
  2809. return StmtError();
  2810. }
  2811. } else if (CapturedRegionScopeInfo *CurRegion =
  2812. dyn_cast<CapturedRegionScopeInfo>(CurCap)) {
  2813. Diag(ReturnLoc, diag::err_return_in_captured_stmt) << CurRegion->getRegionName();
  2814. return StmtError();
  2815. } else {
  2816. assert(CurLambda && "unknown kind of captured scope");
  2817. if (CurLambda->CallOperator->getType()->getAs<FunctionType>()
  2818. ->getNoReturnAttr()) {
  2819. Diag(ReturnLoc, diag::err_noreturn_lambda_has_return_expr);
  2820. return StmtError();
  2821. }
  2822. }
  2823. // Otherwise, verify that this result type matches the previous one. We are
  2824. // pickier with blocks than for normal functions because we don't have GCC
  2825. // compatibility to worry about here.
  2826. const VarDecl *NRVOCandidate = nullptr;
  2827. if (FnRetType->isDependentType()) {
  2828. // Delay processing for now. TODO: there are lots of dependent
  2829. // types we can conclusively prove aren't void.
  2830. } else if (FnRetType->isVoidType()) {
  2831. if (RetValExp && !isa<InitListExpr>(RetValExp) &&
  2832. !(getLangOpts().CPlusPlus &&
  2833. (RetValExp->isTypeDependent() ||
  2834. RetValExp->getType()->isVoidType()))) {
  2835. if (!getLangOpts().CPlusPlus &&
  2836. RetValExp->getType()->isVoidType())
  2837. Diag(ReturnLoc, diag::ext_return_has_void_expr) << "literal" << 2;
  2838. else {
  2839. Diag(ReturnLoc, diag::err_return_block_has_expr);
  2840. RetValExp = nullptr;
  2841. }
  2842. }
  2843. } else if (!RetValExp) {
  2844. return StmtError(Diag(ReturnLoc, diag::err_block_return_missing_expr));
  2845. } else if (!RetValExp->isTypeDependent()) {
  2846. // we have a non-void block with an expression, continue checking
  2847. // C99 6.8.6.4p3(136): The return statement is not an assignment. The
  2848. // overlap restriction of subclause 6.5.16.1 does not apply to the case of
  2849. // function return.
  2850. // In C++ the return statement is handled via a copy initialization.
  2851. // the C version of which boils down to CheckSingleAssignmentConstraints.
  2852. NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, CES_Strict);
  2853. InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc,
  2854. FnRetType,
  2855. NRVOCandidate != nullptr);
  2856. ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate,
  2857. FnRetType, RetValExp);
  2858. if (Res.isInvalid()) {
  2859. // FIXME: Cleanup temporaries here, anyway?
  2860. return StmtError();
  2861. }
  2862. RetValExp = Res.get();
  2863. CheckReturnValExpr(RetValExp, FnRetType, ReturnLoc);
  2864. } else {
  2865. NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, CES_Strict);
  2866. }
  2867. if (RetValExp) {
  2868. ExprResult ER =
  2869. ActOnFinishFullExpr(RetValExp, ReturnLoc, /*DiscardedValue*/ false);
  2870. if (ER.isInvalid())
  2871. return StmtError();
  2872. RetValExp = ER.get();
  2873. }
  2874. auto *Result =
  2875. ReturnStmt::Create(Context, ReturnLoc, RetValExp, NRVOCandidate);
  2876. // If we need to check for the named return value optimization,
  2877. // or if we need to infer the return type,
  2878. // save the return statement in our scope for later processing.
  2879. if (CurCap->HasImplicitReturnType || NRVOCandidate)
  2880. FunctionScopes.back()->Returns.push_back(Result);
  2881. if (FunctionScopes.back()->FirstReturnLoc.isInvalid())
  2882. FunctionScopes.back()->FirstReturnLoc = ReturnLoc;
  2883. return Result;
  2884. }
  2885. namespace {
  2886. /// Marks all typedefs in all local classes in a type referenced.
  2887. ///
  2888. /// In a function like
  2889. /// auto f() {
  2890. /// struct S { typedef int a; };
  2891. /// return S();
  2892. /// }
  2893. ///
  2894. /// the local type escapes and could be referenced in some TUs but not in
  2895. /// others. Pretend that all local typedefs are always referenced, to not warn
  2896. /// on this. This isn't necessary if f has internal linkage, or the typedef
  2897. /// is private.
  2898. class LocalTypedefNameReferencer
  2899. : public RecursiveASTVisitor<LocalTypedefNameReferencer> {
  2900. public:
  2901. LocalTypedefNameReferencer(Sema &S) : S(S) {}
  2902. bool VisitRecordType(const RecordType *RT);
  2903. private:
  2904. Sema &S;
  2905. };
  2906. bool LocalTypedefNameReferencer::VisitRecordType(const RecordType *RT) {
  2907. auto *R = dyn_cast<CXXRecordDecl>(RT->getDecl());
  2908. if (!R || !R->isLocalClass() || !R->isLocalClass()->isExternallyVisible() ||
  2909. R->isDependentType())
  2910. return true;
  2911. for (auto *TmpD : R->decls())
  2912. if (auto *T = dyn_cast<TypedefNameDecl>(TmpD))
  2913. if (T->getAccess() != AS_private || R->hasFriends())
  2914. S.MarkAnyDeclReferenced(T->getLocation(), T, /*OdrUse=*/false);
  2915. return true;
  2916. }
  2917. }
  2918. TypeLoc Sema::getReturnTypeLoc(FunctionDecl *FD) const {
  2919. TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc().IgnoreParens();
  2920. while (auto ATL = TL.getAs<AttributedTypeLoc>())
  2921. TL = ATL.getModifiedLoc().IgnoreParens();
  2922. return TL.castAs<FunctionProtoTypeLoc>().getReturnLoc();
  2923. }
  2924. /// Deduce the return type for a function from a returned expression, per
  2925. /// C++1y [dcl.spec.auto]p6.
  2926. bool Sema::DeduceFunctionTypeFromReturnExpr(FunctionDecl *FD,
  2927. SourceLocation ReturnLoc,
  2928. Expr *&RetExpr,
  2929. AutoType *AT) {
  2930. // If this is the conversion function for a lambda, we choose to deduce it
  2931. // type from the corresponding call operator, not from the synthesized return
  2932. // statement within it. See Sema::DeduceReturnType.
  2933. if (isLambdaConversionOperator(FD))
  2934. return false;
  2935. TypeLoc OrigResultType = getReturnTypeLoc(FD);
  2936. QualType Deduced;
  2937. if (RetExpr && isa<InitListExpr>(RetExpr)) {
  2938. // If the deduction is for a return statement and the initializer is
  2939. // a braced-init-list, the program is ill-formed.
  2940. Diag(RetExpr->getExprLoc(),
  2941. getCurLambda() ? diag::err_lambda_return_init_list
  2942. : diag::err_auto_fn_return_init_list)
  2943. << RetExpr->getSourceRange();
  2944. return true;
  2945. }
  2946. if (FD->isDependentContext()) {
  2947. // C++1y [dcl.spec.auto]p12:
  2948. // Return type deduction [...] occurs when the definition is
  2949. // instantiated even if the function body contains a return
  2950. // statement with a non-type-dependent operand.
  2951. assert(AT->isDeduced() && "should have deduced to dependent type");
  2952. return false;
  2953. }
  2954. if (RetExpr) {
  2955. // Otherwise, [...] deduce a value for U using the rules of template
  2956. // argument deduction.
  2957. DeduceAutoResult DAR = DeduceAutoType(OrigResultType, RetExpr, Deduced);
  2958. if (DAR == DAR_Failed && !FD->isInvalidDecl())
  2959. Diag(RetExpr->getExprLoc(), diag::err_auto_fn_deduction_failure)
  2960. << OrigResultType.getType() << RetExpr->getType();
  2961. if (DAR != DAR_Succeeded)
  2962. return true;
  2963. // If a local type is part of the returned type, mark its fields as
  2964. // referenced.
  2965. LocalTypedefNameReferencer Referencer(*this);
  2966. Referencer.TraverseType(RetExpr->getType());
  2967. } else {
  2968. // In the case of a return with no operand, the initializer is considered
  2969. // to be void().
  2970. //
  2971. // Deduction here can only succeed if the return type is exactly 'cv auto'
  2972. // or 'decltype(auto)', so just check for that case directly.
  2973. if (!OrigResultType.getType()->getAs<AutoType>()) {
  2974. Diag(ReturnLoc, diag::err_auto_fn_return_void_but_not_auto)
  2975. << OrigResultType.getType();
  2976. return true;
  2977. }
  2978. // We always deduce U = void in this case.
  2979. Deduced = SubstAutoType(OrigResultType.getType(), Context.VoidTy);
  2980. if (Deduced.isNull())
  2981. return true;
  2982. }
  2983. // If a function with a declared return type that contains a placeholder type
  2984. // has multiple return statements, the return type is deduced for each return
  2985. // statement. [...] if the type deduced is not the same in each deduction,
  2986. // the program is ill-formed.
  2987. QualType DeducedT = AT->getDeducedType();
  2988. if (!DeducedT.isNull() && !FD->isInvalidDecl()) {
  2989. AutoType *NewAT = Deduced->getContainedAutoType();
  2990. // It is possible that NewAT->getDeducedType() is null. When that happens,
  2991. // we should not crash, instead we ignore this deduction.
  2992. if (NewAT->getDeducedType().isNull())
  2993. return false;
  2994. CanQualType OldDeducedType = Context.getCanonicalFunctionResultType(
  2995. DeducedT);
  2996. CanQualType NewDeducedType = Context.getCanonicalFunctionResultType(
  2997. NewAT->getDeducedType());
  2998. if (!FD->isDependentContext() && OldDeducedType != NewDeducedType) {
  2999. const LambdaScopeInfo *LambdaSI = getCurLambda();
  3000. if (LambdaSI && LambdaSI->HasImplicitReturnType) {
  3001. Diag(ReturnLoc, diag::err_typecheck_missing_return_type_incompatible)
  3002. << NewAT->getDeducedType() << DeducedT
  3003. << true /*IsLambda*/;
  3004. } else {
  3005. Diag(ReturnLoc, diag::err_auto_fn_different_deductions)
  3006. << (AT->isDecltypeAuto() ? 1 : 0)
  3007. << NewAT->getDeducedType() << DeducedT;
  3008. }
  3009. return true;
  3010. }
  3011. } else if (!FD->isInvalidDecl()) {
  3012. // Update all declarations of the function to have the deduced return type.
  3013. Context.adjustDeducedFunctionResultType(FD, Deduced);
  3014. }
  3015. return false;
  3016. }
  3017. StmtResult
  3018. Sema::ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
  3019. Scope *CurScope) {
  3020. StmtResult R = BuildReturnStmt(ReturnLoc, RetValExp);
  3021. if (R.isInvalid() || ExprEvalContexts.back().Context ==
  3022. ExpressionEvaluationContext::DiscardedStatement)
  3023. return R;
  3024. if (VarDecl *VD =
  3025. const_cast<VarDecl*>(cast<ReturnStmt>(R.get())->getNRVOCandidate())) {
  3026. CurScope->addNRVOCandidate(VD);
  3027. } else {
  3028. CurScope->setNoNRVO();
  3029. }
  3030. CheckJumpOutOfSEHFinally(*this, ReturnLoc, *CurScope->getFnParent());
  3031. return R;
  3032. }
  3033. StmtResult Sema::BuildReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
  3034. // Check for unexpanded parameter packs.
  3035. if (RetValExp && DiagnoseUnexpandedParameterPack(RetValExp))
  3036. return StmtError();
  3037. if (isa<CapturingScopeInfo>(getCurFunction()))
  3038. return ActOnCapScopeReturnStmt(ReturnLoc, RetValExp);
  3039. QualType FnRetType;
  3040. QualType RelatedRetType;
  3041. const AttrVec *Attrs = nullptr;
  3042. bool isObjCMethod = false;
  3043. if (const FunctionDecl *FD = getCurFunctionDecl()) {
  3044. FnRetType = FD->getReturnType();
  3045. if (FD->hasAttrs())
  3046. Attrs = &FD->getAttrs();
  3047. if (FD->isNoReturn())
  3048. Diag(ReturnLoc, diag::warn_noreturn_function_has_return_expr)
  3049. << FD->getDeclName();
  3050. if (FD->isMain() && RetValExp)
  3051. if (isa<CXXBoolLiteralExpr>(RetValExp))
  3052. Diag(ReturnLoc, diag::warn_main_returns_bool_literal)
  3053. << RetValExp->getSourceRange();
  3054. } else if (ObjCMethodDecl *MD = getCurMethodDecl()) {
  3055. FnRetType = MD->getReturnType();
  3056. isObjCMethod = true;
  3057. if (MD->hasAttrs())
  3058. Attrs = &MD->getAttrs();
  3059. if (MD->hasRelatedResultType() && MD->getClassInterface()) {
  3060. // In the implementation of a method with a related return type, the
  3061. // type used to type-check the validity of return statements within the
  3062. // method body is a pointer to the type of the class being implemented.
  3063. RelatedRetType = Context.getObjCInterfaceType(MD->getClassInterface());
  3064. RelatedRetType = Context.getObjCObjectPointerType(RelatedRetType);
  3065. }
  3066. } else // If we don't have a function/method context, bail.
  3067. return StmtError();
  3068. // C++1z: discarded return statements are not considered when deducing a
  3069. // return type.
  3070. if (ExprEvalContexts.back().Context ==
  3071. ExpressionEvaluationContext::DiscardedStatement &&
  3072. FnRetType->getContainedAutoType()) {
  3073. if (RetValExp) {
  3074. ExprResult ER =
  3075. ActOnFinishFullExpr(RetValExp, ReturnLoc, /*DiscardedValue*/ false);
  3076. if (ER.isInvalid())
  3077. return StmtError();
  3078. RetValExp = ER.get();
  3079. }
  3080. return ReturnStmt::Create(Context, ReturnLoc, RetValExp,
  3081. /* NRVOCandidate=*/nullptr);
  3082. }
  3083. // FIXME: Add a flag to the ScopeInfo to indicate whether we're performing
  3084. // deduction.
  3085. if (getLangOpts().CPlusPlus14) {
  3086. if (AutoType *AT = FnRetType->getContainedAutoType()) {
  3087. FunctionDecl *FD = cast<FunctionDecl>(CurContext);
  3088. if (DeduceFunctionTypeFromReturnExpr(FD, ReturnLoc, RetValExp, AT)) {
  3089. FD->setInvalidDecl();
  3090. return StmtError();
  3091. } else {
  3092. FnRetType = FD->getReturnType();
  3093. }
  3094. }
  3095. }
  3096. bool HasDependentReturnType = FnRetType->isDependentType();
  3097. ReturnStmt *Result = nullptr;
  3098. if (FnRetType->isVoidType()) {
  3099. if (RetValExp) {
  3100. if (isa<InitListExpr>(RetValExp)) {
  3101. // We simply never allow init lists as the return value of void
  3102. // functions. This is compatible because this was never allowed before,
  3103. // so there's no legacy code to deal with.
  3104. NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
  3105. int FunctionKind = 0;
  3106. if (isa<ObjCMethodDecl>(CurDecl))
  3107. FunctionKind = 1;
  3108. else if (isa<CXXConstructorDecl>(CurDecl))
  3109. FunctionKind = 2;
  3110. else if (isa<CXXDestructorDecl>(CurDecl))
  3111. FunctionKind = 3;
  3112. Diag(ReturnLoc, diag::err_return_init_list)
  3113. << CurDecl->getDeclName() << FunctionKind
  3114. << RetValExp->getSourceRange();
  3115. // Drop the expression.
  3116. RetValExp = nullptr;
  3117. } else if (!RetValExp->isTypeDependent()) {
  3118. // C99 6.8.6.4p1 (ext_ since GCC warns)
  3119. unsigned D = diag::ext_return_has_expr;
  3120. if (RetValExp->getType()->isVoidType()) {
  3121. NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
  3122. if (isa<CXXConstructorDecl>(CurDecl) ||
  3123. isa<CXXDestructorDecl>(CurDecl))
  3124. D = diag::err_ctor_dtor_returns_void;
  3125. else
  3126. D = diag::ext_return_has_void_expr;
  3127. }
  3128. else {
  3129. ExprResult Result = RetValExp;
  3130. Result = IgnoredValueConversions(Result.get());
  3131. if (Result.isInvalid())
  3132. return StmtError();
  3133. RetValExp = Result.get();
  3134. RetValExp = ImpCastExprToType(RetValExp,
  3135. Context.VoidTy, CK_ToVoid).get();
  3136. }
  3137. // return of void in constructor/destructor is illegal in C++.
  3138. if (D == diag::err_ctor_dtor_returns_void) {
  3139. NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
  3140. Diag(ReturnLoc, D)
  3141. << CurDecl->getDeclName() << isa<CXXDestructorDecl>(CurDecl)
  3142. << RetValExp->getSourceRange();
  3143. }
  3144. // return (some void expression); is legal in C++.
  3145. else if (D != diag::ext_return_has_void_expr ||
  3146. !getLangOpts().CPlusPlus) {
  3147. NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
  3148. int FunctionKind = 0;
  3149. if (isa<ObjCMethodDecl>(CurDecl))
  3150. FunctionKind = 1;
  3151. else if (isa<CXXConstructorDecl>(CurDecl))
  3152. FunctionKind = 2;
  3153. else if (isa<CXXDestructorDecl>(CurDecl))
  3154. FunctionKind = 3;
  3155. Diag(ReturnLoc, D)
  3156. << CurDecl->getDeclName() << FunctionKind
  3157. << RetValExp->getSourceRange();
  3158. }
  3159. }
  3160. if (RetValExp) {
  3161. ExprResult ER =
  3162. ActOnFinishFullExpr(RetValExp, ReturnLoc, /*DiscardedValue*/ false);
  3163. if (ER.isInvalid())
  3164. return StmtError();
  3165. RetValExp = ER.get();
  3166. }
  3167. }
  3168. Result = ReturnStmt::Create(Context, ReturnLoc, RetValExp,
  3169. /* NRVOCandidate=*/nullptr);
  3170. } else if (!RetValExp && !HasDependentReturnType) {
  3171. FunctionDecl *FD = getCurFunctionDecl();
  3172. unsigned DiagID;
  3173. if (getLangOpts().CPlusPlus11 && FD && FD->isConstexpr()) {
  3174. // C++11 [stmt.return]p2
  3175. DiagID = diag::err_constexpr_return_missing_expr;
  3176. FD->setInvalidDecl();
  3177. } else if (getLangOpts().C99) {
  3178. // C99 6.8.6.4p1 (ext_ since GCC warns)
  3179. DiagID = diag::ext_return_missing_expr;
  3180. } else {
  3181. // C90 6.6.6.4p4
  3182. DiagID = diag::warn_return_missing_expr;
  3183. }
  3184. if (FD)
  3185. Diag(ReturnLoc, DiagID) << FD->getIdentifier() << 0/*fn*/;
  3186. else
  3187. Diag(ReturnLoc, DiagID) << getCurMethodDecl()->getDeclName() << 1/*meth*/;
  3188. Result = ReturnStmt::Create(Context, ReturnLoc, /* RetExpr=*/nullptr,
  3189. /* NRVOCandidate=*/nullptr);
  3190. } else {
  3191. assert(RetValExp || HasDependentReturnType);
  3192. const VarDecl *NRVOCandidate = nullptr;
  3193. QualType RetType = RelatedRetType.isNull() ? FnRetType : RelatedRetType;
  3194. // C99 6.8.6.4p3(136): The return statement is not an assignment. The
  3195. // overlap restriction of subclause 6.5.16.1 does not apply to the case of
  3196. // function return.
  3197. // In C++ the return statement is handled via a copy initialization,
  3198. // the C version of which boils down to CheckSingleAssignmentConstraints.
  3199. if (RetValExp)
  3200. NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, CES_Strict);
  3201. if (!HasDependentReturnType && !RetValExp->isTypeDependent()) {
  3202. // we have a non-void function with an expression, continue checking
  3203. InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc,
  3204. RetType,
  3205. NRVOCandidate != nullptr);
  3206. ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate,
  3207. RetType, RetValExp);
  3208. if (Res.isInvalid()) {
  3209. // FIXME: Clean up temporaries here anyway?
  3210. return StmtError();
  3211. }
  3212. RetValExp = Res.getAs<Expr>();
  3213. // If we have a related result type, we need to implicitly
  3214. // convert back to the formal result type. We can't pretend to
  3215. // initialize the result again --- we might end double-retaining
  3216. // --- so instead we initialize a notional temporary.
  3217. if (!RelatedRetType.isNull()) {
  3218. Entity = InitializedEntity::InitializeRelatedResult(getCurMethodDecl(),
  3219. FnRetType);
  3220. Res = PerformCopyInitialization(Entity, ReturnLoc, RetValExp);
  3221. if (Res.isInvalid()) {
  3222. // FIXME: Clean up temporaries here anyway?
  3223. return StmtError();
  3224. }
  3225. RetValExp = Res.getAs<Expr>();
  3226. }
  3227. CheckReturnValExpr(RetValExp, FnRetType, ReturnLoc, isObjCMethod, Attrs,
  3228. getCurFunctionDecl());
  3229. }
  3230. if (RetValExp) {
  3231. ExprResult ER =
  3232. ActOnFinishFullExpr(RetValExp, ReturnLoc, /*DiscardedValue*/ false);
  3233. if (ER.isInvalid())
  3234. return StmtError();
  3235. RetValExp = ER.get();
  3236. }
  3237. Result = ReturnStmt::Create(Context, ReturnLoc, RetValExp, NRVOCandidate);
  3238. }
  3239. // If we need to check for the named return value optimization, save the
  3240. // return statement in our scope for later processing.
  3241. if (Result->getNRVOCandidate())
  3242. FunctionScopes.back()->Returns.push_back(Result);
  3243. if (FunctionScopes.back()->FirstReturnLoc.isInvalid())
  3244. FunctionScopes.back()->FirstReturnLoc = ReturnLoc;
  3245. return Result;
  3246. }
  3247. StmtResult
  3248. Sema::ActOnObjCAtCatchStmt(SourceLocation AtLoc,
  3249. SourceLocation RParen, Decl *Parm,
  3250. Stmt *Body) {
  3251. VarDecl *Var = cast_or_null<VarDecl>(Parm);
  3252. if (Var && Var->isInvalidDecl())
  3253. return StmtError();
  3254. return new (Context) ObjCAtCatchStmt(AtLoc, RParen, Var, Body);
  3255. }
  3256. StmtResult
  3257. Sema::ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body) {
  3258. return new (Context) ObjCAtFinallyStmt(AtLoc, Body);
  3259. }
  3260. StmtResult
  3261. Sema::ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try,
  3262. MultiStmtArg CatchStmts, Stmt *Finally) {
  3263. if (!getLangOpts().ObjCExceptions)
  3264. Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@try";
  3265. setFunctionHasBranchProtectedScope();
  3266. unsigned NumCatchStmts = CatchStmts.size();
  3267. return ObjCAtTryStmt::Create(Context, AtLoc, Try, CatchStmts.data(),
  3268. NumCatchStmts, Finally);
  3269. }
  3270. StmtResult Sema::BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw) {
  3271. if (Throw) {
  3272. ExprResult Result = DefaultLvalueConversion(Throw);
  3273. if (Result.isInvalid())
  3274. return StmtError();
  3275. Result = ActOnFinishFullExpr(Result.get(), /*DiscardedValue*/ false);
  3276. if (Result.isInvalid())
  3277. return StmtError();
  3278. Throw = Result.get();
  3279. QualType ThrowType = Throw->getType();
  3280. // Make sure the expression type is an ObjC pointer or "void *".
  3281. if (!ThrowType->isDependentType() &&
  3282. !ThrowType->isObjCObjectPointerType()) {
  3283. const PointerType *PT = ThrowType->getAs<PointerType>();
  3284. if (!PT || !PT->getPointeeType()->isVoidType())
  3285. return StmtError(Diag(AtLoc, diag::err_objc_throw_expects_object)
  3286. << Throw->getType() << Throw->getSourceRange());
  3287. }
  3288. }
  3289. return new (Context) ObjCAtThrowStmt(AtLoc, Throw);
  3290. }
  3291. StmtResult
  3292. Sema::ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw,
  3293. Scope *CurScope) {
  3294. if (!getLangOpts().ObjCExceptions)
  3295. Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@throw";
  3296. if (!Throw) {
  3297. // @throw without an expression designates a rethrow (which must occur
  3298. // in the context of an @catch clause).
  3299. Scope *AtCatchParent = CurScope;
  3300. while (AtCatchParent && !AtCatchParent->isAtCatchScope())
  3301. AtCatchParent = AtCatchParent->getParent();
  3302. if (!AtCatchParent)
  3303. return StmtError(Diag(AtLoc, diag::err_rethrow_used_outside_catch));
  3304. }
  3305. return BuildObjCAtThrowStmt(AtLoc, Throw);
  3306. }
  3307. ExprResult
  3308. Sema::ActOnObjCAtSynchronizedOperand(SourceLocation atLoc, Expr *operand) {
  3309. ExprResult result = DefaultLvalueConversion(operand);
  3310. if (result.isInvalid())
  3311. return ExprError();
  3312. operand = result.get();
  3313. // Make sure the expression type is an ObjC pointer or "void *".
  3314. QualType type = operand->getType();
  3315. if (!type->isDependentType() &&
  3316. !type->isObjCObjectPointerType()) {
  3317. const PointerType *pointerType = type->getAs<PointerType>();
  3318. if (!pointerType || !pointerType->getPointeeType()->isVoidType()) {
  3319. if (getLangOpts().CPlusPlus) {
  3320. if (RequireCompleteType(atLoc, type,
  3321. diag::err_incomplete_receiver_type))
  3322. return Diag(atLoc, diag::err_objc_synchronized_expects_object)
  3323. << type << operand->getSourceRange();
  3324. ExprResult result = PerformContextuallyConvertToObjCPointer(operand);
  3325. if (result.isInvalid())
  3326. return ExprError();
  3327. if (!result.isUsable())
  3328. return Diag(atLoc, diag::err_objc_synchronized_expects_object)
  3329. << type << operand->getSourceRange();
  3330. operand = result.get();
  3331. } else {
  3332. return Diag(atLoc, diag::err_objc_synchronized_expects_object)
  3333. << type << operand->getSourceRange();
  3334. }
  3335. }
  3336. }
  3337. // The operand to @synchronized is a full-expression.
  3338. return ActOnFinishFullExpr(operand, /*DiscardedValue*/ false);
  3339. }
  3340. StmtResult
  3341. Sema::ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc, Expr *SyncExpr,
  3342. Stmt *SyncBody) {
  3343. // We can't jump into or indirect-jump out of a @synchronized block.
  3344. setFunctionHasBranchProtectedScope();
  3345. return new (Context) ObjCAtSynchronizedStmt(AtLoc, SyncExpr, SyncBody);
  3346. }
  3347. /// ActOnCXXCatchBlock - Takes an exception declaration and a handler block
  3348. /// and creates a proper catch handler from them.
  3349. StmtResult
  3350. Sema::ActOnCXXCatchBlock(SourceLocation CatchLoc, Decl *ExDecl,
  3351. Stmt *HandlerBlock) {
  3352. // There's nothing to test that ActOnExceptionDecl didn't already test.
  3353. return new (Context)
  3354. CXXCatchStmt(CatchLoc, cast_or_null<VarDecl>(ExDecl), HandlerBlock);
  3355. }
  3356. StmtResult
  3357. Sema::ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body) {
  3358. setFunctionHasBranchProtectedScope();
  3359. return new (Context) ObjCAutoreleasePoolStmt(AtLoc, Body);
  3360. }
  3361. namespace {
  3362. class CatchHandlerType {
  3363. QualType QT;
  3364. unsigned IsPointer : 1;
  3365. // This is a special constructor to be used only with DenseMapInfo's
  3366. // getEmptyKey() and getTombstoneKey() functions.
  3367. friend struct llvm::DenseMapInfo<CatchHandlerType>;
  3368. enum Unique { ForDenseMap };
  3369. CatchHandlerType(QualType QT, Unique) : QT(QT), IsPointer(false) {}
  3370. public:
  3371. /// Used when creating a CatchHandlerType from a handler type; will determine
  3372. /// whether the type is a pointer or reference and will strip off the top
  3373. /// level pointer and cv-qualifiers.
  3374. CatchHandlerType(QualType Q) : QT(Q), IsPointer(false) {
  3375. if (QT->isPointerType())
  3376. IsPointer = true;
  3377. if (IsPointer || QT->isReferenceType())
  3378. QT = QT->getPointeeType();
  3379. QT = QT.getUnqualifiedType();
  3380. }
  3381. /// Used when creating a CatchHandlerType from a base class type; pretends the
  3382. /// type passed in had the pointer qualifier, does not need to get an
  3383. /// unqualified type.
  3384. CatchHandlerType(QualType QT, bool IsPointer)
  3385. : QT(QT), IsPointer(IsPointer) {}
  3386. QualType underlying() const { return QT; }
  3387. bool isPointer() const { return IsPointer; }
  3388. friend bool operator==(const CatchHandlerType &LHS,
  3389. const CatchHandlerType &RHS) {
  3390. // If the pointer qualification does not match, we can return early.
  3391. if (LHS.IsPointer != RHS.IsPointer)
  3392. return false;
  3393. // Otherwise, check the underlying type without cv-qualifiers.
  3394. return LHS.QT == RHS.QT;
  3395. }
  3396. };
  3397. } // namespace
  3398. namespace llvm {
  3399. template <> struct DenseMapInfo<CatchHandlerType> {
  3400. static CatchHandlerType getEmptyKey() {
  3401. return CatchHandlerType(DenseMapInfo<QualType>::getEmptyKey(),
  3402. CatchHandlerType::ForDenseMap);
  3403. }
  3404. static CatchHandlerType getTombstoneKey() {
  3405. return CatchHandlerType(DenseMapInfo<QualType>::getTombstoneKey(),
  3406. CatchHandlerType::ForDenseMap);
  3407. }
  3408. static unsigned getHashValue(const CatchHandlerType &Base) {
  3409. return DenseMapInfo<QualType>::getHashValue(Base.underlying());
  3410. }
  3411. static bool isEqual(const CatchHandlerType &LHS,
  3412. const CatchHandlerType &RHS) {
  3413. return LHS == RHS;
  3414. }
  3415. };
  3416. }
  3417. namespace {
  3418. class CatchTypePublicBases {
  3419. ASTContext &Ctx;
  3420. const llvm::DenseMap<CatchHandlerType, CXXCatchStmt *> &TypesToCheck;
  3421. const bool CheckAgainstPointer;
  3422. CXXCatchStmt *FoundHandler;
  3423. CanQualType FoundHandlerType;
  3424. public:
  3425. CatchTypePublicBases(
  3426. ASTContext &Ctx,
  3427. const llvm::DenseMap<CatchHandlerType, CXXCatchStmt *> &T, bool C)
  3428. : Ctx(Ctx), TypesToCheck(T), CheckAgainstPointer(C),
  3429. FoundHandler(nullptr) {}
  3430. CXXCatchStmt *getFoundHandler() const { return FoundHandler; }
  3431. CanQualType getFoundHandlerType() const { return FoundHandlerType; }
  3432. bool operator()(const CXXBaseSpecifier *S, CXXBasePath &) {
  3433. if (S->getAccessSpecifier() == AccessSpecifier::AS_public) {
  3434. CatchHandlerType Check(S->getType(), CheckAgainstPointer);
  3435. const auto &M = TypesToCheck;
  3436. auto I = M.find(Check);
  3437. if (I != M.end()) {
  3438. FoundHandler = I->second;
  3439. FoundHandlerType = Ctx.getCanonicalType(S->getType());
  3440. return true;
  3441. }
  3442. }
  3443. return false;
  3444. }
  3445. };
  3446. }
  3447. /// ActOnCXXTryBlock - Takes a try compound-statement and a number of
  3448. /// handlers and creates a try statement from them.
  3449. StmtResult Sema::ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock,
  3450. ArrayRef<Stmt *> Handlers) {
  3451. // Don't report an error if 'try' is used in system headers.
  3452. if (!getLangOpts().CXXExceptions &&
  3453. !getSourceManager().isInSystemHeader(TryLoc) && !getLangOpts().CUDA) {
  3454. // Delay error emission for the OpenMP device code.
  3455. targetDiag(TryLoc, diag::err_exceptions_disabled) << "try";
  3456. }
  3457. // Exceptions aren't allowed in CUDA device code.
  3458. if (getLangOpts().CUDA)
  3459. CUDADiagIfDeviceCode(TryLoc, diag::err_cuda_device_exceptions)
  3460. << "try" << CurrentCUDATarget();
  3461. if (getCurScope() && getCurScope()->isOpenMPSimdDirectiveScope())
  3462. Diag(TryLoc, diag::err_omp_simd_region_cannot_use_stmt) << "try";
  3463. sema::FunctionScopeInfo *FSI = getCurFunction();
  3464. // C++ try is incompatible with SEH __try.
  3465. if (!getLangOpts().Borland && FSI->FirstSEHTryLoc.isValid()) {
  3466. Diag(TryLoc, diag::err_mixing_cxx_try_seh_try);
  3467. Diag(FSI->FirstSEHTryLoc, diag::note_conflicting_try_here) << "'__try'";
  3468. }
  3469. const unsigned NumHandlers = Handlers.size();
  3470. assert(!Handlers.empty() &&
  3471. "The parser shouldn't call this if there are no handlers.");
  3472. llvm::DenseMap<CatchHandlerType, CXXCatchStmt *> HandledTypes;
  3473. for (unsigned i = 0; i < NumHandlers; ++i) {
  3474. CXXCatchStmt *H = cast<CXXCatchStmt>(Handlers[i]);
  3475. // Diagnose when the handler is a catch-all handler, but it isn't the last
  3476. // handler for the try block. [except.handle]p5. Also, skip exception
  3477. // declarations that are invalid, since we can't usefully report on them.
  3478. if (!H->getExceptionDecl()) {
  3479. if (i < NumHandlers - 1)
  3480. return StmtError(Diag(H->getBeginLoc(), diag::err_early_catch_all));
  3481. continue;
  3482. } else if (H->getExceptionDecl()->isInvalidDecl())
  3483. continue;
  3484. // Walk the type hierarchy to diagnose when this type has already been
  3485. // handled (duplication), or cannot be handled (derivation inversion). We
  3486. // ignore top-level cv-qualifiers, per [except.handle]p3
  3487. CatchHandlerType HandlerCHT =
  3488. (QualType)Context.getCanonicalType(H->getCaughtType());
  3489. // We can ignore whether the type is a reference or a pointer; we need the
  3490. // underlying declaration type in order to get at the underlying record
  3491. // decl, if there is one.
  3492. QualType Underlying = HandlerCHT.underlying();
  3493. if (auto *RD = Underlying->getAsCXXRecordDecl()) {
  3494. if (!RD->hasDefinition())
  3495. continue;
  3496. // Check that none of the public, unambiguous base classes are in the
  3497. // map ([except.handle]p1). Give the base classes the same pointer
  3498. // qualification as the original type we are basing off of. This allows
  3499. // comparison against the handler type using the same top-level pointer
  3500. // as the original type.
  3501. CXXBasePaths Paths;
  3502. Paths.setOrigin(RD);
  3503. CatchTypePublicBases CTPB(Context, HandledTypes, HandlerCHT.isPointer());
  3504. if (RD->lookupInBases(CTPB, Paths)) {
  3505. const CXXCatchStmt *Problem = CTPB.getFoundHandler();
  3506. if (!Paths.isAmbiguous(CTPB.getFoundHandlerType())) {
  3507. Diag(H->getExceptionDecl()->getTypeSpecStartLoc(),
  3508. diag::warn_exception_caught_by_earlier_handler)
  3509. << H->getCaughtType();
  3510. Diag(Problem->getExceptionDecl()->getTypeSpecStartLoc(),
  3511. diag::note_previous_exception_handler)
  3512. << Problem->getCaughtType();
  3513. }
  3514. }
  3515. }
  3516. // Add the type the list of ones we have handled; diagnose if we've already
  3517. // handled it.
  3518. auto R = HandledTypes.insert(std::make_pair(H->getCaughtType(), H));
  3519. if (!R.second) {
  3520. const CXXCatchStmt *Problem = R.first->second;
  3521. Diag(H->getExceptionDecl()->getTypeSpecStartLoc(),
  3522. diag::warn_exception_caught_by_earlier_handler)
  3523. << H->getCaughtType();
  3524. Diag(Problem->getExceptionDecl()->getTypeSpecStartLoc(),
  3525. diag::note_previous_exception_handler)
  3526. << Problem->getCaughtType();
  3527. }
  3528. }
  3529. FSI->setHasCXXTry(TryLoc);
  3530. return CXXTryStmt::Create(Context, TryLoc, TryBlock, Handlers);
  3531. }
  3532. StmtResult Sema::ActOnSEHTryBlock(bool IsCXXTry, SourceLocation TryLoc,
  3533. Stmt *TryBlock, Stmt *Handler) {
  3534. assert(TryBlock && Handler);
  3535. sema::FunctionScopeInfo *FSI = getCurFunction();
  3536. // SEH __try is incompatible with C++ try. Borland appears to support this,
  3537. // however.
  3538. if (!getLangOpts().Borland) {
  3539. if (FSI->FirstCXXTryLoc.isValid()) {
  3540. Diag(TryLoc, diag::err_mixing_cxx_try_seh_try);
  3541. Diag(FSI->FirstCXXTryLoc, diag::note_conflicting_try_here) << "'try'";
  3542. }
  3543. }
  3544. FSI->setHasSEHTry(TryLoc);
  3545. // Reject __try in Obj-C methods, blocks, and captured decls, since we don't
  3546. // track if they use SEH.
  3547. DeclContext *DC = CurContext;
  3548. while (DC && !DC->isFunctionOrMethod())
  3549. DC = DC->getParent();
  3550. FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(DC);
  3551. if (FD)
  3552. FD->setUsesSEHTry(true);
  3553. else
  3554. Diag(TryLoc, diag::err_seh_try_outside_functions);
  3555. // Reject __try on unsupported targets.
  3556. if (!Context.getTargetInfo().isSEHTrySupported())
  3557. Diag(TryLoc, diag::err_seh_try_unsupported);
  3558. return SEHTryStmt::Create(Context, IsCXXTry, TryLoc, TryBlock, Handler);
  3559. }
  3560. StmtResult
  3561. Sema::ActOnSEHExceptBlock(SourceLocation Loc,
  3562. Expr *FilterExpr,
  3563. Stmt *Block) {
  3564. assert(FilterExpr && Block);
  3565. if(!FilterExpr->getType()->isIntegerType()) {
  3566. return StmtError(Diag(FilterExpr->getExprLoc(),
  3567. diag::err_filter_expression_integral)
  3568. << FilterExpr->getType());
  3569. }
  3570. return SEHExceptStmt::Create(Context,Loc,FilterExpr,Block);
  3571. }
  3572. void Sema::ActOnStartSEHFinallyBlock() {
  3573. CurrentSEHFinally.push_back(CurScope);
  3574. }
  3575. void Sema::ActOnAbortSEHFinallyBlock() {
  3576. CurrentSEHFinally.pop_back();
  3577. }
  3578. StmtResult Sema::ActOnFinishSEHFinallyBlock(SourceLocation Loc, Stmt *Block) {
  3579. assert(Block);
  3580. CurrentSEHFinally.pop_back();
  3581. return SEHFinallyStmt::Create(Context, Loc, Block);
  3582. }
  3583. StmtResult
  3584. Sema::ActOnSEHLeaveStmt(SourceLocation Loc, Scope *CurScope) {
  3585. Scope *SEHTryParent = CurScope;
  3586. while (SEHTryParent && !SEHTryParent->isSEHTryScope())
  3587. SEHTryParent = SEHTryParent->getParent();
  3588. if (!SEHTryParent)
  3589. return StmtError(Diag(Loc, diag::err_ms___leave_not_in___try));
  3590. CheckJumpOutOfSEHFinally(*this, Loc, *SEHTryParent);
  3591. return new (Context) SEHLeaveStmt(Loc);
  3592. }
  3593. StmtResult Sema::BuildMSDependentExistsStmt(SourceLocation KeywordLoc,
  3594. bool IsIfExists,
  3595. NestedNameSpecifierLoc QualifierLoc,
  3596. DeclarationNameInfo NameInfo,
  3597. Stmt *Nested)
  3598. {
  3599. return new (Context) MSDependentExistsStmt(KeywordLoc, IsIfExists,
  3600. QualifierLoc, NameInfo,
  3601. cast<CompoundStmt>(Nested));
  3602. }
  3603. StmtResult Sema::ActOnMSDependentExistsStmt(SourceLocation KeywordLoc,
  3604. bool IsIfExists,
  3605. CXXScopeSpec &SS,
  3606. UnqualifiedId &Name,
  3607. Stmt *Nested) {
  3608. return BuildMSDependentExistsStmt(KeywordLoc, IsIfExists,
  3609. SS.getWithLocInContext(Context),
  3610. GetNameFromUnqualifiedId(Name),
  3611. Nested);
  3612. }
  3613. RecordDecl*
  3614. Sema::CreateCapturedStmtRecordDecl(CapturedDecl *&CD, SourceLocation Loc,
  3615. unsigned NumParams) {
  3616. DeclContext *DC = CurContext;
  3617. while (!(DC->isFunctionOrMethod() || DC->isRecord() || DC->isFileContext()))
  3618. DC = DC->getParent();
  3619. RecordDecl *RD = nullptr;
  3620. if (getLangOpts().CPlusPlus)
  3621. RD = CXXRecordDecl::Create(Context, TTK_Struct, DC, Loc, Loc,
  3622. /*Id=*/nullptr);
  3623. else
  3624. RD = RecordDecl::Create(Context, TTK_Struct, DC, Loc, Loc, /*Id=*/nullptr);
  3625. RD->setCapturedRecord();
  3626. DC->addDecl(RD);
  3627. RD->setImplicit();
  3628. RD->startDefinition();
  3629. assert(NumParams > 0 && "CapturedStmt requires context parameter");
  3630. CD = CapturedDecl::Create(Context, CurContext, NumParams);
  3631. DC->addDecl(CD);
  3632. return RD;
  3633. }
  3634. static void
  3635. buildCapturedStmtCaptureList(SmallVectorImpl<CapturedStmt::Capture> &Captures,
  3636. SmallVectorImpl<Expr *> &CaptureInits,
  3637. ArrayRef<sema::Capture> Candidates) {
  3638. for (const sema::Capture &Cap : Candidates) {
  3639. if (Cap.isThisCapture()) {
  3640. Captures.push_back(CapturedStmt::Capture(Cap.getLocation(),
  3641. CapturedStmt::VCK_This));
  3642. CaptureInits.push_back(Cap.getInitExpr());
  3643. continue;
  3644. } else if (Cap.isVLATypeCapture()) {
  3645. Captures.push_back(
  3646. CapturedStmt::Capture(Cap.getLocation(), CapturedStmt::VCK_VLAType));
  3647. CaptureInits.push_back(nullptr);
  3648. continue;
  3649. }
  3650. Captures.push_back(CapturedStmt::Capture(Cap.getLocation(),
  3651. Cap.isReferenceCapture()
  3652. ? CapturedStmt::VCK_ByRef
  3653. : CapturedStmt::VCK_ByCopy,
  3654. Cap.getVariable()));
  3655. CaptureInits.push_back(Cap.getInitExpr());
  3656. }
  3657. }
  3658. void Sema::ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
  3659. CapturedRegionKind Kind,
  3660. unsigned NumParams) {
  3661. CapturedDecl *CD = nullptr;
  3662. RecordDecl *RD = CreateCapturedStmtRecordDecl(CD, Loc, NumParams);
  3663. // Build the context parameter
  3664. DeclContext *DC = CapturedDecl::castToDeclContext(CD);
  3665. IdentifierInfo *ParamName = &Context.Idents.get("__context");
  3666. QualType ParamType = Context.getPointerType(Context.getTagDeclType(RD));
  3667. auto *Param =
  3668. ImplicitParamDecl::Create(Context, DC, Loc, ParamName, ParamType,
  3669. ImplicitParamDecl::CapturedContext);
  3670. DC->addDecl(Param);
  3671. CD->setContextParam(0, Param);
  3672. // Enter the capturing scope for this captured region.
  3673. PushCapturedRegionScope(CurScope, CD, RD, Kind);
  3674. if (CurScope)
  3675. PushDeclContext(CurScope, CD);
  3676. else
  3677. CurContext = CD;
  3678. PushExpressionEvaluationContext(
  3679. ExpressionEvaluationContext::PotentiallyEvaluated);
  3680. }
  3681. void Sema::ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
  3682. CapturedRegionKind Kind,
  3683. ArrayRef<CapturedParamNameType> Params) {
  3684. CapturedDecl *CD = nullptr;
  3685. RecordDecl *RD = CreateCapturedStmtRecordDecl(CD, Loc, Params.size());
  3686. // Build the context parameter
  3687. DeclContext *DC = CapturedDecl::castToDeclContext(CD);
  3688. bool ContextIsFound = false;
  3689. unsigned ParamNum = 0;
  3690. for (ArrayRef<CapturedParamNameType>::iterator I = Params.begin(),
  3691. E = Params.end();
  3692. I != E; ++I, ++ParamNum) {
  3693. if (I->second.isNull()) {
  3694. assert(!ContextIsFound &&
  3695. "null type has been found already for '__context' parameter");
  3696. IdentifierInfo *ParamName = &Context.Idents.get("__context");
  3697. QualType ParamType = Context.getPointerType(Context.getTagDeclType(RD))
  3698. .withConst()
  3699. .withRestrict();
  3700. auto *Param =
  3701. ImplicitParamDecl::Create(Context, DC, Loc, ParamName, ParamType,
  3702. ImplicitParamDecl::CapturedContext);
  3703. DC->addDecl(Param);
  3704. CD->setContextParam(ParamNum, Param);
  3705. ContextIsFound = true;
  3706. } else {
  3707. IdentifierInfo *ParamName = &Context.Idents.get(I->first);
  3708. auto *Param =
  3709. ImplicitParamDecl::Create(Context, DC, Loc, ParamName, I->second,
  3710. ImplicitParamDecl::CapturedContext);
  3711. DC->addDecl(Param);
  3712. CD->setParam(ParamNum, Param);
  3713. }
  3714. }
  3715. assert(ContextIsFound && "no null type for '__context' parameter");
  3716. if (!ContextIsFound) {
  3717. // Add __context implicitly if it is not specified.
  3718. IdentifierInfo *ParamName = &Context.Idents.get("__context");
  3719. QualType ParamType = Context.getPointerType(Context.getTagDeclType(RD));
  3720. auto *Param =
  3721. ImplicitParamDecl::Create(Context, DC, Loc, ParamName, ParamType,
  3722. ImplicitParamDecl::CapturedContext);
  3723. DC->addDecl(Param);
  3724. CD->setContextParam(ParamNum, Param);
  3725. }
  3726. // Enter the capturing scope for this captured region.
  3727. PushCapturedRegionScope(CurScope, CD, RD, Kind);
  3728. if (CurScope)
  3729. PushDeclContext(CurScope, CD);
  3730. else
  3731. CurContext = CD;
  3732. PushExpressionEvaluationContext(
  3733. ExpressionEvaluationContext::PotentiallyEvaluated);
  3734. }
  3735. void Sema::ActOnCapturedRegionError() {
  3736. DiscardCleanupsInEvaluationContext();
  3737. PopExpressionEvaluationContext();
  3738. CapturedRegionScopeInfo *RSI = getCurCapturedRegion();
  3739. RecordDecl *Record = RSI->TheRecordDecl;
  3740. Record->setInvalidDecl();
  3741. SmallVector<Decl*, 4> Fields(Record->fields());
  3742. ActOnFields(/*Scope=*/nullptr, Record->getLocation(), Record, Fields,
  3743. SourceLocation(), SourceLocation(), ParsedAttributesView());
  3744. PopDeclContext();
  3745. PopFunctionScopeInfo();
  3746. }
  3747. StmtResult Sema::ActOnCapturedRegionEnd(Stmt *S) {
  3748. CapturedRegionScopeInfo *RSI = getCurCapturedRegion();
  3749. SmallVector<CapturedStmt::Capture, 4> Captures;
  3750. SmallVector<Expr *, 4> CaptureInits;
  3751. buildCapturedStmtCaptureList(Captures, CaptureInits, RSI->Captures);
  3752. CapturedDecl *CD = RSI->TheCapturedDecl;
  3753. RecordDecl *RD = RSI->TheRecordDecl;
  3754. CapturedStmt *Res = CapturedStmt::Create(
  3755. getASTContext(), S, static_cast<CapturedRegionKind>(RSI->CapRegionKind),
  3756. Captures, CaptureInits, CD, RD);
  3757. CD->setBody(Res->getCapturedStmt());
  3758. RD->completeDefinition();
  3759. DiscardCleanupsInEvaluationContext();
  3760. PopExpressionEvaluationContext();
  3761. PopDeclContext();
  3762. PopFunctionScopeInfo();
  3763. return Res;
  3764. }