SemaStmt.cpp 181 KB

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