SemaStmt.cpp 163 KB

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