SemaStmt.cpp 181 KB

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